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: sync linked folders into RAG (#8014)

alkinun86b3ee185373
diff --git a/studio/backend/core/rag/config.py b/studio/backend/core/rag/config.py
index f54d7957315..76bfabfee1b 100644
--- a/studio/backend/core/rag/config.py
+++ b/studio/backend/core/rag/config.py
@@ -29,6 +29,13 @@ UPLOAD_EXTS = {".pdf", ".txt", ".md", ".markdown", ".docx", ".html", ".htm"}
# + vision work at ingest. 0 disables the cap. Default 200 MB.
MAX_UPLOAD_BYTES = int(os.environ.get("RAG_MAX_UPLOAD_BYTES", str(200 * 1024 * 1024)))
+# Linked folders use periodic full reconciliation. Metadata-only comparisons keep
+# unchanged passes cheap; caps prevent an accidentally broad folder from becoming
+# an unbounded ingestion queue.
+FOLDER_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"))
+
# Extract PDF text as layout-aware Markdown (pymupdf4llm) instead of flat text, so
# tables, headings and lists survive into chunks and retrieval. Falls back to plain
# PyMuPDF text when off, when pymupdf4llm is missing, or when extraction fails.
diff --git a/studio/backend/core/rag/folder_sync.py b/studio/backend/core/rag/folder_sync.py
new file mode 100644
index 00000000000..5bf695e5305
--- /dev/null
+++ b/studio/backend/core/rag/folder_sync.py
@@ -0,0 +1,1833 @@
+# 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."""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+import os
+import sqlite3
+import stat
+import threading
+import time
+import uuid
+from contextlib import closing
+import weakref
+from datetime import datetime, timezone
+from pathlib import Path, PurePosixPath
+
+from storage import rag_db
+from utils.paths import ensure_dir, rag_uploads_root
+
+from . import config, ingestion, job_leases, store
+
+logger = logging.getLogger(__name__)
+
+_wake = threading.Event()
+_stop = threading.Event()
+_thread: threading.Thread | None = None
+_thread_stop: threading.Event | None = None
+_thread_lock = threading.Lock()
+_worker_lock = threading.Lock()
+_worker_state = threading.local()
+_folder_locks: weakref.WeakValueDictionary[str, threading.RLock] = weakref.WeakValueDictionary()
+_scope_locks: weakref.WeakValueDictionary[str, threading.RLock] = weakref.WeakValueDictionary()
+_named_locks_lock = threading.Lock()
+_retirement_schema_lock = threading.Lock()
+_TERMINAL = {"completed", "failed"}
+_MAX_FOLDER_DEPTH = 64
+_MAX_NAMED_FAILURES = 3
+_MAX_WITHHELD_PATHS = 500
+_JOB_EVENT_KEEPALIVE_S = 4.0
+_SQLITE_INTEGER_MAX = (1 << 63) - 1
+
+
+class _SyncStopped(Exception):
+ pass
+
+
+class _LeaseLost(Exception):
+ pass
+
+
+class _FolderChanged(RuntimeError):
+ pass
+
+
+def _folder_lock(folder_id: str) -> threading.RLock:
+ with _named_locks_lock:
+ return _folder_locks.setdefault(folder_id, threading.RLock())
+
+
+def _scope_lock(scope: str) -> threading.RLock:
+ with _named_locks_lock:
+ return _scope_locks.setdefault(scope, threading.RLock())
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def now_iso() -> str:
+ """The timestamp format linked-folder rows are written and compared with."""
+ return _now()
+
+
+def _hash_file(path: str) -> str:
+ digest = hashlib.sha256()
+ with open(path, "rb") as source:
+ for block in iter(lambda: source.read(1 << 20), b""):
+ digest.update(block)
+ return digest.hexdigest()
+
+
+def _path_key(path: str) -> str:
+ return os.path.normcase(os.path.normpath(path))
+
+
+def _same_file(left: str, right: str) -> bool:
+ try:
+ return os.path.samefile(left, right)
+ except OSError:
+ return False
+
+
+def _paths_overlap(left: str, right: str) -> bool:
+ try:
+ if os.path.commonpath((left, right)) in (left, right):
+ return True
+ except ValueError:
+ pass
+ return any(_same_file(left, str(parent)) for parent in Path(right).parents) or any(
+ _same_file(right, str(parent)) for parent in Path(left).parents
+ )
+
+
+def _error_text(exc: Exception, native_path: str | None = None) -> str:
+ from utils.native_path_leases import redact_native_paths
+
+ error = redact_native_paths(str(exc) or exc.__class__.__name__)
+ if native_path:
+ error = error.replace(native_path, "<native_path>")
+ error = error.replace(os.path.normpath(native_path), "<native_path>")
+ return error
+
+
+def _is_within(root: str, path: str) -> bool:
+ try:
+ return os.path.normcase(os.path.commonpath([root, path])) == os.path.normcase(root)
+ except ValueError:
+ return False
+
+
+def validate_folder_path(path: str) -> str:
+ """Apply the existing model scan-folder policy without persisting there."""
+ if not path or not path.strip() or "\x00" in path:
+ raise ValueError("Path cannot be empty")
+ expanded = os.path.abspath(os.path.expanduser(path))
+ try:
+ if stat.S_ISLNK(os.lstat(expanded).st_mode):
+ raise ValueError("Symbolic-link folders are not allowed")
+ except OSError as exc:
+ raise ValueError("Path does not exist") from exc
+ normalized = os.path.realpath(expanded)
+ uploads_root = os.path.realpath(str(rag_uploads_root()))
+ if _paths_overlap(_path_key(normalized), _path_key(uploads_root)):
+ raise ValueError("The managed RAG uploads folder cannot be linked")
+
+ from hub.storage.scan_folders import (
+ contains_sensitive_path_component,
+ is_denied_system_path,
+ )
+ from utils.paths.external_media import is_local_filesystem_root
+
+ if not os.path.isdir(normalized):
+ raise ValueError("Path must be a directory, not a file")
+ if not os.access(normalized, os.R_OK | os.X_OK):
+ raise ValueError("Path is not readable")
+ if is_local_filesystem_root(normalized):
+ raise ValueError("The filesystem root cannot be registered")
+ try:
+ if Path(normalized) == Path.home().resolve():
+ raise ValueError("The entire home folder cannot be registered")
+ except RuntimeError:
+ pass
+ if contains_sensitive_path_component(normalized):
+ raise ValueError("Credential or configuration directories are not allowed")
+ if is_denied_system_path(normalized):
+ raise ValueError("System directories are not allowed")
+ return normalized
+
+
+def _root_identity(root: str) -> tuple[int, int]:
+ try:
+ root_stat = os.lstat(root)
+ except OSError as exc:
+ raise RuntimeError("Linked folder is unavailable") from exc
+ if stat.S_ISLNK(root_stat.st_mode) or not stat.S_ISDIR(root_stat.st_mode):
+ raise RuntimeError("Linked folder is no longer a regular directory")
+ if os.path.normcase(os.path.realpath(root)) != os.path.normcase(root):
+ raise RuntimeError("Linked folder no longer resolves to its registered path")
+ return root_stat.st_dev, root_stat.st_ino
+
+
+def _store_identity(identity: tuple[int, int]) -> tuple[int | str, int | str]:
+ return tuple(value if value <= _SQLITE_INTEGER_MAX else f"x{value:x}" for value in identity)
+
+
+def _file_identity(metadata: dict) -> tuple[int | str, int | str]:
+ return _store_identity((metadata["device"], metadata["inode"]))
+
+
+def _load_identity(device_id: int | str, file_id: int | str) -> tuple[int, int]:
+ def load(value: int | str) -> int:
+ return (
+ int(value[1:], 16) if isinstance(value, str) and value.startswith("x") else int(value)
+ )
+
+ return load(device_id), load(file_id)
+
+
+def _mount_points() -> frozenset[str]:
+ """Return known mount boundaries without assuming directory identities are unique."""
+ if os.name != "posix" or not os.path.exists("/proc/self/mountinfo"):
+ return frozenset()
+ escaped = {"\\040": " ", "\\011": "\t", "\\012": "\n", "\\134": "\\"}
+ points = set()
+ try:
+ with open("/proc/self/mountinfo", encoding = "utf-8") as mountinfo:
+ for line in mountinfo:
+ fields = line.split()
+ if len(fields) < 5:
+ continue
+ path = fields[4]
+ for encoded, decoded in escaped.items():
+ path = path.replace(encoded, decoded)
+ points.add(_path_key(os.path.realpath(path)))
+ except OSError:
+ return frozenset()
+ return frozenset(points)
+
+
+def create_folder(
+ *,
+ scope_type: str,
+ scope_id: str,
+ path: str,
+ expected_identity: tuple[int, int] | None = None,
+ name: str | None = None,
+ auto_sync: bool = True,
+) -> dict:
+ if scope_type not in {"knowledge_base", "project"}:
+ raise ValueError("Linked folders support only knowledge-base and project scopes")
+ normalized = validate_folder_path(path)
+ try:
+ root_device, root_inode = _root_identity(normalized)
+ except RuntimeError as exc:
+ raise ValueError(str(exc)) from exc
+ if expected_identity is not None and (root_device, root_inode) != expected_identity:
+ raise ValueError("Linked folder changed after it was selected")
+ scope = (
+ store.kb_scope(scope_id)
+ if scope_type == "knowledge_base"
+ else store.project_scope(scope_id)
+ )
+ folder_id = str(uuid.uuid4())
+ now = _now()
+ with _scope_lock(scope):
+ conn = rag_db.get_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ if conn.execute(
+ "SELECT 1 FROM linked_folder_retired_scopes WHERE scope=?", (scope,)
+ ).fetchone():
+ raise ValueError("The linked-folder scope no longer exists")
+ normalized_key = _path_key(normalized)
+ existing = conn.execute(
+ "SELECT * FROM linked_folders WHERE scope=?", (scope,)
+ ).fetchall()
+ for row in existing:
+ existing_key = _path_key(row["path"])
+ if existing_key == normalized_key or _same_file(row["path"], normalized):
+ if row["status"] == "retired" or row["delete_remove_index"] is not None:
+ raise ValueError("Linked folder is still being removed")
+ conn.rollback()
+ return _reauthorize_folder(row["id"], normalized, expected_identity)
+ if _paths_overlap(existing_key, normalized_key):
+ raise ValueError("Linked folders in the same scope cannot overlap")
+ try:
+ current_identity = _root_identity(normalized)
+ except RuntimeError as exc:
+ raise ValueError(str(exc)) from exc
+ if current_identity != (root_device, root_inode) or (
+ expected_identity is not None and current_identity != expected_identity
+ ):
+ raise ValueError("Linked folder changed after it was selected")
+ conn.execute(
+ "INSERT INTO linked_folders(id, scope_type, scope_id, scope, path, name, "
+ "root_device, root_inode, auto_sync, status, created_at, updated_at) "
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?)",
+ (
+ folder_id,
+ scope_type,
+ scope_id,
+ scope,
+ normalized,
+ (name or Path(normalized).name or normalized).strip(),
+ *_store_identity((root_device, root_inode)),
+ int(auto_sync),
+ "pending",
+ now,
+ now,
+ ),
+ )
+ conn.commit()
+ return dict(
+ conn.execute("SELECT * FROM linked_folders WHERE id=?", (folder_id,)).fetchone()
+ )
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+
+
+def _reauthorize_folder(
+ folder_id: str, path: str, expected_identity: tuple[int, int] | None
+) -> dict:
+ with _folder_lock(folder_id):
+ conn = rag_db.get_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ if (
+ conn.execute("SELECT 1 FROM linked_folders WHERE id=?", (folder_id,)).fetchone()
+ is None
+ ):
+ raise ValueError("Linked folder changed while it was reauthorized")
+ try:
+ identity = _root_identity(path)
+ except RuntimeError as exc:
+ raise ValueError(str(exc)) from exc
+ if expected_identity is not None and identity != expected_identity:
+ raise ValueError("Linked folder changed after it was selected")
+ conn.execute(
+ "UPDATE linked_folders SET root_device=?, root_inode=?, updated_at=? WHERE id=?",
+ (*_store_identity(identity), _now(), folder_id),
+ )
+ conn.commit()
+ return dict(
+ conn.execute("SELECT * FROM linked_folders WHERE id=?", (folder_id,)).fetchone()
+ )
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+
+
+def create_folder_with_sync(
+ *,
+ scope_type: str,
+ scope_id: str,
+ path: str,
+ expected_identity: tuple[int, int] | None = None,
+ name: str | None = None,
+ auto_sync: bool = True,
+) -> tuple[dict, str]:
+ if scope_type not in {"knowledge_base", "project"}:
+ raise ValueError("Linked folders support only knowledge-base and project scopes")
+ scope = (
+ store.kb_scope(scope_id)
+ if scope_type == "knowledge_base"
+ else store.project_scope(scope_id)
+ )
+ with _scope_lock(scope):
+ folder = create_folder(
+ scope_type = scope_type,
+ scope_id = scope_id,
+ path = path,
+ expected_identity = expected_identity,
+ name = name,
+ auto_sync = auto_sync,
+ )
+ return folder, request_sync(folder["id"])
+
+
+def get_folder(folder_id: str) -> dict | None:
+ with closing(rag_db.get_connection()) as conn:
+ row = conn.execute("SELECT * FROM linked_folders WHERE id=?", (folder_id,)).fetchone()
+ return dict(row) if row else None
+
+
+def list_folders(scope: str) -> list[dict]:
+ with closing(rag_db.get_connection()) as conn:
+ rows = conn.execute(
+ "SELECT f.*, COUNT(ff.relative_path) AS file_count, (SELECT j.id FROM "
+ "linked_folder_sync_jobs j WHERE j.folder_id=f.id AND j.status IN ('pending','running') "
+ "ORDER BY j.created_at LIMIT 1) AS active_job_id FROM linked_folders f "
+ "LEFT JOIN linked_folder_files ff ON ff.folder_id=f.id WHERE f.scope=? "
+ "GROUP BY f.id ORDER BY f.created_at",
+ (scope,),
+ ).fetchall()
+ return [dict(row) for row in rows]
+
+
+def update_folder(
+ folder_id: str,
+ *,
+ name: str | None = None,
+ auto_sync: bool | None = None,
+) -> dict:
+ with _folder_lock(folder_id):
+ return _update_folder(folder_id, name = name, auto_sync = auto_sync)
+
+
+def _update_folder(
+ folder_id: str,
+ *,
+ name: str | None = None,
+ auto_sync: bool | None = None,
+) -> dict:
+ with closing(rag_db.get_connection()) as conn:
+ row = conn.execute(
+ "SELECT status, delete_remove_index FROM linked_folders WHERE id=?", (folder_id,)
+ ).fetchone()
+ if row is None or row["status"] == "retired" or row["delete_remove_index"] is not None:
+ raise KeyError(folder_id)
+ if name is not None:
+ clean_name = name.strip()
+ if not clean_name:
+ raise ValueError("Folder name cannot be empty")
+ conn.execute(
+ "UPDATE linked_folders SET name=?, updated_at=? WHERE id=?",
+ (clean_name, _now(), folder_id),
+ )
+ if auto_sync is not None:
+ conn.execute(
+ "UPDATE linked_folders SET auto_sync=?, updated_at=? WHERE id=?",
+ (int(auto_sync), _now(), folder_id),
+ )
+ conn.commit()
+ return dict(
+ conn.execute("SELECT * FROM linked_folders WHERE id=?", (folder_id,)).fetchone()
+ )
+
+
+def _remove_snapshot(path: str | None) -> None:
+ if not path:
+ return
+ try:
+ root = os.path.realpath(str(rag_uploads_root()))
+ target = os.path.realpath(path)
+ if _is_within(root, target) and os.path.isfile(target):
+ os.remove(target)
+ except Exception:
+ logger.warning("failed to remove linked-folder snapshot", exc_info = True)
+
+
+def _remove_retired_snapshot(path: str | None) -> None:
+ """Remove a managed snapshot or raise so its retirement remains retryable."""
+ if not path:
+ return
+ root = os.path.realpath(str(rag_uploads_root()))
+ target = os.path.realpath(path)
+ if not _is_within(root, target):
+ return
+ try:
+ os.remove(target)
+ except FileNotFoundError:
+ pass
+
+
+def _delete_retired_folder(folder_id: str) -> bool | None:
+ """Finish a durable unlink once no process still owns its sync job."""
+ conn = rag_db.get_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ folder = conn.execute(
+ "SELECT delete_remove_index FROM linked_folders "
+ "WHERE id=? AND delete_remove_index IS NOT NULL",
+ (folder_id,),
+ ).fetchone()
+ if folder is None:
+ conn.rollback()
+ return None
+ if conn.execute(
+ "SELECT 1 FROM linked_folder_sync_jobs j JOIN rag_job_leases l "
+ "ON l.kind=? AND l.job_id=j.id WHERE j.folder_id=? AND l.expires_at>? LIMIT 1",
+ (job_leases.FOLDER_SYNC, folder_id, _now()),
+ ).fetchone():
+ conn.rollback()
+ return False
+ docs = conn.execute(
+ "SELECT d.id, d.stored_path FROM linked_folder_files ff "
+ "JOIN documents d ON d.id=ff.document_id WHERE ff.folder_id=?",
+ (folder_id,),
+ ).fetchall()
+ if folder["delete_remove_index"]:
+ for snapshot in dict.fromkeys(doc["stored_path"] for doc in docs):
+ _remove_retired_snapshot(snapshot)
+ conn.execute("DELETE FROM linked_folder_files WHERE folder_id=?", (folder_id,))
+ for doc in docs:
+ if folder["delete_remove_index"]:
+ store.delete_document(conn, doc["id"], commit = False)
+ else:
+ conn.execute(
+ "UPDATE documents SET linked_folder_id=NULL, linked_relative_path=NULL "
+ "WHERE id=?",
+ (doc["id"],),
+ )
+ conn.execute(
+ "DELETE FROM rag_job_leases WHERE kind=? AND job_id IN "
+ "(SELECT id FROM linked_folder_sync_jobs WHERE folder_id=?)",
+ (job_leases.FOLDER_SYNC, folder_id),
+ )
+ conn.execute("DELETE FROM linked_folder_sync_jobs WHERE folder_id=?", (folder_id,))
+ conn.execute("DELETE FROM linked_folders WHERE id=?", (folder_id,))
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+ return True
+
+
+def _reconcile_retired_folder_deletions() -> None:
+ with closing(rag_db.get_connection()) as conn:
+ folder_ids = [
+ row["id"]
+ for row in conn.execute(
+ "SELECT id FROM linked_folders WHERE delete_remove_index IS NOT NULL"
+ )
+ ]
+ for folder_id in folder_ids:
+ _delete_retired_folder(folder_id)
+
+
+def delete_folder(folder_id: str, *, remove_index: bool = True) -> bool:
+ conn = rag_db.get_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ if conn.execute("SELECT 1 FROM linked_folders WHERE id=?", (folder_id,)).fetchone() is None:
+ conn.rollback()
+ return False
+ conn.execute(
+ "UPDATE linked_folders SET auto_sync=0, status='retired', "
+ "delete_remove_index=COALESCE(delete_remove_index, ?), updated_at=? WHERE id=?",
+ (int(remove_index), _now(), folder_id),
+ )
+ conn.execute(
+ "UPDATE linked_folder_sync_jobs SET status='failed', stage='error', "
+ "error='Linked folder was removed', completed_at=? "
+ "WHERE folder_id=? AND status IN ('pending','running')",
+ (_now(), folder_id),
+ )
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+ while _delete_retired_folder(folder_id) is False:
+ time.sleep(0.05)
+ return True
+
+
+def _retirement_connection():
+ conn = rag_db.get_metadata_connection()
+ try:
+ with _retirement_schema_lock:
+ conn.execute("BEGIN IMMEDIATE")
+ conn.execute(
+ "CREATE TABLE IF NOT EXISTS linked_folder_retired_scopes ("
+ "scope TEXT NOT NULL PRIMARY KEY, retired_at TEXT NOT NULL, purged_at TEXT)"
+ )
+ rag_db.ensure_linked_folder_columns(conn)
+ conn.commit()
+ except Exception:
+ conn.close()
+ raise
+ return conn
+
+
+def _metadata_table_exists(conn, table: str) -> bool:
+ return (
+ conn.execute(
+ "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (table,)
+ ).fetchone()
+ is not None
+ )
+
+
+def _retire_scope_rows(
+ conn,
+ scope: str,
+ linked_before: str | None = None,
+) -> None:
+ folders_exist = _metadata_table_exists(conn, "linked_folders")
+ jobs_exist = folders_exist and _metadata_table_exists(conn, "linked_folder_sync_jobs")
+ conn.execute(
+ "INSERT OR IGNORE INTO linked_folder_retired_scopes(scope, retired_at) VALUES(?, ?)",
+ (scope, _now()),
+ )
+ # the ownership check and this write cannot share a transaction across two databases,
+ # so a folder another process linked after that check keeps its own state
+ bound = "" if linked_before is None else " AND created_at<=?"
+ params = () if linked_before is None else (linked_before,)
+ if folders_exist:
+ conn.execute(
+ "UPDATE linked_folders SET auto_sync=0, status='retired', "
+ f"last_error='Owning scope was removed', updated_at=? WHERE scope=?{bound}",
+ (_now(), scope, *params),
+ )
+ if jobs_exist:
+ conn.execute(
+ "UPDATE linked_folder_sync_jobs SET status='failed', stage='error', "
+ "error='Owning scope was removed', successor_kind=NULL, completed_at=? "
+ "WHERE folder_id IN (SELECT id FROM linked_folders WHERE scope=?"
+ f"{bound}) AND (status IN ('pending','running') OR successor_kind IS NOT NULL)",
+ (_now(), scope, *params),
+ )
+
+
+def retire_scope(scope: str, linked_before: str | None = None) -> None:
+ """Stop all future work, even when the vector extension cannot load."""
+ conn = _retirement_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ _retire_scope_rows(conn, scope, linked_before)
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+
+
+def retire_and_delete_kb(kb_id: str) -> bool:
+ """Atomically retire a KB scope and delete its owner row.
+
+ Document rows remain as the durable cleanup queue until
+ ``delete_retired_scope`` removes their stored files and database state.
+ """
+ scope = store.kb_scope(kb_id)
+ conn = rag_db.get_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ if store.get_kb(conn, kb_id) is None:
+ conn.rollback()
+ return False
+ _retire_scope_rows(conn, scope)
+ store.delete_kb(conn, kb_id, commit = False, delete_documents = False)
+ conn.commit()
+ return True
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+
+
+def delete_retired_scope(scope: str) -> bool:
+ """Purge an ownerless scope and retain its tombstone permanently.
+
+ Scope identifiers are treated as non-reusable lifecycle IDs. Keeping the small
+ tombstone closes late cross-database upload/link races without a distributed transaction.
+ File removal happens before database rows are discarded, so any failure remains
+ retryable from durable metadata.
+ """
+ conn = rag_db.get_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ if (
+ conn.execute(
+ "SELECT 1 FROM linked_folder_retired_scopes WHERE scope=? AND purged_at IS NULL",
+ (scope,),
+ ).fetchone()
+ is None
+ ):
+ conn.rollback()
+ return False
+ live_ingestion = conn.execute(
+ "SELECT 1 FROM ingestion_jobs j JOIN rag_job_leases l "
+ "ON l.kind=? AND l.job_id=j.id WHERE j.scope=? "
+ "AND j.status IN ('pending','running') AND l.expires_at>? LIMIT 1",
+ (job_leases.INGESTION, scope, _now()),
+ ).fetchone()
+ if live_ingestion is not None:
+ conn.rollback()
+ return False
+ live_folder_sync = conn.execute(
+ "SELECT 1 FROM linked_folder_sync_jobs j JOIN linked_folders f "
+ "ON f.id=j.folder_id JOIN rag_job_leases l "
+ "ON l.kind=? AND l.job_id=j.id WHERE f.scope=? "
+ "AND l.expires_at>? LIMIT 1",
+ (job_leases.FOLDER_SYNC, scope, _now()),
+ ).fetchone()
+ if live_folder_sync is not None:
+ conn.rollback()
+ return False
+ documents = conn.execute(
+ "SELECT id, stored_path FROM documents WHERE scope=?", (scope,)
+ ).fetchall()
+ for stored_path in dict.fromkeys(document["stored_path"] for document in documents):
+ _remove_retired_snapshot(stored_path)
+ for document in documents:
+ store.delete_document(conn, document["id"], commit = False)
+ conn.execute(
+ "DELETE FROM rag_job_leases WHERE kind=? AND job_id IN "
+ "(SELECT id FROM ingestion_jobs WHERE scope=?)",
+ (job_leases.INGESTION, scope),
+ )
+ conn.execute("DELETE FROM ingestion_jobs WHERE scope=?", (scope,))
+ conn.execute(
+ "DELETE FROM linked_folder_files WHERE folder_id IN "
+ "(SELECT id FROM linked_folders WHERE scope=?)",
+ (scope,),
+ )
+ conn.execute(
+ "DELETE FROM rag_job_leases WHERE kind=? AND job_id IN "
+ "(SELECT j.id FROM linked_folder_sync_jobs j JOIN linked_folders f "
+ "ON f.id=j.folder_id WHERE f.scope=?)",
+ (job_leases.FOLDER_SYNC, scope),
+ )
+ conn.execute(
+ "DELETE FROM linked_folder_sync_jobs WHERE folder_id IN "
+ "(SELECT id FROM linked_folders WHERE scope=?)",
+ (scope,),
+ )
+ conn.execute("DELETE FROM linked_folders WHERE scope=?", (scope,))
+ conn.execute(
+ "UPDATE linked_folder_retired_scopes SET purged_at=? WHERE scope=?",
+ (_now(), scope),
+ )
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+ return True
+
+
+def reconcile_retired_scopes(project_exists) -> dict[str, list[str]]:
+ """Retire orphaned project scopes and reap ownerless retired scopes."""
+ with closing(rag_db.get_connection()) as conn:
+ retired_scopes = {
+ row["scope"]
+ for row in conn.execute(
+ "SELECT scope FROM linked_folder_retired_scopes WHERE purged_at IS NULL"
+ )
+ }
+ project_scopes = {
+ row["scope"]
+ for row in conn.execute(
+ "SELECT scope FROM linked_folders WHERE scope_type='project' "
+ "UNION SELECT scope FROM documents WHERE project_id IS NOT NULL"
+ )
+ }
+ retired: list[str] = []
+ deleted: list[str] = []
+ restored: list[str] = []
+ for scope in sorted(project_scopes - retired_scopes):
+ project_id = scope.removeprefix("project_")
+ if not project_id:
+ continue
+ try:
+ # under the lock create_folder and upload admission take, and rechecked inside
+ # it: a project recreated with the same id must not have its new folders retired
+ with _scope_lock(scope):
+ checked_at = _now()
+ if project_exists(project_id):
+ continue
+ retire_scope(scope, checked_at)
+ retired_scopes.add(scope)
+ retired.append(scope)
+ except Exception:
+ logger.warning("failed to retire orphaned RAG scope %s", scope, exc_info = True)
+ for scope in sorted(retired_scopes):
+ try:
+ if scope.startswith("project_"):
+ project_id = scope[len("project_") :]
+ if not project_id:
+ continue
+ owner_exists = project_exists(project_id)
+ elif scope.startswith("kb_"):
+ kb_id = scope[len("kb_") :]
+ if not kb_id:
+ continue
+ with closing(rag_db.get_connection()) as owner_conn:
+ owner_exists = store.get_kb(owner_conn, kb_id) is not None
+ else:
+ continue
+ if owner_exists:
+ # the id came back, so the scope has an owner again and its retirement,
+ # which only ever meant "ownerless", must not keep gating that owner
+ if unretire_scope(scope):
+ restored.append(scope)
+ elif delete_retired_scope(scope):
+ deleted.append(scope)
+ except Exception:
+ logger.warning("failed to reconcile retired RAG scope %s", scope, exc_info = True)
+ if retired:
+ logger.info("retired %s orphaned RAG scope(s)", len(retired))
+ if deleted:
+ logger.info("deleted %s retired RAG scope(s)", len(deleted))
+ if restored:
+ logger.info("restored %s recreated RAG scope(s)", len(restored))
+ return {"retired": retired, "deleted": deleted, "restored": restored}
+
+
+def unretire_scope(scope: str) -> bool:
+ """Drop the tombstone of a scope whose owner exists again, so it can be used."""
+ with _scope_lock(scope):
+ conn = _retirement_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ removed = conn.execute(
+ "DELETE FROM linked_folder_retired_scopes WHERE scope=?", (scope,)
+ ).rowcount
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+ return bool(removed)
+
+
+def scope_retired(scope: str) -> bool:
+ with _scope_lock(scope):
+ with closing(_retirement_connection()) as conn:
+ return (
+ conn.execute(
+ "SELECT 1 FROM linked_folder_retired_scopes WHERE scope=?", (scope,)
+ ).fetchone()
+ is not None
+ )
+
+
+def scope_lock(scope: str) -> threading.RLock:
+ return _scope_lock(scope)
+
+
+def request_sync(folder_id: str, *, rebuild: bool = False) -> str:
+ with _folder_lock(folder_id):
+ return _request_sync(folder_id, rebuild = rebuild)
+
+
+def _fold_into_active_job(conn, active, kind: str) -> None:
+ """Absorb a new request into the job already queued or running for this folder.
+
+ A pending job has not scanned yet, so it can simply become the requested kind. A
+ running job already fixed its file list, so the request becomes a successor: the
+ caller's changes are only guaranteed to land in the run that follows this one.
+ """
+ if active["status"] == "pending":
+ if kind == "rebuild":
+ conn.execute(
+ "UPDATE linked_folder_sync_jobs SET kind='rebuild', successor_kind=NULL WHERE id=?",
+ (active["id"],),
+ )
+ return
+ # a queued rebuild outranks a queued sync; it covers everything a sync would
+ conn.execute(
+ "UPDATE linked_folder_sync_jobs SET successor_kind=? WHERE id=? "
+ "AND (successor_kind IS NULL OR ?='rebuild')",
+ (kind, active["id"], kind),
+ )
+
+
+def _request_sync(folder_id: str, *, rebuild: bool = False) -> str:
+ job_id = str(uuid.uuid4())
+ with closing(rag_db.get_connection()) as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ folder = conn.execute(
+ "SELECT status, delete_remove_index FROM linked_folders WHERE id=?", (folder_id,)
+ ).fetchone()
+ if (
+ folder is None
+ or folder["status"] == "retired"
+ or folder["delete_remove_index"] is not None
+ ):
+ raise KeyError(folder_id)
+ active = conn.execute(
+ "SELECT id, kind, status FROM linked_folder_sync_jobs WHERE folder_id=? "
+ "AND status IN ('pending','running') ORDER BY created_at LIMIT 1",
+ (folder_id,),
+ ).fetchone()
+ if active is not None:
+ _fold_into_active_job(conn, active, "rebuild" if rebuild else "sync")
+ conn.commit()
+ return active["id"]
+ conn.execute(
+ "INSERT INTO linked_folder_sync_jobs(id, folder_id, kind, status, stage, created_at) "
+ "VALUES(?,?,?,'pending','queued',?)",
+ (job_id, folder_id, "rebuild" if rebuild else "sync", _now()),
+ )
+ conn.commit()
+ _prune_terminal_jobs(conn)
+ _wake.set()
+ return job_id
+
+
+def _prune_terminal_jobs(conn) -> None:
+ limit = max(0, config.FOLDER_JOB_HISTORY_LIMIT)
+ conn.execute(
+ "DELETE FROM linked_folder_sync_jobs WHERE id IN ("
+ "SELECT id FROM linked_folder_sync_jobs WHERE status IN ('completed','failed') "
+ "AND successor_kind IS NULL "
+ "ORDER BY completed_at DESC, created_at DESC LIMIT -1 OFFSET ?)",
+ (limit,),
+ )
+ conn.commit()
+
+
+def get_job(job_id: str) -> dict | None:
+ with closing(rag_db.get_connection()) as conn:
+ row = conn.execute("SELECT * FROM linked_folder_sync_jobs WHERE id=?", (job_id,)).fetchone()
+ return dict(row) if row else None
+
+
+def job_events(job_id: str):
+ """Poll persisted state so streams also work after a backend restart.
+
+ Yields None as a keepalive when a pass produces no change for a while, which is what
+ lets a client tell a slow job from a proxy holding the whole response back.
+ """
+ previous = None
+ last_sent = time.monotonic()
+ while True:
+ row = get_job(job_id)
+ if row is None:
+ return
+ state = tuple(row.items())
+ if state != previous:
+ yield row
+ previous = state
+ last_sent = time.monotonic()
+ elif time.monotonic() - last_sent >= _JOB_EVENT_KEEPALIVE_S:
+ yield None
+ last_sent = time.monotonic()
+ if row["status"] in _TERMINAL:
+ return
+ time.sleep(0.5)
+
+
+def _scan(
+ root: str, expected_identity: tuple[int, int] | None = None
+) -> tuple[dict[str, dict], tuple[int, int]]:
+ from hub.storage.scan_folders import contains_sensitive_path_component, is_denied_system_path
+
+ identity = _root_identity(root)
+ if expected_identity is not None and identity != expected_identity:
+ raise RuntimeError("Linked folder root identity changed")
+
+ found: dict[str, dict] = {}
+ mount_points = _mount_points()
+ root_identities = frozenset({identity}) if identity[1] not in (None, 0) else frozenset()
+ pending = [(root, frozenset({_path_key(root)}), root_identities, 0)]
+ while pending:
+ directory, ancestor_paths, ancestor_identities, depth = pending.pop()
+ with os.scandir(directory) as entries:
+ for entry in entries:
+ full = entry.path
+ if entry.is_symlink():
+ continue
+ if entry.is_dir(follow_symlinks = False):
+ resolved = os.path.realpath(full)
+ if (
+ not _is_within(root, resolved)
+ or contains_sensitive_path_component(os.path.relpath(resolved, root))
+ or is_denied_system_path(resolved)
+ ):
+ continue
+ resolved_key = _path_key(resolved)
+ if resolved_key in ancestor_paths:
+ continue
+ directory_stat = entry.stat(follow_symlinks = False)
+ directory_identity = (directory_stat.st_dev, directory_stat.st_ino)
+ identity_usable = directory_identity[1] not in (None, 0)
+ if (
+ identity_usable
+ and directory_identity in ancestor_identities
+ and (resolved_key in mount_points or os.path.ismount(full))
+ ):
+ continue
+ if depth >= _MAX_FOLDER_DEPTH:
+ raise RuntimeError(
+ f"Folder nesting exceeds the {_MAX_FOLDER_DEPTH}-level scan limit"
+ )
+ child_identities = ancestor_identities
+ if identity_usable:
+ child_identities = ancestor_identities | {directory_identity}
+ pending.append(
+ (
+ full,
+ ancestor_paths | {resolved_key},
+ child_identities,
+ depth + 1,
+ )
+ )
+ continue
+ if not entry.is_file(follow_symlinks = False):
+ continue
+ if os.path.splitext(entry.name)[1].lower() not in config.UPLOAD_EXTS:
+ continue
+ st = entry.stat(follow_symlinks = False)
+ rel = os.path.relpath(full, root).replace(os.sep, "/")
+ found[rel] = {
+ "path": full,
+ "size_bytes": st.st_size,
+ "mtime_ns": st.st_mtime_ns,
+ "device": st.st_dev,
+ "inode": st.st_ino,
+ }
+ if config.FOLDER_MAX_FILES and len(found) > config.FOLDER_MAX_FILES:
+ raise RuntimeError(
+ f"Folder contains more than the {config.FOLDER_MAX_FILES} supported files limit"
+ )
+ if _root_identity(root) != identity:
+ raise RuntimeError("Linked folder root identity changed during scan")
+ return found, identity
+
+
+def _snapshot(root: str, metadata: dict) -> str:
+ source = metadata["path"]
+ resolved = os.path.realpath(source)
+ if not _is_within(root, resolved):
+ raise RuntimeError("File escaped the linked folder")
+ flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
+ fd = os.open(source, flags)
+ target = None
+ try:
+ ext = os.path.splitext(source)[1].lower()
+ target = ensure_dir(rag_uploads_root()) / f"linked-{uuid.uuid4().hex}{ext}"
+ before = os.fstat(fd)
+ if not stat.S_ISREG(before.st_mode):
+ raise RuntimeError("Linked source is not a regular file")
+ expected = (
+ metadata["size_bytes"],
+ metadata["mtime_ns"],
+ metadata["device"],
+ metadata["inode"],
+ )
+ actual = (before.st_size, before.st_mtime_ns, before.st_dev, before.st_ino)
+ if actual != expected:
+ raise RuntimeError("Linked source changed during reconciliation")
+ if config.MAX_UPLOAD_BYTES and before.st_size > config.MAX_UPLOAD_BYTES:
+ raise RuntimeError("Linked source exceeds the RAG file size limit")
+ with os.fdopen(fd, "rb", closefd = False) as src, open(target, "xb") as dst:
+ _copy_exact(src, dst, before.st_size)
+ after = os.fstat(fd)
+ if (after.st_size, after.st_mtime_ns, after.st_dev, after.st_ino) != expected:
+ raise RuntimeError("Linked source changed while it was copied")
+ return str(target)
+ except Exception:
+ if target is not None:
+ _remove_snapshot(str(target))
+ raise
+ finally:
+ os.close(fd)
+
+
+def _copy_exact(source, target, size: int) -> None:
+ remaining = size
+ while remaining:
+ block = source.read(min(1 << 20, remaining))
+ if not block:
+ raise RuntimeError("Linked source changed while it was copied")
+ target.write(block)
+ remaining -= len(block)
+ if source.read(1):
+ raise RuntimeError("Linked source changed while it was copied")
+
+
+def _check_running() -> None:
+ stop_event = getattr(_worker_state, "stop_event", _stop)
+ if stop_event.is_set():
+ raise _SyncStopped
+ job_id = getattr(_worker_state, "job_id", None)
+ if job_id is None:
+ return
+ with closing(rag_db.get_connection()) as conn:
+ if not job_leases.renew_owned(conn, job_leases.FOLDER_SYNC, job_id):
+ conn.rollback()
+ raise _LeaseLost
+ folder = conn.execute(
+ "SELECT f.status, f.delete_remove_index FROM linked_folder_sync_jobs j "
+ "JOIN linked_folders f ON f.id=j.folder_id WHERE j.id=?",
+ (job_id,),
+ ).fetchone()
+ if (
+ folder is None
+ or folder["status"] == "retired"
+ or folder["delete_remove_index"] is not None
+ ):
+ conn.commit()
+ raise _LeaseLost
+ conn.commit()
+
+
+def _check_root_identity(root: str, expected: tuple[int, int]) -> None:
+ try:
+ current = _root_identity(root)
+ except RuntimeError as exc:
+ raise _FolderChanged(str(exc)) from exc
+ if current != expected:
+ raise _FolderChanged("Linked folder root identity changed during reconciliation")
+
+
+def _source_reappeared(root: str, relative_path: str) -> bool:
+ """Check scanner eligibility without following a replaced path component."""
+ path = PurePosixPath(relative_path)
+ parts = path.parts
+ if (
+ not parts
+ or path.is_absolute()
+ or "\x00" in relative_path
+ or any(part == ".." for part in parts)
+ ):
+ raise _FolderChanged("Linked folder mapping has an invalid relative path")
+ current = root
+ for index, part in enumerate(parts):
+ current = os.path.join(current, part)
+ try:
+ current_stat = os.lstat(current)
+ except FileNotFoundError:
+ return False
+ except OSError as exc:
+ raise _FolderChanged("Linked source could not be rechecked") from exc
+ if stat.S_ISLNK(current_stat.st_mode):
+ return False
+ if index < len(parts) - 1:
+ if not stat.S_ISDIR(current_stat.st_mode):
+ return False
+ else:
+ return stat.S_ISREG(current_stat.st_mode)
+ return False
+
+
+def _set_job(job_id: str, **values) -> None:
+ if not values:
+ return
+ with closing(rag_db.get_connection()) as conn:
+ columns = ", ".join(f"{key}=?" for key in values)
+ conn.execute(
+ f"UPDATE linked_folder_sync_jobs SET {columns} WHERE id=?",
+ (*values.values(), job_id),
+ )
+ conn.commit()
+
+
+def _discard_document(document_id: str) -> None:
+ conn = rag_db.get_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ doc = store.get_document(conn, document_id)
+ if doc is not None:
+ _remove_retired_snapshot(doc.get("stored_path"))
+ store.delete_document(conn, document_id, commit = False)
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+
+
+def _install_mapping(
+ folder: dict, rel: str, metadata: dict, document_id: str, content_hash: str
+) -> None:
+ replaced: list[str] = []
+ conn = rag_db.get_connection()
+ try:
+ old_rows = conn.execute(
+ "SELECT ff.document_id, d.stored_path FROM linked_folder_files ff "
+ "LEFT JOIN documents d ON d.id=ff.document_id "
+ "WHERE ff.folder_id=? AND ff.relative_path=?",
+ (folder["id"], rel),
+ ).fetchall()
+ conn.execute("BEGIN IMMEDIATE")
+ conn.execute(
+ "INSERT INTO linked_folder_files(folder_id, relative_path, size_bytes, mtime_ns, "
+ "device, inode, document_id, synced_at, content_hash) VALUES(?,?,?,?,?,?,?,?,?) "
+ "ON CONFLICT(folder_id, relative_path) DO UPDATE SET size_bytes=excluded.size_bytes, "
+ "mtime_ns=excluded.mtime_ns, device=excluded.device, inode=excluded.inode, "
+ "document_id=excluded.document_id, synced_at=excluded.synced_at, "
+ "content_hash=excluded.content_hash",
+ (
+ folder["id"],
+ rel,
+ metadata["size_bytes"],
+ metadata["mtime_ns"],
+ *_file_identity(metadata),
+ document_id,
+ _now(),
+ content_hash,
+ ),
+ )
+ for old in old_rows:
+ if old["document_id"] != document_id:
+ store.delete_document(conn, old["document_id"], commit = False)
+ replaced.append(old["stored_path"])
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+ # Only after the commit: a rollback here restores a live searchable document,
+ # unlike the delete paths where the surviving row is the retry queue.
+ for stored_path in replaced:
+ _remove_snapshot(stored_path)
+
+
+def _update_mapping_metadata(folder_id: str, rel: str, metadata: dict, content_hash: str) -> None:
+ with closing(rag_db.get_connection()) as conn:
+ conn.execute(
+ "UPDATE linked_folder_files SET size_bytes=?, mtime_ns=?, device=?, inode=?, "
+ "content_hash=?, synced_at=? WHERE folder_id=? AND relative_path=?",
+ (
+ metadata["size_bytes"],
+ metadata["mtime_ns"],
+ *_file_identity(metadata),
+ content_hash,
+ _now(),
+ folder_id,
+ rel,
+ ),
+ )
+ conn.commit()
+
+
+def _delete_mapping(folder_id: str, rel: str) -> None:
+ conn = rag_db.get_connection()
+ try:
+ row = conn.execute(
+ "SELECT ff.document_id, d.stored_path FROM linked_folder_files ff "
+ "LEFT JOIN documents d ON d.id=ff.document_id "
+ "WHERE ff.folder_id=? AND ff.relative_path=?",
+ (folder_id, rel),
+ ).fetchone()
+ if row is None:
+ return
+ conn.execute("BEGIN IMMEDIATE")
+ conn.execute(
+ "DELETE FROM linked_folder_files WHERE folder_id=? AND relative_path=?",
+ (folder_id, rel),
+ )
+ store.delete_document(conn, row["document_id"], commit = False)
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+ # After the commit, as in _install_mapping: a rollback here restores a live
+ # document, and an auto_sync=0 folder may not reconcile again for a long time.
+ _remove_snapshot(row["stored_path"])
+
+
+def _rename_mapping(folder_id: str, old_rel: str, new_rel: str) -> None:
+ with closing(rag_db.get_connection()) as conn:
+ row = conn.execute(
+ "SELECT document_id FROM linked_folder_files WHERE folder_id=? AND relative_path=?",
+ (folder_id, old_rel),
+ ).fetchone()
+ if row is None:
+ return
+ conn.execute(
+ "UPDATE linked_folder_files SET relative_path=?, synced_at=? "
+ "WHERE folder_id=? AND relative_path=?",
+ (new_rel, _now(), folder_id, old_rel),
+ )
+ conn.execute(
+ "UPDATE documents SET filename=?, linked_relative_path=? WHERE id=?",
+ (new_rel, new_rel, row["document_id"]),
+ )
+ conn.commit()
+
+
+def _load_withheld(folder: dict) -> set[str]:
+ try:
+ stored = json.loads(folder.get("withheld_paths") or "[]")
+ except ValueError:
+ return set()
+ return {path for path in stored if isinstance(path, str)} if isinstance(stored, list) else set()
+
+
+def _store_withheld(folder_id: str, withheld: set[str]) -> None:
+ # truncation only shortens a grace pass, so the cap can never block a removal
+ capped = sorted(withheld)[:_MAX_WITHHELD_PATHS]
+ with closing(rag_db.get_connection()) as conn:
+ conn.execute(
+ "UPDATE linked_folders SET withheld_paths=? WHERE id=?",
+ (json.dumps(capped) if capped else None, folder_id),
+ )
+ conn.commit()
+
+
+def _failure_summary(failures: list[str]) -> str | None:
+ """Name the files that could not be indexed, so the folder error is actionable."""
+ if not failures:
+ return None
+ named = ", ".join(sorted(failures)[:_MAX_NAMED_FAILURES])
+ remainder = len(failures) - _MAX_NAMED_FAILURES
+ if remainder > 0:
+ named = f"{named} and {remainder} more"
+ return f"{len(failures)} file(s) could not be indexed ({named})"
+
+
+def _reconcile_folder(job_id: str) -> None:
+ """Run one complete reconciliation; called serially by the coordinator."""
+ _check_running()
+ with closing(rag_db.get_connection()) as conn:
+ row = conn.execute("SELECT * FROM linked_folder_sync_jobs WHERE id=?", (job_id,)).fetchone()
+ if (
+ row is None
+ or row["status"] != "running"
+ or not job_leases.owned_by_this_process(conn, job_leases.FOLDER_SYNC, job_id)
+ ):
+ return
+ job = dict(row)
+ folder = get_folder(job["folder_id"])
+ if folder is None or folder["status"] == "retired" or folder["delete_remove_index"] is not None:
+ _set_job(
+ job_id,
+ status = "failed",
+ stage = "error",
+ error = "Linked folder not found" if folder is None else "Owning scope was removed",
+ completed_at = _now(),
+ )
+ return
+ embedding_model = config.effective_embedding_model()
+ with closing(rag_db.get_connection()) as conn:
+ conn.execute(
+ "UPDATE linked_folders SET status='syncing', last_error=NULL, updated_at=? WHERE id=?",
+ (_now(), folder["id"]),
+ )
+ conn.commit()
+ try:
+ _check_running()
+ expected_identity = _load_identity(folder["root_device"], folder["root_inode"])
+ current, scanned_identity = _scan(folder["path"], expected_identity)
+ _check_running()
+ except (_SyncStopped, _LeaseLost):
+ raise
+ except Exception as exc:
+ # A partial/unavailable scan is never authoritative for deletion.
+ error = _error_text(exc, folder["path"])
+ _set_job(job_id, status = "failed", stage = "error", error = error, completed_at = _now())
+ with closing(rag_db.get_connection()) as conn:
+ conn.execute(
+ "UPDATE linked_folders SET status='error', last_error=?, updated_at=? WHERE id=?",
+ (error, _now(), folder["id"]),
+ )
+ conn.commit()
+ _prune_terminal_jobs(conn)
+ return
+
+ with closing(rag_db.get_connection()) as conn:
+ known = {
+ row["relative_path"]: dict(row)
+ for row in conn.execute(
+ "SELECT * FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchall()
+ }
+
+ rebuild = job["kind"] == "rebuild"
+ missing = set(known) - set(current)
+ new = set(current) - set(known)
+ renamed = 0
+ materially_changed = {
+ rel
+ for rel in set(current) & set(known)
+ if current[rel]["size_bytes"] != known[rel]["size_bytes"]
+ or current[rel]["mtime_ns"] != known[rel]["mtime_ns"]
+ or _file_identity(current[rel]) != (known[rel]["device"], known[rel]["inode"])
+ }
+ changed = set(current) & set(known) if rebuild else materially_changed
+ work = sorted(new | changed)
+ missing_by_content: dict[tuple[str, str], list[str]] = {}
+ if not rebuild:
+ for rel in sorted(missing):
+ content_hash = known[rel].get("content_hash")
+ if content_hash:
+ key = (content_hash, os.path.splitext(rel)[1].lower())
+ missing_by_content.setdefault(key, []).append(rel)
+ already_withheld = _load_withheld(folder)
+ total = len(work) + len(missing)
+ _set_job(job_id, stage = "ingesting", discovered = len(current), renamed = renamed)
+ added = changed_count = 0
+ failures: 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,
+ )
+ 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,
+ )
+ _set_job(
+ job_id,
+ added = added,
+ changed = changed_count,
+ failed = len(failures),
+ progress = (index + 1) / max(total, 1),
+ )
+
+ deleted = 0
+ for rel in sorted(missing - withheld):
+ _check_running()
+ _check_root_identity(folder["path"], scanned_identity)
+ if _source_reappeared(folder["path"], rel):
+ raise _FolderChanged("Linked source reappeared during reconciliation")
+ _check_root_identity(folder["path"], scanned_identity)
+ _delete_mapping(folder["id"], rel)
+ deleted += 1
+ _set_job(
+ job_id,
+ deleted = deleted,
+ progress = (len(work) + deleted) / max(total, 1),
+ )
+
+ _check_running()
+ _store_withheld(folder["id"], withheld)
+ error = _failure_summary(failures)
+ _set_job(
+ job_id,
+ status = "completed" if error is None else "failed",
+ stage = "done" if error is None else "error",
+ progress = 1.0,
+ error = error,
+ completed_at = _now(),
+ )
+ with closing(rag_db.get_connection()) as conn:
+ conn.execute(
+ "UPDATE linked_folders SET status=?, last_error=?, last_scan_at=?, updated_at=? "
+ "WHERE id=? AND delete_remove_index IS NULL",
+ ("ready" if error is None else "error", error, _now(), _now(), folder["id"]),
+ )
+ conn.commit()
+ _prune_terminal_jobs(conn)
+
+
+def _fail_job(job_id: str, exc: Exception) -> None:
+ job = get_job(job_id)
+ folder = get_folder(job["folder_id"]) if job is not None else None
+ error = _error_text(exc, folder["path"] if folder else None)
+ _set_job(job_id, status = "failed", stage = "error", error = error, completed_at = _now())
+ if job is None:
+ return
+ with closing(rag_db.get_connection()) as conn:
+ conn.execute(
+ "UPDATE linked_folders SET status='error', last_error=?, updated_at=? WHERE id=?",
+ (error, _now(), job["folder_id"]),
+ )
+ conn.commit()
+ _prune_terminal_jobs(conn)
+
+
+def _pause_job(job_id: str) -> None:
+ job = get_job(job_id)
+ if job is None:
+ return
+ _set_job(job_id, status = "pending", stage = "queued", started_at = None)
+ with closing(rag_db.get_connection()) as conn:
+ conn.execute(
+ "UPDATE linked_folders SET status='ready', updated_at=? WHERE id=?",
+ (_now(), job["folder_id"]),
+ )
+ conn.commit()
+
+
+def _queue_successor(job_id: str) -> None:
+ """Hand a finished job's queued follow-up request to the next run."""
+ conn = rag_db.get_connection()
+ queued = False
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ job = conn.execute(
+ "SELECT folder_id, successor_kind, status FROM linked_folder_sync_jobs WHERE id=?",
+ (job_id,),
+ ).fetchone()
+ if job and job["successor_kind"] and job["status"] not in ("pending", "running"):
+ active = conn.execute(
+ "SELECT id, kind, status FROM linked_folder_sync_jobs WHERE folder_id=? "
+ "AND status IN ('pending','running') ORDER BY created_at LIMIT 1",
+ (job["folder_id"],),
+ ).fetchone()
+ if active is None:
+ conn.execute(
+ "INSERT INTO linked_folder_sync_jobs"
+ "(id, folder_id, kind, status, stage, created_at) "
+ "VALUES(?,?,?,'pending','queued',?)",
+ (str(uuid.uuid4()), job["folder_id"], job["successor_kind"], _now()),
+ )
+ else:
+ _fold_into_active_job(conn, active, job["successor_kind"])
+ conn.execute(
+ "UPDATE linked_folder_sync_jobs SET successor_kind=NULL WHERE id=?", (job_id,)
+ )
+ queued = True
+ conn.commit()
+ if queued:
+ _prune_terminal_jobs(conn)
+ finally:
+ conn.close()
+ if queued:
+ _wake.set()
+
+
+def reconcile_folder(job_id: str) -> None:
+ """Reconcile and persist a terminal folder state for every unexpected failure."""
+ if _claim_job(job_id) is None:
+ # The caller may already hold an activated claim (the queue claims before
+ # dispatching); drop it here or the heartbeat renews it for the process
+ # lifetime and an unlink waits on a job that will never run.
+ job_leases.release(job_leases.FOLDER_SYNC, job_id)
+ return
+ lease_lost = False
+ _worker_state.job_id = job_id
+ try:
+ _reconcile_folder(job_id)
+ except _LeaseLost:
+ lease_lost = True
+ except _SyncStopped:
+ _pause_job(job_id)
+ except Exception as exc:
+ logger.exception("linked-folder job %s failed unexpectedly", job_id)
+ _fail_job(job_id, exc)
+ finally:
+ try:
+ if not lease_lost:
+ _queue_successor(job_id)
+ finally:
+ del _worker_state.job_id
+ job_leases.release(job_leases.FOLDER_SYNC, job_id)
+
+
+def _enqueue_periodic() -> None:
+ rag_db.reconcile_orphaned_ingestion_jobs()
+ _reconcile_retired_folder_deletions()
+ with closing(rag_db.get_connection()) as conn:
+ now = _now()
+ conn.execute("BEGIN IMMEDIATE")
+ rows = conn.execute(
+ "SELECT id FROM linked_folders WHERE auto_sync=1 AND status!='retired' "
+ "AND delete_remove_index IS NULL"
+ ).fetchall()
+ for row in rows:
+ conn.execute(
+ "INSERT OR IGNORE INTO linked_folder_sync_jobs"
+ "(id, folder_id, kind, status, stage, created_at) "
+ "VALUES(?,?,'sync','pending','queued',?)",
+ (str(uuid.uuid4()), row["id"], now),
+ )
+ _reap_orphaned_documents(conn, now)
+ conn.commit()
+ _prune_terminal_jobs(conn)
+
+
+def _claim_job(job_id: str) -> tuple[str, str] | None:
+ with closing(rag_db.get_connection()) as conn:
+ conn.execute("BEGIN IMMEDIATE")
+ row = conn.execute(
+ "SELECT id, folder_id, status FROM linked_folder_sync_jobs WHERE id=?", (job_id,)
+ ).fetchone()
+ if row is None or row["status"] not in ("pending", "running"):
+ conn.rollback()
+ return None
+ if row["status"] == "running":
+ if not job_leases.owned_by_this_process(
+ conn, job_leases.FOLDER_SYNC, job_id
+ ) and not job_leases.claim(conn, job_leases.FOLDER_SYNC, job_id):
+ conn.rollback()
+ return None
+ else:
+ if not job_leases.claim(conn, job_leases.FOLDER_SYNC, job_id):
+ conn.rollback()
+ return None
+ conn.execute(
+ "UPDATE linked_folder_sync_jobs SET status='running', stage='scanning', "
+ "started_at=COALESCE(started_at, ?) WHERE id=? AND status='pending'",
+ (_now(), job_id),
+ )
+ conn.commit()
+ try:
+ job_leases.activate(job_leases.FOLDER_SYNC, job_id)
+ except Exception:
+ with closing(rag_db.get_connection()) as conn:
+ conn.execute(
+ "UPDATE linked_folder_sync_jobs SET status='pending', stage='queued' WHERE id=?",
+ (job_id,),
+ )
+ conn.commit()
+ job_leases.release(job_leases.FOLDER_SYNC, job_id)
+ raise
+ return job_id, row["folder_id"]
+
+
+def _next_job() -> tuple[str, str] | None:
+ with closing(rag_db.get_connection()) as conn:
+ row = conn.execute(
+ "SELECT j.id FROM linked_folder_sync_jobs j WHERE j.status='pending' OR "
+ "(j.status='running' AND NOT EXISTS (SELECT 1 FROM rag_job_leases l "
+ "WHERE l.kind=? AND l.job_id=j.id AND l.expires_at>?)) "
+ "ORDER BY CASE j.status WHEN 'running' THEN 0 ELSE 1 END, j.created_at LIMIT 1",
+ (job_leases.FOLDER_SYNC, _now()),
+ ).fetchone()
+ return _claim_job(row["id"]) if row else None
+
+
+def _worker(stop_event: threading.Event | None = None, project_exists = None) -> None:
+ global _thread, _thread_stop
+ stop_event = stop_event or _stop
+ try:
+ with _worker_lock:
+ _worker_state.stop_event = stop_event
+ while not stop_event.is_set():
+ try:
+ _recover_startup_state()
+ if project_exists is not None:
+ reconcile_retired_scopes(project_exists)
+ _enqueue_periodic()
+ break
+ except Exception:
+ logger.warning("linked-folder worker initialization failed", exc_info = True)
+ stop_event.wait(1.0)
+ while not stop_event.is_set():
+ try:
+ job = _next_job()
+ except Exception:
+ # Writer-lock contention must not retire the only worker: the
+ # initialization and periodic paths already back off and retry.
+ logger.warning("linked-folder queue selection failed", exc_info = True)
+ stop_event.wait(1.0)
+ continue
+ if job:
+ job_id, folder_id = job
+ try:
+ reconcile_folder(job_id)
+ except Exception as exc:
+ logger.exception("linked-folder job %s failed unexpectedly", job_id)
+ _fail_job(job_id, exc)
+ continue
+ _wake.wait(max(1.0, config.FOLDER_SYNC_INTERVAL_S))
+ _wake.clear()
+ if not stop_event.is_set():
+ try:
+ if project_exists is not None:
+ reconcile_retired_scopes(project_exists)
+ _enqueue_periodic()
+ except Exception:
+ logger.warning("linked-folder periodic scheduling failed", exc_info = True)
+ finally:
+ _worker_state.stop_event = None
+ with _thread_lock:
+ if _thread is threading.current_thread():
+ _thread = None
+ _thread_stop = None
+
+
+def _recover_startup_state() -> None:
+ with closing(rag_db.get_connection()) as conn:
+ now = _now()
+ conn.execute("BEGIN IMMEDIATE")
+ conn.execute(
+ "UPDATE linked_folder_sync_jobs SET status='pending', stage='queued', "
+ "error=NULL WHERE status='running' AND NOT EXISTS ("
+ "SELECT 1 FROM rag_job_leases l WHERE l.kind=? "
+ "AND l.job_id=linked_folder_sync_jobs.id AND l.expires_at>?)",
+ (job_leases.FOLDER_SYNC, now),
+ )
+ conn.execute("DELETE FROM rag_job_leases WHERE expires_at<=?", (now,))
+ successor_handoffs = conn.execute(
+ "SELECT id FROM linked_folder_sync_jobs WHERE status IN ('completed','failed') "
+ "AND successor_kind IS NOT NULL"
+ ).fetchall()
+ _reap_orphaned_documents(conn, now)
+ conn.commit()
+ for job in successor_handoffs:
+ _queue_successor(job["id"])
+
+
+def _reap_orphaned_documents(conn, now: str) -> None:
+ """Drop folder-owned documents left unreferenced by a crash before mapping.
+
+ Also runs periodically: a process that survives the crash reclaims the
+ expired job and reindexes the file, so its own startup pass is long past.
+ Anything still leased by a live ingestion or folder sync is left alone.
+ """
+ orphans = conn.execute(
+ "SELECT d.id, d.stored_path FROM documents d "
+ "WHERE d.linked_folder_id IS NOT NULL AND NOT EXISTS "
+ "(SELECT 1 FROM linked_folder_files ff WHERE ff.document_id=d.id) AND NOT EXISTS ("
+ "SELECT 1 FROM ingestion_jobs j JOIN rag_job_leases l "
+ "ON l.kind=? AND l.job_id=j.id WHERE j.document_id=d.id "
+ "AND j.status IN ('pending','running') AND l.expires_at>?) AND NOT EXISTS ("
+ "SELECT 1 FROM linked_folder_sync_jobs sj JOIN rag_job_leases sl "
+ "ON sl.kind=? AND sl.job_id=sj.id WHERE sj.folder_id=d.linked_folder_id "
+ "AND sl.expires_at>?)",
+ (job_leases.INGESTION, now, job_leases.FOLDER_SYNC, now),
+ ).fetchall()
+ for orphan in orphans:
+ _remove_retired_snapshot(orphan["stored_path"])
+ store.delete_document(conn, orphan["id"], commit = False)
+ conn.execute(
+ "DELETE FROM rag_job_leases WHERE kind=? AND job_id IN "
+ "(SELECT id FROM ingestion_jobs WHERE document_id=?)",
+ (job_leases.INGESTION, orphan["id"]),
+ )
+ conn.execute("DELETE FROM ingestion_jobs WHERE document_id=?", (orphan["id"],))
+
+
+def start_auto_sync(
+ *,
+ admission_lock = None,
+ admit = None,
+ project_exists = None,
+) -> bool:
+ global _thread, _thread_stop
+ try:
+ if not rag_db.rag_available():
+ return False
+ except sqlite3.OperationalError:
+ # The worker retries initialization, so transient database contention must
+ # not turn a one-shot startup preflight into a process-lifetime outage.
+ pass
+ with _thread_lock:
+ retired = _thread if _thread is not None and _thread.is_alive() else None
+ if retired is not None and not _stop.is_set():
+ return False
+
+ def launch() -> bool:
+ global _thread, _thread_stop
+ with _thread_lock:
+ if _thread is not None and _thread.is_alive() and not _stop.is_set():
+ return False
+ stop_event = threading.Event()
+ _stop.clear()
+ _thread_stop = stop_event
+ _thread = threading.Thread(
+ target = _worker,
+ args = (stop_event, project_exists),
+ daemon = True,
+ name = "rag-folder-sync",
+ )
+ _thread.start()
+ return True
+
+ if admission_lock is None:
+ return launch()
+ with admission_lock:
+ if admit is not None and not admit():
+ return False
+ return launch()
+
+
+def stop_auto_sync(timeout: float = 2.0) -> None:
+ _stop.set()
+ _wake.set()
+ with _thread_lock:
+ thread = _thread
+ stop_event = _thread_stop
+ if stop_event is not None:
+ stop_event.set()
+ if thread is not None:
+ thread.join(timeout = timeout)
diff --git a/studio/backend/core/rag/ingestion.py b/studio/backend/core/rag/ingestion.py
index 2f56f2602c2..5c2a11f00fa 100644
--- a/studio/backend/core/rag/ingestion.py
+++ b/studio/backend/core/rag/ingestion.py
@@ -16,12 +16,13 @@ import threading
from storage import rag_db
-from . import captioner, chunking, config, embeddings, parsers, store
+from . import captioner, chunking, config, embeddings, job_leases, parsers, store
logger = logging.getLogger(__name__)
# Per-job event queues, drained by job_events; ``None`` ends the stream.
_jobs: dict[str, "queue.Queue"] = {}
+_workers: dict[str, threading.Thread] = {}
_jobs_lock = threading.Lock()
_EMBED_BATCH = 64 # bounds peak memory
@@ -85,6 +86,8 @@ def _set_job(
def _progress(conn, job_id: str, stage: str, progress: float) -> None:
+ if not job_leases.renew_owned(conn, job_leases.INGESTION, job_id):
+ raise job_leases.JobLeaseLost("Ingestion job lease was reclaimed")
_set_job(conn, job_id, status = "running", stage = stage, progress = progress)
_emit(job_id, {"type": "progress", "stage": stage, "progress": progress})
@@ -202,8 +205,9 @@ def _run(
caption: bool | None = None,
replaces: tuple[str, str | None] | None = None,
) -> None:
- conn = rag_db.get_connection()
+ conn = None
try:
+ conn = rag_db.get_connection()
_progress(conn, job_id, "parsing", 0.1)
pages = parsers.parse(stored_path)
is_pdf = stored_path.lower().endswith(".pdf")
@@ -258,6 +262,9 @@ def _run(
# needs the same guard as the chunk write below.
if _abort_if_document_deleted(conn, job_id, document_id):
return
+ # inside the write transaction the guard opened, as _progress does
+ if not job_leases.renew_owned(conn, job_leases.INGESTION, job_id):
+ raise job_leases.JobLeaseLost("Ingestion job lease was reclaimed")
store.set_document_status(conn, document_id, "completed", num_chunks = 0)
_replace_old_document(conn, replaces, stored_path, document_id)
_set_job(conn, job_id, status = "completed", stage = "done", progress = 1.0)
@@ -290,16 +297,24 @@ def _run(
_set_job(conn, job_id, status = "completed", stage = "done", progress = 1.0)
_emit(job_id, {"type": "complete", "num_chunks": len(chunks)})
+ except job_leases.JobLeaseLost:
+ logger.info("ingestion job %s stopped after its lease was reclaimed", job_id)
except Exception as exc: # noqa: BLE001 - report any failure to the client
logger.exception("ingestion job %s failed", job_id)
try:
+ if conn is None:
+ conn = rag_db.get_connection()
store.set_document_status(conn, document_id, "failed", error = str(exc))
_set_job(conn, job_id, status = "failed", stage = "error", error = str(exc))
except Exception: # noqa: BLE001
logger.exception("failed to record ingestion failure for job %s", job_id)
_emit(job_id, {"type": "error", "stage": "error", "error": str(exc)})
finally:
- conn.close()
+ if conn is not None:
+ conn.close()
+ job_leases.release(job_leases.INGESTION, job_id)
+ with _jobs_lock:
+ _workers.pop(job_id, None)
_emit(job_id, None)
@@ -314,6 +329,10 @@ def start_ingestion(
model_name: str | None = None,
ocr: bool | None = None,
caption: bool | None = None,
+ dedupe: bool = True,
+ linked_folder_id: str | None = None,
+ linked_relative_path: str | None = None,
+ background: bool = True,
) -> 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
@@ -328,12 +347,21 @@ def start_ingestion(
sha = _sha256_file(stored_path)
conn = rag_db.get_connection()
try:
+ # Serialize admission with durable scope retirement across backend
+ # processes. The job lease is committed in the same transaction as the
+ # document, so cleanup never observes an unowned in-flight document.
+ conn.execute("BEGIN IMMEDIATE")
+ if conn.execute(
+ "SELECT 1 FROM linked_folder_retired_scopes WHERE scope=?", (scope,)
+ ).fetchone():
+ conn.rollback()
+ raise RuntimeError("Owning scope is being deleted")
effective_model = model_name or config.effective_embedding_model()
# (old_document_id, old_stored_path) replaced by this upload; deleted by
# the worker only after the replacement completes, so a failed re-index
# never destroys the still-searchable original.
replaces: tuple[str, str | None] | None = None
- existing = store.document_by_hash(conn, scope, sha)
+ existing = store.document_by_hash(conn, scope, sha) if dedupe else None
if existing is not None:
doc = store.get_document(conn, existing)
empty_completed = (
@@ -365,9 +393,10 @@ def start_ingestion(
)
_emit(job_id, None)
return existing, job_id
- for failed in store.failed_documents_by_hash(conn, scope, sha):
- store.delete_document(conn, failed["id"])
- _remove_upload(failed.get("stored_path"), keep_path = stored_path)
+ if dedupe:
+ for failed in store.failed_documents_by_hash(conn, scope, sha):
+ store.delete_document(conn, failed["id"], commit = False)
+ _remove_upload(failed.get("stored_path"), keep_path = stored_path)
document_id = store.create_document(
conn,
@@ -380,24 +409,91 @@ def start_ingestion(
status = "pending",
stored_path = stored_path,
embedding_model = effective_model,
+ linked_folder_id = linked_folder_id,
+ linked_relative_path = linked_relative_path,
+ commit = False,
)
job_id = _new_job(conn, document_id, scope)
finally:
conn.close()
- with _jobs_lock:
- _jobs[job_id] = queue.Queue()
- threading.Thread(
- target = _run,
- # effective_model (not the raw model_name) pins the embedder for the
- # whole job: a Settings change mid-ingestion must not switch tokenizer
- # or embedder between batches of one document.
- args = (job_id, document_id, scope, stored_path, effective_model, ocr, caption, replaces),
- daemon = True,
- ).start()
+ try:
+ job_leases.activate(job_leases.INGESTION, job_id)
+ with _jobs_lock:
+ _jobs[job_id] = queue.Queue()
+ args = (
+ job_id,
+ document_id,
+ scope,
+ stored_path,
+ effective_model,
+ ocr,
+ caption,
+ replaces,
+ )
+ if not background:
+ _run(*args)
+ return document_id, job_id
+ worker = threading.Thread(
+ target = _run,
+ # effective_model (not the raw model_name) pins the embedder for the
+ # whole job: a Settings change mid-ingestion must not switch tokenizer
+ # or embedder between batches of one document.
+ args = args,
+ daemon = True,
+ )
+ with _jobs_lock:
+ _workers[job_id] = worker
+ worker.start()
+ except Exception:
+ with _jobs_lock:
+ _workers.pop(job_id, None)
+ job_leases.release(job_leases.INGESTION, job_id)
+ fail_stalled_job(job_id, "Ingestion worker could not start")
+ raise
return document_id, job_id
+def job_worker_alive(job_id: str) -> bool:
+ """Return whether this process still has a live worker for a persisted job."""
+ with _jobs_lock:
+ worker = _workers.get(job_id)
+ return worker is not None and worker.is_alive()
+
+
+def fail_stalled_job(job_id: str, error: str) -> bool:
+ """Fail a nonterminal job only after its in-process worker has exited."""
+ if job_worker_alive(job_id):
+ return False
+ conn = rag_db.get_connection()
+ try:
+ conn.execute("BEGIN IMMEDIATE")
+ row = conn.execute(
+ "SELECT document_id, status FROM ingestion_jobs WHERE id=?", (job_id,)
+ ).fetchone()
+ if row is None or row["status"] in _TERMINAL_JOB_STATUSES:
+ conn.rollback()
+ return False
+ conn.execute(
+ "UPDATE documents SET status='failed', error=? "
+ "WHERE id=? AND status IN ('pending','running')",
+ (error, row["document_id"]),
+ )
+ conn.execute(
+ "UPDATE ingestion_jobs SET status='failed', stage='error', error=? WHERE id=?",
+ (error, job_id),
+ )
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+ finally:
+ conn.close()
+ _emit(job_id, {"type": "error", "stage": "error", "error": error})
+ _emit(job_id, None)
+ return True
+
+
def _new_job(
conn,
document_id: str,
@@ -423,6 +519,9 @@ def _new_job(
datetime.now(timezone.utc).isoformat(),
),
)
+ if status not in _TERMINAL_JOB_STATUSES:
+ if not job_leases.claim(conn, job_leases.INGESTION, job_id):
+ raise RuntimeError("Could not claim ingestion job")
conn.commit()
return job_id
@@ -443,6 +542,24 @@ def _reap_finished_jobs() -> None:
_jobs.pop(jid, None)
+def delete_terminal_job(job_id: str) -> bool:
+ """Remove a consumed internal job without racing an active ingestion worker."""
+ conn = rag_db.get_connection()
+ try:
+ cursor = conn.execute(
+ "DELETE FROM ingestion_jobs WHERE id=? AND status IN ('completed','failed')",
+ (job_id,),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+ if cursor.rowcount:
+ with _jobs_lock:
+ _jobs.pop(job_id, None)
+ return True
+ return False
+
+
def job_events(job_id: str):
"""Yield job events for SSE; ends when the worker signals completion.
diff --git a/studio/backend/core/rag/job_leases.py b/studio/backend/core/rag/job_leases.py
new file mode 100644
index 00000000000..93f529106d7
--- /dev/null
+++ b/studio/backend/core/rag/job_leases.py
@@ -0,0 +1,131 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Renewable SQLite leases for RAG work shared by multiple backend processes."""
+
+from __future__ import annotations
+
+import logging
+import threading
+import uuid
+from datetime import datetime, timedelta, timezone
+
+from storage import rag_db
+
+logger = logging.getLogger(__name__)
+
+INGESTION = "ingestion"
+FOLDER_SYNC = "folder_sync"
+
+_OWNER_ID = str(uuid.uuid4())
+_LEASE_SECONDS = 30
+_HEARTBEAT_SECONDS = 5
+_active: set[tuple[str, str]] = set()
+_lock = threading.Lock()
+_wake = threading.Event()
+_thread: threading.Thread | None = None
+
+
+class JobLeaseLost(RuntimeError):
+ pass
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _deadline() -> str:
+ return (datetime.now(timezone.utc) + timedelta(seconds = _LEASE_SECONDS)).isoformat()
+
+
+def claim(conn, kind: str, job_id: str) -> bool:
+ """Claim an unleased or expired job inside the caller's transaction."""
+ cursor = conn.execute(
+ "INSERT INTO rag_job_leases(kind, job_id, owner_id, expires_at) VALUES(?,?,?,?) "
+ "ON CONFLICT(kind, job_id) DO UPDATE SET owner_id=excluded.owner_id, "
+ "expires_at=excluded.expires_at WHERE rag_job_leases.owner_id=excluded.owner_id "
+ "OR rag_job_leases.expires_at<=?",
+ (kind, job_id, _OWNER_ID, _deadline(), _now()),
+ )
+ return cursor.rowcount == 1
+
+
+def owned_by_this_process(conn, kind: str, job_id: str) -> bool:
+ return (
+ conn.execute(
+ "SELECT 1 FROM rag_job_leases WHERE kind=? AND job_id=? AND owner_id=? "
+ "AND expires_at>?",
+ (kind, job_id, _OWNER_ID, _now()),
+ ).fetchone()
+ is not None
+ )
+
+
+def renew_owned(conn, kind: str, job_id: str) -> bool:
+ """Renew only if no other process reclaimed the job."""
+ cursor = conn.execute(
+ "UPDATE rag_job_leases SET expires_at=? WHERE kind=? AND job_id=? AND owner_id=?",
+ (_deadline(), kind, job_id, _OWNER_ID),
+ )
+ return cursor.rowcount == 1
+
+
+def activate(kind: str, job_id: str) -> None:
+ """Renew a committed claim until the local worker releases it."""
+ global _thread
+ with _lock:
+ _active.add((kind, job_id))
+ if _thread is None or not _thread.is_alive():
+ try:
+ _thread = threading.Thread(target = _heartbeat, daemon = True)
+ _thread.start()
+ except Exception:
+ _thread = None
+ _active.discard((kind, job_id))
+ raise
+ _wake.set()
+
+
+def release(kind: str, job_id: str) -> None:
+ """Stop renewal and remove this process's persisted claim."""
+ with _lock:
+ _active.discard((kind, job_id))
+ try:
+ conn = rag_db.get_connection()
+ try:
+ conn.execute(
+ "DELETE FROM rag_job_leases WHERE kind=? AND job_id=? AND owner_id=?",
+ (kind, job_id, _OWNER_ID),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+ except Exception:
+ logger.warning("failed to release RAG job lease", exc_info = True)
+
+
+def _heartbeat() -> None:
+ while True:
+ with _lock:
+ active = tuple(_active)
+ if not active:
+ _wake.wait()
+ _wake.clear()
+ continue
+ try:
+ conn = rag_db.get_connection()
+ try:
+ deadline = _deadline()
+ for kind, job_id in active:
+ conn.execute(
+ "UPDATE rag_job_leases SET expires_at=? "
+ "WHERE kind=? AND job_id=? AND owner_id=?",
+ (deadline, kind, job_id, _OWNER_ID),
+ )
+ conn.commit()
+ finally:
+ conn.close()
+ except Exception:
+ logger.warning("failed to renew RAG job leases", exc_info = True)
+ _wake.wait(_HEARTBEAT_SECONDS)
+ _wake.clear()
diff --git a/studio/backend/core/rag/store.py b/studio/backend/core/rag/store.py
index 1165b6bb0e7..1e31bef1f8d 100644
--- a/studio/backend/core/rag/store.py
+++ b/studio/backend/core/rag/store.py
@@ -85,16 +85,32 @@ def get_kb(conn: sqlite3.Connection, kb_id: str) -> dict | None:
return dict(row) if row else None
-def delete_kb(conn: sqlite3.Connection, kb_id: str) -> None:
- """Delete a knowledge base and every document (+ chunks) under it."""
- scope = kb_scope(kb_id)
- doc_ids = [
- r["id"] for r in conn.execute("SELECT id FROM documents WHERE scope=?", (scope,)).fetchall()
- ]
- for doc_id in doc_ids:
- delete_document(conn, doc_id)
- conn.execute("DELETE FROM knowledge_bases WHERE id=?", (kb_id,))
- conn.commit()
+def delete_kb(
+ conn: sqlite3.Connection,
+ kb_id: str,
+ *,
+ commit: bool = True,
+ delete_documents: bool = True,
+) -> None:
+ """Delete a knowledge base, optionally retaining documents for durable cleanup."""
+ try:
+ if commit:
+ conn.execute("BEGIN IMMEDIATE")
+ scope = kb_scope(kb_id)
+ if delete_documents:
+ doc_ids = [
+ r["id"]
+ for r in conn.execute("SELECT id FROM documents WHERE scope=?", (scope,)).fetchall()
+ ]
+ for doc_id in doc_ids:
+ delete_document(conn, doc_id, commit = False)
+ conn.execute("DELETE FROM knowledge_bases WHERE id=?", (kb_id,))
+ if commit:
+ conn.commit()
+ except Exception:
+ if commit:
+ conn.rollback()
+ raise
def create_document(
@@ -110,11 +126,15 @@ def create_document(
stored_path: str | None = None,
document_id: str | None = None,
embedding_model: str | None = None,
+ linked_folder_id: str | None = None,
+ linked_relative_path: str | None = None,
+ commit: bool = True,
) -> str:
document_id = document_id or str(uuid.uuid4())
conn.execute(
"INSERT INTO documents(id, scope, kb_id, thread_id, project_id, filename, sha256, "
- "status, stored_path, created_at, embedding_model) VALUES(?,?,?,?,?,?,?,?,?,?,?)",
+ "status, stored_path, created_at, embedding_model, linked_folder_id, "
+ "linked_relative_path) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
(
document_id,
scope,
@@ -127,9 +147,12 @@ def create_document(
stored_path,
_now(),
embedding_model,
+ linked_folder_id,
+ linked_relative_path,
),
)
- conn.commit()
+ if commit:
+ conn.commit()
return document_id
@@ -151,8 +174,10 @@ def set_document_status(
def list_documents(conn: sqlite3.Connection, scope: str) -> list[dict]:
rows = conn.execute(
"SELECT id, scope, kb_id, thread_id, project_id, filename, sha256, status, error, "
- "num_chunks, created_at "
- "FROM documents WHERE scope=? ORDER BY created_at DESC",
+ "num_chunks, created_at, linked_folder_id "
+ "FROM documents d WHERE scope=? AND NOT EXISTS "
+ "(SELECT 1 FROM linked_folder_retired_scopes r WHERE r.scope=d.scope) "
+ "ORDER BY created_at DESC",
(scope,),
).fetchall()
return [dict(r) for r in rows]
@@ -162,8 +187,10 @@ def list_all_documents(conn: sqlite3.Connection) -> list[dict]:
"""Every uploaded document across all scopes (KBs, threads, projects)."""
rows = conn.execute(
"SELECT id, scope, kb_id, thread_id, project_id, filename, sha256, status, error, "
- "num_chunks, stored_path, created_at "
- "FROM documents ORDER BY created_at DESC"
+ "num_chunks, stored_path, created_at, linked_folder_id "
+ "FROM documents d WHERE NOT EXISTS "
+ "(SELECT 1 FROM linked_folder_retired_scopes r WHERE r.scope=d.scope) "
+ "ORDER BY created_at DESC"
).fetchall()
return [dict(r) for r in rows]
@@ -173,9 +200,20 @@ def get_document(conn: sqlite3.Connection, document_id: str) -> dict | None:
return dict(row) if row else None
+def get_visible_document(conn: sqlite3.Connection, document_id: str) -> dict | None:
+ """Return a document only while its owning scope is available to readers."""
+ row = conn.execute(
+ "SELECT d.* FROM documents d WHERE d.id=? AND NOT EXISTS "
+ "(SELECT 1 FROM linked_folder_retired_scopes r WHERE r.scope=d.scope)",
+ (document_id,),
+ ).fetchone()
+ return dict(row) if row else None
+
+
def document_by_hash(conn: sqlite3.Connection, scope: str, sha256: str) -> str | None:
row = conn.execute(
"SELECT id FROM documents WHERE scope=? AND sha256=? AND status!='failed' "
+ "AND linked_folder_id IS NULL "
"ORDER BY created_at DESC LIMIT 1",
(scope, sha256),
).fetchone()
@@ -184,7 +222,8 @@ def document_by_hash(conn: sqlite3.Connection, scope: str, sha256: str) -> str |
def failed_documents_by_hash(conn: sqlite3.Connection, scope: str, sha256: str) -> list[dict]:
rows = conn.execute(
- "SELECT id, stored_path FROM documents WHERE scope=? AND sha256=? AND status='failed'",
+ "SELECT id, stored_path FROM documents WHERE scope=? AND sha256=? AND status='failed' "
+ "AND linked_folder_id IS NULL",
(scope, sha256),
).fetchall()
return [dict(r) for r in rows]
@@ -236,7 +275,12 @@ def add_chunks(
conn.commit()
-def delete_document(conn: sqlite3.Connection, document_id: str) -> None:
+def delete_document(
+ conn: sqlite3.Connection,
+ document_id: str,
+ *,
+ commit: bool = True,
+) -> None:
"""Remove a document and all its chunks (+ fts + vec rows)."""
ids = [
r["id"]
@@ -251,7 +295,8 @@ def delete_document(conn: sqlite3.Connection, document_id: str) -> None:
conn.execute("DELETE FROM chunks_vec WHERE chunk_id=?", (chunk_id,))
conn.execute("DELETE FROM chunks WHERE document_id=?", (document_id,))
conn.execute("DELETE FROM documents WHERE id=?", (document_id,))
- conn.commit()
+ if commit:
+ conn.commit()
def search_lexical(conn: sqlite3.Connection, scope, query: str, k: int):
@@ -265,8 +310,15 @@ def search_lexical(conn: sqlite3.Connection, scope, query: str, k: int):
return []
placeholders = ",".join("?" * len(scopes))
rows = conn.execute(
- f"SELECT chunk_id, bm25(chunks_fts) AS s FROM chunks_fts "
- f"WHERE chunks_fts MATCH ? AND scope IN ({placeholders}) ORDER BY s LIMIT ?",
+ f"SELECT chunks_fts.chunk_id, bm25(chunks_fts) AS s FROM chunks_fts "
+ f"JOIN chunks c ON c.id=chunks_fts.chunk_id "
+ f"JOIN documents d ON d.id=c.document_id "
+ f"WHERE chunks_fts MATCH ? AND chunks_fts.scope IN ({placeholders}) "
+ f"AND NOT EXISTS "
+ f"(SELECT 1 FROM linked_folder_retired_scopes r WHERE r.scope=d.scope) "
+ f"AND (d.linked_folder_id IS NULL OR EXISTS "
+ f"(SELECT 1 FROM linked_folder_files ff WHERE ff.document_id=d.id)) "
+ f"ORDER BY s LIMIT ?",
(mq, *scopes, k),
).fetchall()
# bm25() is negative (more negative = better); flip to higher-is-better.
@@ -295,25 +347,32 @@ def search_dense(
# table cannot answer new-model queries (vec0 errors on the MATCH).
return []
# Over-fetch when filtering so stale-model hits don't starve the top-k.
- fetch = k * 3 if embedding_model else k
+ fetch = max(k * 3, k + 10)
out: list[tuple[str, float]] = []
for s in _scopes(scope):
+ if conn.execute(
+ "SELECT 1 FROM linked_folder_retired_scopes WHERE scope=?", (s,)
+ ).fetchone():
+ continue
rows = conn.execute(
"SELECT chunk_id, distance FROM chunks_vec "
"WHERE scope=? AND embedding MATCH ? ORDER BY distance LIMIT ?",
(s, _f32(vector), fetch),
).fetchall()
out.extend((r["chunk_id"], 1.0 - r["distance"]) for r in rows)
- if embedding_model and out:
+ if out:
ids = [cid for cid, _ in out]
placeholders = ",".join("?" * len(ids))
valid = {
r["id"]
for r in conn.execute(
f"SELECT c.id FROM chunks c JOIN documents d ON d.id=c.document_id "
- f"WHERE c.id IN ({placeholders}) "
- f"AND (d.embedding_model IS NULL OR d.embedding_model=?)",
- (*ids, embedding_model),
+ f"WHERE c.id IN ({placeholders}) AND NOT EXISTS "
+ f"(SELECT 1 FROM linked_folder_retired_scopes r WHERE r.scope=d.scope) "
+ f"AND (d.linked_folder_id IS NULL OR EXISTS "
+ f"(SELECT 1 FROM linked_folder_files ff WHERE ff.document_id=d.id)) "
+ f"AND (? IS NULL OR d.embedding_model IS NULL OR d.embedding_model=?)",
+ (*ids, embedding_model, embedding_model),
).fetchall()
}
out = [t for t in out if t[0] in valid]
@@ -330,7 +389,10 @@ def chunks_by_id(conn: sqlite3.Connection, ids) -> dict:
f"SELECT c.id, c.text, c.document_id, c.chunk_index, c.page_number, "
f"c.source_page_index, d.filename "
f"FROM chunks c JOIN documents d ON d.id=c.document_id "
- f"WHERE c.id IN ({placeholders})",
+ f"WHERE c.id IN ({placeholders}) AND NOT EXISTS "
+ f"(SELECT 1 FROM linked_folder_retired_scopes r WHERE r.scope=d.scope) "
+ f"AND (d.linked_folder_id IS NULL OR EXISTS "
+ f"(SELECT 1 FROM linked_folder_files ff WHERE ff.document_id=d.id))",
list(ids),
).fetchall()
return {r["id"]: r for r in rows}
@@ -349,6 +411,10 @@ def all_chunks_for_scope(conn: sqlite3.Connection, scope) -> list[dict]:
f"c.token_count, d.filename, d.created_at "
f"FROM chunks c JOIN documents d ON d.id=c.document_id "
f"WHERE c.scope IN ({placeholders}) AND d.status='completed' "
+ f"AND NOT EXISTS "
+ f"(SELECT 1 FROM linked_folder_retired_scopes r WHERE r.scope=d.scope) "
+ f"AND (d.linked_folder_id IS NULL OR EXISTS "
+ f"(SELECT 1 FROM linked_folder_files ff WHERE ff.document_id=d.id)) "
f"ORDER BY d.created_at, c.document_id, c.chunk_index",
list(scopes),
).fetchall()
@@ -367,7 +433,11 @@ def scope_token_estimate(conn: sqlite3.Connection, scope) -> int:
f"SELECT COALESCE(SUM(CASE WHEN c.token_count > 0 THEN c.token_count "
f"ELSE MAX(1, length(COALESCE(c.text, '')) / 4) END), 0) AS total "
f"FROM chunks c JOIN documents d ON d.id=c.document_id "
- f"WHERE c.scope IN ({placeholders}) AND d.status='completed'",
+ f"WHERE c.scope IN ({placeholders}) AND d.status='completed' "
+ f"AND NOT EXISTS "
+ f"(SELECT 1 FROM linked_folder_retired_scopes r WHERE r.scope=d.scope) "
+ f"AND (d.linked_folder_id IS NULL OR EXISTS "
+ f"(SELECT 1 FROM linked_folder_files ff WHERE ff.document_id=d.id))",
list(scopes),
).fetchone()
return int(row["total"] or 0)
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 442f4d90069..a1328708463 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -563,6 +563,25 @@ def _post_warm_retired(generation: Optional[int]) -> bool:
return True
+def _start_linked_folder_auto_sync(generation: Optional[int]) -> None:
+ # A real lifespan worker carries a generation; direct calls without one are tests.
+ if generation is None:
+ return
+ try:
+ from core.rag.folder_sync import start_auto_sync
+ from storage.studio_db import get_chat_project
+ start_auto_sync(
+ admission_lock = _post_warm_lock,
+ admit = lambda: _post_warm_generation == generation,
+ project_exists = lambda project_id: get_chat_project(project_id) is not None,
+ )
+ except Exception as exc:
+ import structlog as _structlog
+ _structlog.get_logger(__name__).warning(
+ "linked-folder auto-sync failed at startup: %s", exc
+ )
+
+
def _post_warm_background_work(generation: Optional[int] = None) -> None:
"""Stack-dependent startup work, run after the coordinated warm.
@@ -592,8 +611,12 @@ def _post_warm_background_work(generation: Optional[int] = None) -> None:
import structlog as _structlog
_structlog.get_logger(__name__).debug("mlx autorepair skipped: %s", _mlx_exc)
+ if _post_warm_retired(generation):
+ return
+ _start_linked_folder_auto_sync(generation)
+
# Only the RAG warm is gated: it pulls sentence-transformers/transformers/torch. MLX
- # autorepair has its own opt-out, and gating it would leave a broken MLX Mac chat-only.
+ # autorepair and linked-folder scheduling have their own lifecycles.
if os.environ.get(DISABLE_ENV_VAR) == "1":
return
@@ -725,6 +748,11 @@ async def lifespan(app: FastAPI):
# Before any shutdown await: a warm finishing during one would still read the lifespan as current.
_stop_post_warm_thread()
+ try:
+ from core.rag.folder_sync import stop_auto_sync
+ stop_auto_sync()
+ except Exception as exc:
+ _lifespan_log.warning("linked-folder auto-sync failed at shutdown: %s", exc)
# Same for the coordinated warm: retiring its epoch stops it at the next stage boundary.
# run_lifespan_shutdown() also invalidates, but only after several awaits, through which the
diff --git a/studio/backend/routes/chat_history.py b/studio/backend/routes/chat_history.py
index 6e0f8548b4a..fa0cb1ead6c 100644
--- a/studio/backend/routes/chat_history.py
+++ b/studio/backend/routes/chat_history.py
@@ -8,6 +8,7 @@ SQLite-backed handlers are sync defs unless they also perform asynchronous clean
mixed handlers explicitly send their database transaction through Starlette's threadpool.
"""
+import asyncio
import sqlite3
from typing import Annotated, Any, Literal, Optional
@@ -719,6 +720,23 @@ def patch_project(
return ChatProject(**project)
+def _delete_project_rag_sources(project_id: str) -> None:
+ """Retire an ownerless project scope and reap it when RAG is available."""
+ from storage import rag_db
+ from core.rag import folder_sync, store as rag_store
+
+ scope = rag_store.project_scope(project_id)
+ # a project id is reusable, and the tombstone outlives the scope, so retiring one that
+ # another client already recreated would permanently disable RAG for the new project
+ with folder_sync.scope_lock(scope):
+ checked_at = folder_sync.now_iso()
+ if get_chat_project(project_id) is not None:
+ return
+ folder_sync.retire_scope(scope, checked_at)
+ if rag_db.rag_available():
+ folder_sync.delete_retired_scope(scope)
+
+
@router.delete("/projects/{project_id}", response_model = ChatProjectDeleted)
async def delete_project(
project_id: str,
@@ -731,12 +749,32 @@ async def delete_project(
# Rows first, files last: a member chat can still be running a tool in the
# workspace, and its cwd disappearing mid-call either kills the call or
# leaves what it writes next in a directory no project owns.
- project = await run_in_threadpool(lambda: delete_chat_project(project_id, delete_files = False))
+ try:
+ project = await run_in_threadpool(
+ lambda: delete_chat_project(project_id, delete_files = False)
+ )
+ except Exception:
+ # the row transaction may still have committed, and an ownerless scope has to be
+ # retired by someone; periodic reconciliation is the fallback if this also fails
+ try:
+ if await run_in_threadpool(get_chat_project, project_id) is None:
+ await run_in_threadpool(_delete_project_rag_sources, project_id)
+ except Exception: # noqa: BLE001 - preserve the original deletion error
+ logger.warning(
+ "failed to delete RAG sources for committed project %s", project_id, exc_info = True
+ )
+ raise
if project is None:
raise HTTPException(
status_code = 404,
detail = f"Project {project_id} not found",
)
+ # before any workspace work: the row is already gone, so a later failure must not
+ # leave the scope owned by nothing
+ try:
+ await run_in_threadpool(_delete_project_rag_sources, project_id)
+ except Exception: # noqa: BLE001 - source cleanup must not block project deletion
+ logger.warning("failed to delete RAG sources for project %s", project_id, exc_info = True)
# The transaction is the only authority on membership and it runs first, so
# a chat moved in just before is deleted and one moved out survives. An
# earlier listing would stop a chat that is still there.
@@ -859,35 +897,6 @@ async def delete_project(
# Each member chat had its own sandbox for anything it wrote before joining
# the project, and deleting the project removes the only records of them.
_, sandboxes_kept = await _remove_sandboxes(member_ids, delete_files)
- # Best-effort: drop the project's RAG sources (lazy import keeps RAG optional).
- try:
- import os
-
- from storage import rag_db
- if rag_db.RAG_AVAILABLE:
- from core.rag import store as rag_store
- from utils.paths import rag_uploads_root
-
- uploads = os.path.realpath(str(rag_uploads_root()))
- conn = rag_db.get_connection()
- try:
- scope = rag_store.project_scope(project_id)
- for doc in rag_store.list_documents(conn, scope):
- full = rag_store.get_document(conn, doc["id"]) or {}
- rag_store.delete_document(conn, doc["id"])
- stored = full.get("stored_path")
- # Also remove the uploaded file; confined to the uploads root.
- if stored:
- target = os.path.realpath(stored)
- if (
- os.path.isfile(target)
- and os.path.commonpath([uploads, target]) == uploads
- ):
- os.remove(target)
- finally:
- conn.close()
- except Exception: # noqa: BLE001 - source cleanup must not block project deletion
- logger.warning("failed to delete RAG sources for project %s", project_id, exc_info = True)
# Those folders are reachable from nothing now, so the caller is told which
# ones survived and can offer the delete once.
return ChatProjectDeleted(**project, sandboxes_kept = sandboxes_kept)
diff --git a/studio/backend/routes/rag.py b/studio/backend/routes/rag.py
index ed0b0e1e9bc..1a4b77b7a20 100644
--- a/studio/backend/routes/rag.py
+++ b/studio/backend/routes/rag.py
@@ -33,7 +33,7 @@ from fastapi.responses import FileResponse, StreamingResponse
from pydantic import BaseModel, Field
from auth.authentication import get_current_subject
-from core.rag import config, ingestion, retrieval, store
+from core.rag import config, folder_sync, ingestion, retrieval, store
from storage import rag_db
from utils.paths import ensure_dir, rag_uploads_root
@@ -211,6 +211,15 @@ def _remove_stored_upload(stored_path: str | None) -> None:
logger.warning("failed to remove RAG upload %s", stored_path, exc_info = True)
+def _is_managed_preview_path(stored_path: str) -> bool:
+ uploads = os.path.realpath(str(rag_uploads_root()))
+ try:
+ common = os.path.commonpath([uploads, os.path.realpath(stored_path)])
+ return os.path.normcase(common) == os.path.normcase(uploads)
+ except ValueError:
+ return False
+
+
def _doc_view(row: dict) -> dict:
return {
"id": row["id"],
@@ -221,6 +230,8 @@ def _doc_view(row: dict) -> dict:
"kbId": row.get("kb_id"),
"threadId": row.get("thread_id"),
"projectId": row.get("project_id"),
+ "linkedFolderId": row.get("linked_folder_id"),
+ "managed": bool(row.get("linked_folder_id")),
"createdAt": row.get("created_at"),
}
@@ -245,6 +256,120 @@ class SearchRequest(BaseModel):
mode: str = "hybrid" # hybrid | lexical | dense
+class LinkFolderRequest(BaseModel):
+ name: str | None = Field(default = None, alias = "displayName", max_length = 200)
+ auto_sync: bool = Field(default = True, alias = "autoSync")
+ native_path_lease: str = Field(alias = "nativePathLease", min_length = 1)
+
+
+class UpdateFolderRequest(BaseModel):
+ name: str | None = Field(default = None, max_length = 200)
+ auto_sync: bool | None = Field(default = None, alias = "autoSync")
+
+
+def _resolve_linked_folder_path(
+ native_path_lease: str, *, verifier = None
+) -> tuple[str, tuple[int, int]]:
+ """Resolve a desktop grant; the injectable verifier keeps resolution unit-testable."""
+ from utils.native_path_leases import NativePathLeaseError, verify_native_path_lease
+
+ verify = verifier or verify_native_path_lease
+ try:
+ grant = verify(
+ native_path_lease,
+ operation = "link-documents",
+ expected_kind = "document-folder",
+ expected_path_type = "directory",
+ )
+ device_id = getattr(grant, "device_id", None)
+ file_id = getattr(grant, "file_id", None)
+ if device_id is None or file_id is None:
+ raise NativePathLeaseError("Native folder grant has no stable identity.")
+ return (
+ folder_sync.validate_folder_path(str(grant.canonical_path)),
+ (device_id, file_id),
+ )
+ except NativePathLeaseError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from exc
+ except ValueError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from exc
+
+
+def _folder_view(row: dict) -> dict:
+ status = (
+ "syncing"
+ if row["status"] == "syncing"
+ else "error"
+ if row["status"] in {"error", "retired"}
+ else "idle"
+ )
+ return {
+ "id": row["id"],
+ "displayName": row["name"],
+ "scopeType": row["scope_type"],
+ "scopeId": row["scope_id"],
+ "status": status,
+ "error": row.get("last_error"),
+ "lastSyncedAt": row.get("last_scan_at"),
+ "documentCount": row.get("file_count", 0),
+ "activeJobId": row.get("active_job_id"),
+ "scopeName": row.get("scope_name"),
+ "createdAt": row["created_at"],
+ }
+
+
+def _scope_for_owner(scope_type: str, scope_id: str) -> str:
+ return (
+ store.kb_scope(scope_id)
+ if scope_type == "knowledge_base"
+ else store.project_scope(scope_id)
+ )
+
+
+def _require_scope_owner(scope_type: str, scope_id: str) -> None:
+ if scope_type == "knowledge_base":
+ conn = _rag_connection()
+ try:
+ exists = store.get_kb(conn, scope_id) is not None
+ finally:
+ conn.close()
+ detail = "Knowledge base not found"
+ else:
+ from storage.studio_db import get_chat_project
+ exists = get_chat_project(scope_id) is not None
+ detail = "Project not found"
+ if not exists:
+ raise HTTPException(status_code = 404, detail = detail)
+
+
+def _require_document_owner(conn: sqlite3.Connection, document: dict) -> None:
+ if document.get("kb_id") and store.get_kb(conn, document["kb_id"]) is None:
+ raise HTTPException(status_code = 404, detail = "Document not found")
+ if document.get("project_id"):
+ from storage.studio_db import get_chat_project
+ if get_chat_project(document["project_id"]) is None:
+ raise HTTPException(status_code = 404, detail = "Document not found")
+
+
+def _create_linked_folder(scope_type: str, scope_id: str, payload: LinkFolderRequest) -> dict:
+ path, signed_identity = _resolve_linked_folder_path(payload.native_path_lease)
+ try:
+ with folder_sync.scope_lock(_scope_for_owner(scope_type, scope_id)):
+ _require_scope_owner(scope_type, scope_id)
+ folder, job_id = folder_sync.create_folder_with_sync(
+ scope_type = scope_type,
+ scope_id = scope_id,
+ path = path,
+ expected_identity = signed_identity,
+ name = payload.name,
+ auto_sync = payload.auto_sync,
+ )
+ except ValueError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from exc
+ job = folder_sync.get_job(job_id)
+ return {"linkedFolder": _folder_view(folder), "job": _folder_job_view(job)}
+
+
@router.get("/knowledge-bases")
def list_knowledge_bases(subject: str = Depends(get_current_subject)) -> dict:
try:
@@ -326,14 +451,20 @@ def update_knowledge_base(
@router.delete("/knowledge-bases/{kb_id}")
def delete_knowledge_base(kb_id: str, subject: str = Depends(get_current_subject)) -> dict:
_require_rag()
- conn = _rag_connection()
+ with _rag_unavailable_as_503():
+ deleted = folder_sync.retire_and_delete_kb(kb_id)
+ if not deleted:
+ raise HTTPException(status_code = 404, detail = "Knowledge base not found")
try:
- if store.get_kb(conn, kb_id) is None:
- raise HTTPException(status_code = 404, detail = "Knowledge base not found")
- store.delete_kb(conn, kb_id)
- return {"ok": True}
- finally:
- conn.close()
+ folder_sync.delete_retired_scope(store.kb_scope(kb_id))
+ except Exception:
+ logger.warning("failed to delete retired knowledge-base scope %s", kb_id, exc_info = True)
+ return {"ok": True}
+
+
+def _raise_if_scope_retired(scope: str, detail: str = "Knowledge base is being deleted") -> None:
+ if folder_sync.scope_retired(scope):
+ raise HTTPException(status_code = 409, detail = detail)
@router.post("/knowledge-bases/{kb_id}/documents")
@@ -352,11 +483,20 @@ async def upload_kb_document(
raise HTTPException(status_code = 404, detail = "Knowledge base not found")
finally:
conn.close()
+ scope = store.kb_scope(kb_id)
+ _raise_if_scope_retired(scope)
stored_path, filename = _resolve_document_upload(file, native_path_lease)
- with _rag_unavailable_as_503(stored_path):
- document_id, job_id = ingestion.start_ingestion(
- store.kb_scope(kb_id), kb_id, None, filename, stored_path, ocr = ocr, caption = caption
- )
+ 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
+ )
+ except Exception:
+ _remove_stored_upload(stored_path)
+ raise
return {"documentId": document_id, "jobId": job_id, "filename": filename}
@@ -371,6 +511,17 @@ def list_kb_documents(kb_id: str, subject: str = Depends(get_current_subject)) -
conn.close()
[email protected]("/knowledge-bases/{kb_id}/linked-folders")
+def link_kb_folder(
+ kb_id: str,
+ payload: LinkFolderRequest,
+ subject: str = Depends(get_current_subject),
+) -> dict:
+ _require_rag()
+ _require_scope_owner("knowledge_base", kb_id)
+ return _create_linked_folder("knowledge_base", kb_id, payload)
+
+
@router.post("/threads/{thread_id}/documents")
async def upload_thread_document(
thread_id: str,
@@ -434,18 +585,27 @@ async def upload_project_document(
if get_chat_project(project_id) is None:
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)
- with _rag_unavailable_as_503(stored_path):
- document_id, job_id = ingestion.start_ingestion(
- store.project_scope(project_id),
- None,
- None,
- filename,
- stored_path,
- project_id = project_id,
- ocr = ocr,
- caption = caption,
- )
+ try:
+ with folder_sync.scope_lock(scope):
+ _require_scope_owner("project", project_id)
+ _raise_if_scope_retired(scope, "Project is being deleted")
+ with _rag_unavailable_as_503(stored_path):
+ document_id, job_id = ingestion.start_ingestion(
+ scope,
+ None,
+ None,
+ filename,
+ stored_path,
+ project_id = project_id,
+ ocr = ocr,
+ caption = caption,
+ )
+ except Exception:
+ _remove_stored_upload(stored_path)
+ raise
# the project delete runs in the threadpool and can commit after the check above, once its own
# RAG cleanup has already listed the project's documents
if get_chat_project(project_id) is None:
@@ -457,6 +617,7 @@ async def upload_project_document(
@router.get("/projects/{project_id}/documents")
def list_project_documents(project_id: str, subject: str = Depends(get_current_subject)) -> dict:
_require_rag()
+ _require_scope_owner("project", project_id)
conn = _rag_connection()
try:
docs = store.list_documents(conn, store.project_scope(project_id))
@@ -465,6 +626,109 @@ def list_project_documents(project_id: str, subject: str = Depends(get_current_s
conn.close()
[email protected]("/projects/{project_id}/linked-folders")
+def link_project_folder(
+ project_id: str,
+ payload: LinkFolderRequest,
+ subject: str = Depends(get_current_subject),
+) -> dict:
+ _require_rag()
+ _require_scope_owner("project", project_id)
+ return _create_linked_folder("project", project_id, payload)
+
+
[email protected]("/linked-folders")
+def list_linked_folders(
+ scope_type: str | None = Query(default = None),
+ scope_id: str | None = Query(default = None),
+ subject: str = Depends(get_current_subject),
+) -> dict:
+ _require_rag()
+ if bool(scope_type) != bool(scope_id):
+ raise HTTPException(
+ status_code = 400, detail = "scope_type and scope_id must be provided together"
+ )
+ if scope_type:
+ if scope_type not in {"knowledge_base", "project"}:
+ raise HTTPException(status_code = 400, detail = "Unsupported linked-folder scope")
+ scope = (
+ store.kb_scope(scope_id)
+ if scope_type == "knowledge_base"
+ else store.project_scope(scope_id)
+ )
+ rows = folder_sync.list_folders(scope)
+ else:
+ conn = rag_db.get_connection()
+ try:
+ scopes = [
+ row["scope"] for row in conn.execute("SELECT DISTINCT scope FROM linked_folders")
+ ]
+ kb_names = {row["id"]: row["name"] for row in store.list_kbs(conn)}
+ finally:
+ conn.close()
+ from storage.studio_db import list_chat_projects
+
+ project_names = {
+ row["id"]: row["name"] for row in list_chat_projects(include_archived = True)
+ }
+ rows = [row for scope in scopes for row in folder_sync.list_folders(scope)]
+ for row in rows:
+ names = kb_names if row["scope_type"] == "knowledge_base" else project_names
+ row["scope_name"] = names.get(row["scope_id"])
+ rows = [row for row in rows if row["scope_name"] is not None]
+ return {"linkedFolders": [_folder_view(row) for row in rows]}
+
+
[email protected]("/linked-folders/{folder_id}")
+def update_linked_folder(
+ folder_id: str,
+ payload: UpdateFolderRequest,
+ subject: str = Depends(get_current_subject),
+) -> dict:
+ _require_rag()
+ try:
+ row = folder_sync.update_folder(folder_id, name = payload.name, auto_sync = payload.auto_sync)
+ except KeyError as exc:
+ raise HTTPException(status_code = 404, detail = "Linked folder not found") from exc
+ except ValueError as exc:
+ raise HTTPException(status_code = 400, detail = str(exc)) from exc
+ return {"linkedFolder": _folder_view(row)}
+
+
[email protected]("/linked-folders/{folder_id}")
+def unlink_folder(
+ folder_id: str,
+ remove_index: bool = Query(default = True),
+ subject: str = Depends(get_current_subject),
+) -> dict:
+ _require_rag()
+ if not folder_sync.delete_folder(folder_id, remove_index = remove_index):
+ raise HTTPException(status_code = 404, detail = "Linked folder not found")
+ return {"ok": True}
+
+
[email protected]("/linked-folders/{folder_id}/sync")
+def sync_folder(folder_id: str, subject: str = Depends(get_current_subject)) -> dict:
+ _require_rag()
+ try:
+ return {"job": _folder_job_view(folder_sync.get_job(folder_sync.request_sync(folder_id)))}
+ except KeyError as exc:
+ raise HTTPException(status_code = 404, detail = "Linked folder not found") from exc
+
+
[email protected]("/linked-folders/{folder_id}/rebuild")
+def rebuild_folder(folder_id: str, subject: str = Depends(get_current_subject)) -> dict:
+ _require_rag()
+ try:
+ return {
+ "job": _folder_job_view(
+ folder_sync.get_job(folder_sync.request_sync(folder_id, rebuild = True))
+ )
+ }
+ except KeyError as exc:
+ raise HTTPException(status_code = 404, detail = "Linked folder not found") from exc
+
+
@router.get("/documents")
def list_all_uploaded_documents(subject: str = Depends(get_current_subject)) -> dict:
"""Every uploaded file across chats, projects, and knowledge bases (settings
@@ -503,9 +767,14 @@ def delete_document(document_id: str, subject: str = Depends(get_current_subject
_require_rag()
conn = _rag_connection()
try:
- doc = store.get_document(conn, document_id)
+ doc = store.get_visible_document(conn, document_id)
if doc is None:
raise HTTPException(status_code = 404, detail = "Document not found")
+ if doc.get("linked_folder_id"):
+ raise HTTPException(
+ status_code = 409,
+ detail = "Linked-folder documents are managed by folder synchronization",
+ )
store.delete_document(conn, document_id)
_remove_stored_upload(doc.get("stored_path"))
return {"ok": True}
@@ -550,14 +819,81 @@ def job_events(job_id: str, subject: str = Depends(get_current_subject)) -> Stre
)
+def _folder_job_view(row: dict) -> dict:
+ processed = (
+ (row.get("added") or 0)
+ + (row.get("changed") or 0)
+ + (row.get("deleted") or 0)
+ + (row.get("failed") or 0)
+ )
+ return {
+ "id": row["id"],
+ "linkedFolderId": row["folder_id"],
+ "mode": row["kind"],
+ "status": row["status"],
+ "stage": row.get("stage"),
+ "progress": row.get("progress") or 0.0,
+ "discoveredFiles": row.get("discovered") or 0,
+ "processedFiles": processed,
+ "indexedFiles": (row.get("added") or 0) + (row.get("changed") or 0),
+ "removedFiles": row.get("deleted") or 0,
+ "failedFiles": row.get("failed") or 0,
+ "error": row.get("error"),
+ "createdAt": row.get("created_at"),
+ "completedAt": row.get("completed_at"),
+ }
+
+
[email protected]("/linked-folder-jobs/{job_id}")
+def folder_job_status(job_id: str, subject: str = Depends(get_current_subject)) -> dict:
+ _require_rag()
+ row = folder_sync.get_job(job_id)
+ if row is None:
+ raise HTTPException(status_code = 404, detail = "Folder sync job not found")
+ return _folder_job_view(row)
+
+
[email protected]("/linked-folder-jobs/{job_id}/events")
+def folder_job_events(
+ job_id: str, subject: str = Depends(get_current_subject)
+) -> StreamingResponse:
+ _require_rag()
+ if folder_sync.get_job(job_id) is None:
+ raise HTTPException(status_code = 404, detail = "Folder sync job not found")
+
+ def gen():
+ for event in folder_sync.job_events(job_id):
+ if event is None:
+ yield ": keepalive\n\n"
+ continue
+ view = _folder_job_view(event)
+ view["type"] = (
+ "complete"
+ if event["status"] == "completed"
+ else "error"
+ if event["status"] == "failed"
+ else "progress"
+ )
+ yield f"data: {json.dumps(view)}\n\n"
+ yield "data: [DONE]\n\n"
+
+ return StreamingResponse(
+ gen(),
+ media_type = "text/event-stream",
+ headers = {"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
+ )
+
+
@router.post("/search")
def search(payload: SearchRequest, subject: str = Depends(get_current_subject)) -> dict:
_require_rag()
if payload.kb_id:
+ _require_scope_owner("knowledge_base", payload.kb_id)
scope = store.kb_scope(payload.kb_id)
else:
scopes = []
if payload.project_id:
+ _require_scope_owner("project", payload.project_id)
scopes.append(store.project_scope(payload.project_id))
if payload.thread_id:
scopes.append(store.thread_scope(payload.thread_id))
@@ -648,9 +984,10 @@ def preview_target(
_require_rag()
conn = _rag_connection()
try:
- doc = store.get_document(conn, document_id)
+ doc = store.get_visible_document(conn, document_id)
if doc is None:
raise HTTPException(status_code = 404, detail = "Document not found")
+ _require_document_owner(conn, doc)
ext = os.path.splitext(doc["filename"])[1].lower()
out = {
"documentId": document_id,
@@ -662,8 +999,9 @@ def preview_target(
}
if chunk_id:
row = conn.execute(
- "SELECT text, page_number, pdf_regions_json FROM chunks WHERE id=?",
- (chunk_id,),
+ "SELECT text, page_number, pdf_regions_json FROM chunks "
+ "WHERE id=? AND document_id=?",
+ (chunk_id, document_id),
).fetchone()
if row is not None:
out["text"] = row["text"]
@@ -684,9 +1022,10 @@ def document_file_url(document_id: str, subject: str = Depends(get_current_subje
_require_rag()
conn = _rag_connection()
try:
- doc = store.get_document(conn, document_id)
+ doc = store.get_visible_document(conn, document_id)
if doc is None or not doc.get("stored_path"):
raise HTTPException(status_code = 404, detail = "Document file not available")
+ _require_document_owner(conn, doc)
finally:
conn.close()
token = _sign_document(document_id)
@@ -705,19 +1044,21 @@ def document_file_signed(document_id: str, token: str = Query(...)) -> FileRespo
_require_rag()
conn = _rag_connection()
try:
- doc = store.get_document(conn, document_id)
+ doc = store.get_visible_document(conn, document_id)
+ if doc is not None:
+ _require_document_owner(conn, doc)
finally:
conn.close()
stored_path = (doc or {}).get("stored_path")
if not doc or not stored_path or not os.path.isfile(stored_path):
raise HTTPException(status_code = 404, detail = "Document file not found")
# Confine to the uploads root (defense in depth).
- uploads = os.path.realpath(str(rag_uploads_root()))
- if not os.path.realpath(stored_path).startswith(uploads):
+ if not _is_managed_preview_path(stored_path):
raise HTTPException(status_code = 403, detail = "Forbidden")
ext = os.path.splitext(doc["filename"])[1].lower()
return FileResponse(
stored_path,
media_type = _CONTENT_TYPES.get(ext, "application/octet-stream"),
- filename = doc["filename"],
+ # linked documents are named by a posix relative path, invalid in this header
+ filename = doc["filename"].rsplit("/", 1)[-1],
)
diff --git a/studio/backend/storage/rag_db.py b/studio/backend/storage/rag_db.py
index 406cebd1109..bdebd311e93 100644
--- a/studio/backend/storage/rag_db.py
+++ b/studio/backend/storage/rag_db.py
@@ -19,6 +19,7 @@ import logging
import re
import sqlite3
import threading
+from datetime import datetime, timezone
logger = logging.getLogger(__name__)
@@ -156,6 +157,83 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
created_at TEXT NOT NULL
);
+ CREATE TABLE IF NOT EXISTS rag_job_leases (
+ kind TEXT NOT NULL,
+ job_id TEXT NOT NULL,
+ owner_id TEXT NOT NULL,
+ expires_at TEXT NOT NULL,
+ PRIMARY KEY(kind, job_id)
+ );
+ CREATE INDEX IF NOT EXISTS idx_rag_job_leases_expiry
+ ON rag_job_leases(expires_at);
+
+ CREATE TABLE IF NOT EXISTS linked_folders (
+ id TEXT NOT NULL PRIMARY KEY,
+ scope_type TEXT NOT NULL,
+ scope_id TEXT NOT NULL,
+ scope TEXT NOT NULL,
+ path TEXT NOT NULL,
+ name TEXT NOT NULL,
+ root_device INTEGER,
+ root_inode INTEGER,
+ delete_remove_index INTEGER,
+ auto_sync INTEGER NOT NULL DEFAULT 1,
+ status TEXT NOT NULL DEFAULT 'pending',
+ last_error TEXT,
+ last_scan_at TEXT,
+ withheld_paths TEXT,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL,
+ UNIQUE(scope, path)
+ );
+ CREATE INDEX IF NOT EXISTS idx_linked_folders_scope ON linked_folders(scope);
+
+ CREATE TABLE IF NOT EXISTS linked_folder_retired_scopes (
+ scope TEXT NOT NULL PRIMARY KEY,
+ retired_at TEXT NOT NULL,
+ purged_at TEXT
+ );
+
+ CREATE TABLE IF NOT EXISTS linked_folder_files (
+ folder_id TEXT NOT NULL,
+ relative_path TEXT NOT NULL,
+ size_bytes INTEGER NOT NULL,
+ mtime_ns INTEGER NOT NULL,
+ device INTEGER,
+ inode INTEGER,
+ document_id TEXT NOT NULL,
+ content_hash TEXT,
+ synced_at TEXT NOT NULL,
+ PRIMARY KEY(folder_id, relative_path)
+ );
+ CREATE INDEX IF NOT EXISTS idx_linked_folder_files_document
+ ON linked_folder_files(document_id);
+
+ CREATE TABLE IF NOT EXISTS linked_folder_sync_jobs (
+ id TEXT NOT NULL PRIMARY KEY,
+ folder_id TEXT NOT NULL,
+ kind TEXT NOT NULL DEFAULT 'sync',
+ status TEXT NOT NULL DEFAULT 'pending',
+ stage TEXT,
+ progress REAL NOT NULL DEFAULT 0.0,
+ discovered INTEGER NOT NULL DEFAULT 0,
+ added INTEGER NOT NULL DEFAULT 0,
+ changed INTEGER NOT NULL DEFAULT 0,
+ deleted INTEGER NOT NULL DEFAULT 0,
+ renamed INTEGER NOT NULL DEFAULT 0,
+ failed INTEGER NOT NULL DEFAULT 0,
+ error TEXT,
+ successor_kind TEXT,
+ created_at TEXT NOT NULL,
+ started_at TEXT,
+ completed_at TEXT
+ );
+ CREATE INDEX IF NOT EXISTS idx_linked_folder_jobs_queue
+ ON linked_folder_sync_jobs(status, created_at);
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_linked_folder_jobs_active
+ ON linked_folder_sync_jobs(folder_id)
+ WHERE status IN ('pending','running');
+
CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
text,
chunk_id UNINDEXED,
@@ -172,6 +250,34 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:
# assumed current). Dedupe re-ingests when it no longer matches.
if "embedding_model" not in cols:
conn.execute("ALTER TABLE documents ADD COLUMN embedding_model TEXT")
+ # Folder ownership makes crash cleanup unambiguous without changing retrieval.
+ if "linked_folder_id" not in cols:
+ conn.execute("ALTER TABLE documents ADD COLUMN linked_folder_id TEXT")
+ if "linked_relative_path" not in cols:
+ conn.execute("ALTER TABLE documents ADD COLUMN linked_relative_path TEXT")
+ ensure_linked_folder_columns(conn)
+ conn.commit()
+
+
+def ensure_linked_folder_columns(conn: sqlite3.Connection) -> None:
+ """Add the linked-folder columns a database created by an earlier build is missing.
+
+ Also called for the metadata connection, which skips _ensure_schema so that scope
+ retirement keeps working when the vector extension cannot load.
+ """
+ job_cols = {r[1] for r in conn.execute("PRAGMA table_info(linked_folder_sync_jobs)").fetchall()}
+ # the queued follow-up request; it replaced a flag that only recorded rebuilds
+ if job_cols and "successor_kind" not in job_cols:
+ conn.execute("ALTER TABLE linked_folder_sync_jobs ADD COLUMN successor_kind TEXT")
+ if "rebuild_requested" in job_cols:
+ conn.execute(
+ "UPDATE linked_folder_sync_jobs SET successor_kind='rebuild' "
+ "WHERE rebuild_requested=1"
+ )
+ # vanished paths already granted their one grace pass before removal
+ folder_cols = {r[1] for r in conn.execute("PRAGMA table_info(linked_folders)").fetchall()}
+ if folder_cols and "withheld_paths" not in folder_cols:
+ conn.execute("ALTER TABLE linked_folders ADD COLUMN withheld_paths TEXT")
def get_connection() -> sqlite3.Connection:
@@ -212,6 +318,21 @@ def get_connection() -> sqlite3.Connection:
return conn
+def get_metadata_connection() -> sqlite3.Connection:
+ """Open rag.db without loading sqlite-vec.
+
+ This connection is only for ordinary SQLite metadata tables. It lets lifecycle
+ tombstones remain writable when the optional native vector extension is temporarily
+ unavailable. Callers must not query or mutate the vec0 virtual table.
+ """
+ db_path = rag_db_path()
+ ensure_dir(db_path.parent)
+ conn = sqlite3.connect(str(db_path))
+ conn.row_factory = sqlite3.Row
+ conn.execute("PRAGMA busy_timeout = 5000")
+ return conn
+
+
def vec_table_dim(conn: sqlite3.Connection) -> int | None:
"""Embedding width baked into ``chunks_vec``, or None when absent."""
row = conn.execute(
@@ -276,8 +397,9 @@ def _delete_document_chunks(conn, document_id: str) -> None:
def reconcile_orphaned_ingestion_jobs() -> int:
"""Fail ingestion jobs/documents left mid-flight by a crash so they stop
- showing as stuck "processing" and become re-ingestible. Run at startup.
- No-op without RAG. Returns the number of jobs reset.
+ showing as stuck "processing" and become re-ingestible. Work owned by another
+ live backend is left alone until its lease expires. No-op without RAG. Returns
+ the number of jobs reset.
"""
# rag_available(), not RAG_AVAILABLE: a venv with the package but no vec0 binary
# would otherwise raise out of startup and be logged as a reconcile failure, when
@@ -286,11 +408,16 @@ def reconcile_orphaned_ingestion_jobs() -> int:
return 0
conn = get_connection()
try:
+ conn.execute("BEGIN IMMEDIATE")
+ now = datetime.now(timezone.utc).isoformat()
# 'cancelled' is terminal too: the job stopped because its document was deleted, so
# rewriting it to failed would report a deliberate cancellation as an indexing failure.
rows = conn.execute(
- "SELECT id, document_id FROM ingestion_jobs "
- "WHERE status NOT IN ('completed', 'failed', 'cancelled')"
+ "SELECT j.id, j.document_id FROM ingestion_jobs j "
+ "WHERE j.status NOT IN ('completed', 'failed', 'cancelled') AND NOT EXISTS ("
+ "SELECT 1 FROM rag_job_leases l WHERE l.kind='ingestion' "
+ "AND l.job_id=j.id AND l.expires_at>?)",
+ (now,),
).fetchall()
for row in rows:
doc = conn.execute(
@@ -306,21 +433,25 @@ def reconcile_orphaned_ingestion_jobs() -> int:
"progress=1.0, error=NULL WHERE id=?",
(row["id"],),
)
- continue
+ else:
+ conn.execute(
+ "UPDATE ingestion_jobs SET status='failed', stage='error', "
+ "error='Server restarted during ingestion' WHERE id=?",
+ (row["id"],),
+ )
+ conn.execute(
+ "UPDATE documents SET status='failed' "
+ "WHERE id=? AND status NOT IN ('completed', 'failed')",
+ (row["document_id"],),
+ )
+ # A failed or still-in-flight doc must not leave citable chunks
+ # (retrieval filters by scope, not status); also drops any chunks of a
+ # doc already 'failed' before the crash.
+ _delete_document_chunks(conn, row["document_id"])
conn.execute(
- "UPDATE ingestion_jobs SET status='failed', stage='error', "
- "error='Server restarted during ingestion' WHERE id=?",
+ "DELETE FROM rag_job_leases WHERE kind='ingestion' AND job_id=?",
(row["id"],),
)
- conn.execute(
- "UPDATE documents SET status='failed' "
- "WHERE id=? AND status NOT IN ('completed', 'failed')",
- (row["document_id"],),
- )
- # A failed or still-in-flight doc must not leave citable chunks
- # (retrieval filters by scope, not status); also drops any chunks of a
- # doc already 'failed' before the crash.
- _delete_document_chunks(conn, row["document_id"])
conn.commit()
return len(rows)
finally:
diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.py
index d9415374d83..087b10653aa 100644
--- a/studio/backend/tests/conftest.py
+++ b/studio/backend/tests/conftest.py
@@ -15,6 +15,7 @@ import contextlib
import errno
import itertools
import os
+import shutil
import sys
from pathlib import Path
@@ -653,18 +654,46 @@ def api_key(studio_server):
# ── RAG fixtures ─────────────────────────────────────────────────────
[email protected](scope = "session")
+def linkable_temp_base(tmp_path_factory):
+ """Session scratch root for tests whose paths must satisfy the linked-folder policy.
+
+ macOS puts the pytest temp root under /private/var/folders, which the shared denylist
+ rejects as a system directory. The directory is unique per session so concurrent runs
+ cannot delete each other's databases, and session scope keeps its removal after every
+ function-scoped monkeypatch has been undone, so teardown sees a real os.scandir.
+ """
+ basetemp = tmp_path_factory.getbasetemp()
+ root = Path.home() / ".unsloth-test-tmp"
+ base = root / basetemp.name
+ base.mkdir(parents = True, exist_ok = True)
+ # pytest keeps its numbered temp roots, so a missing one means that session is gone
+ for stale in root.iterdir():
+ if stale.name != basetemp.name and not (basetemp.parent / stale.name).exists():
+ shutil.rmtree(stale, ignore_errors = True)
+ try:
+ yield base
+ finally:
+ shutil.rmtree(base, ignore_errors = True)
+
+
@pytest.fixture
-def rag_home(tmp_path, monkeypatch):
+def rag_home(tmp_path, monkeypatch, linkable_temp_base):
"""Isolate the RAG database under a fresh UNSLOTH_STUDIO_HOME per test.
- Points the storage root at ``tmp_path`` and resets the lazy schema flag so
+ Points the storage root at a linkable directory and resets the lazy schema flag so
each test starts from an empty rag.db. Yields the temp home path.
"""
+ from hub.storage.scan_folders import is_denied_system_path
from storage import rag_db
- monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(tmp_path))
+ root = tmp_path
+ if is_denied_system_path(os.path.realpath(str(tmp_path))):
+ root = linkable_temp_base / tmp_path.name
+ root.mkdir(parents = True, exist_ok = True)
+ monkeypatch.setenv("UNSLOTH_STUDIO_HOME", str(root))
monkeypatch.setattr(rag_db, "_schema_ready", False)
- return tmp_path
+ return root
@pytest.fixture
diff --git a/studio/backend/tests/test_rag_ingestion.py b/studio/backend/tests/test_rag_ingestion.py
index 15b835ce824..268d7712265 100644
--- a/studio/backend/tests/test_rag_ingestion.py
+++ b/studio/backend/tests/test_rag_ingestion.py
@@ -4,6 +4,7 @@
"""Ingestion lifecycle tests: pending -> completed, SSE events, dedupe, delete."""
import os
+import sqlite3
import threading
import time
@@ -41,6 +42,38 @@ def _wait_completed(job_id, timeout = 30.0):
return _wait_finished(job_id, timeout, ("completed", "failed"))
+def test_initial_connection_failure_marks_ingestion_failed(rag_home, monkeypatch, tmp_path):
+ path = _write(tmp_path, "doc.txt", "alpha bravo")
+ scope = store.kb_scope("K1")
+ conn = rag_db.get_connection()
+ try:
+ document_id = store.create_document(
+ conn,
+ scope = scope,
+ filename = "doc.txt",
+ sha256 = "hash",
+ stored_path = path,
+ status = "pending",
+ )
+ job_id = ingestion._new_job(conn, document_id, scope)
+ finally:
+ conn.close()
+ original_get_connection = rag_db.get_connection
+ attempts = 0
+
+ def fail_once():
+ nonlocal attempts
+ attempts += 1
+ if attempts == 1:
+ raise sqlite3.OperationalError("database is busy")
+ return original_get_connection()
+
+ monkeypatch.setattr(rag_db, "get_connection", fail_once)
+ ingestion._run(job_id, document_id, scope, path, None)
+
+ assert ingestion.get_job_status(job_id)["status"] == "failed"
+
+
def test_ingestion_lifecycle_pending_to_completed(rag_home, stub_embeddings, tmp_path):
path = _write(tmp_path, "doc.txt", "alpha bravo charlie " * 50)
scope = store.kb_scope("K1")
@@ -162,6 +195,42 @@ def test_ingestion_dedupe_by_hash(rag_home, stub_embeddings, tmp_path):
conn.close()
+def test_manual_upload_does_not_dedupe_to_linked_folder_document(
+ rag_home, stub_embeddings, tmp_path
+):
+ path = _write(tmp_path, "manual.txt", "alpha bravo charlie")
+ scope = store.kb_scope("K1")
+ sha = ingestion._sha256_file(path)
+ conn = rag_db.get_connection()
+ try:
+ linked_id = store.create_document(
+ conn,
+ scope = scope,
+ filename = "linked.txt",
+ sha256 = sha,
+ kb_id = "K1",
+ status = "completed",
+ linked_folder_id = "folder-1",
+ linked_relative_path = "linked.txt",
+ )
+ store.set_document_status(conn, linked_id, "completed", num_chunks = 1)
+ finally:
+ conn.close()
+
+ manual_id, job_id = ingestion.start_ingestion(scope, "K1", None, "manual.txt", path)
+ events = _drain(job_id)
+ _wait_completed(job_id)
+
+ assert manual_id != linked_id
+ assert not any(event.get("deduped") for event in events)
+ conn = rag_db.get_connection()
+ try:
+ assert store.get_document(conn, linked_id) is not None
+ assert store.get_document(conn, manual_id)["linked_folder_id"] is None
+ finally:
+ conn.close()
+
+
def test_ingestion_reingests_when_existing_has_zero_chunks(rag_home, stub_embeddings, tmp_path):
# A prior ingest of identical bytes that yielded no chunks (e.g. a scanned PDF
# before a vision model loaded) must re-ingest, not dedupe to the empty record.
diff --git a/studio/backend/tests/test_rag_job_events_queue_lifecycle.py b/studio/backend/tests/test_rag_job_events_queue_lifecycle.py
index 27cabd5de41..28e94c6d07a 100644
--- a/studio/backend/tests/test_rag_job_events_queue_lifecycle.py
+++ b/studio/backend/tests/test_rag_job_events_queue_lifecycle.py
@@ -142,3 +142,36 @@ def test_terminal_db_status_removes_queue(monkeypatch):
assert jid not in ing._jobs, "a terminal DB status must remove the queue"
finally:
ing._jobs.pop(jid, None)
+
+
+def test_consumed_internal_job_removes_terminal_row_and_queue(tmp_path, monkeypatch):
+ db_path = tmp_path / "jobs.db"
+ conn = sqlite3.connect(db_path)
+ try:
+ conn.execute("CREATE TABLE ingestion_jobs(id TEXT PRIMARY KEY, status TEXT NOT NULL)")
+ conn.executemany(
+ "INSERT INTO ingestion_jobs(id, status) VALUES(?, ?)",
+ [("terminal", "completed"), ("active", "running")],
+ )
+ conn.commit()
+ finally:
+ conn.close()
+
+ monkeypatch.setattr(ing.rag_db, "get_connection", lambda: sqlite3.connect(db_path))
+ ing._jobs["terminal"] = queue.Queue()
+ ing._jobs["active"] = queue.Queue()
+ try:
+ assert ing.delete_terminal_job("terminal") is True
+ assert ing.delete_terminal_job("active") is False
+ assert "terminal" not in ing._jobs
+ assert "active" in ing._jobs
+ conn = sqlite3.connect(db_path)
+ try:
+ assert conn.execute("SELECT id FROM ingestion_jobs ORDER BY id").fetchall() == [
+ ("active",)
+ ]
+ finally:
+ conn.close()
+ finally:
+ ing._jobs.pop("terminal", None)
+ ing._jobs.pop("active", None)
diff --git a/studio/backend/tests/test_rag_linked_folders.py b/studio/backend/tests/test_rag_linked_folders.py
new file mode 100644
index 00000000000..65aed89a51a
--- /dev/null
+++ b/studio/backend/tests/test_rag_linked_folders.py
@@ -0,0 +1,2215 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Focused linked-folder reconciliation tests; embeddings are always stubbed."""
+
+from __future__ import annotations
+
+import asyncio
+import io
+import os
+import sqlite3
+import threading
+import time
+from contextlib import closing
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from core.rag import folder_sync, store
+from storage import rag_db
+from utils.paths import rag_db_path
+
+requires_sqlite_vec = pytest.mark.skipif(
+ not rag_db.RAG_AVAILABLE, reason = "sqlite-vec is not installed"
+)
+
+
+def _run(folder_id: str, *, rebuild: bool = False) -> dict:
+ job_id = folder_sync.request_sync(folder_id, rebuild = rebuild)
+ folder_sync.reconcile_folder(job_id)
+ return folder_sync.get_job(job_id)
+
+
+def _folder(rag_home: Path, scope_type: str = "knowledge_base"):
+ source = rag_home / "source"
+ source.mkdir()
+ row = folder_sync.create_folder(
+ scope_type = scope_type,
+ scope_id = "scope-1",
+ path = str(source),
+ name = "Docs",
+ )
+ return source, row
+
+
+def _connection(*, metadata: bool = False):
+ connect = rag_db.get_metadata_connection if metadata else rag_db.get_connection
+ return closing(connect())
+
+
+def _row(sql: str, params = ()) -> dict | None:
+ with _connection() as conn:
+ row = conn.execute(sql, params).fetchone()
+ return dict(row) if row else None
+
+
+def _mapping(folder: dict) -> dict | None:
+ return _row("SELECT * FROM linked_folder_files WHERE folder_id=?", (folder["id"],))
+
+
+class _CommitFails:
+ """A connection whose commit always fails, to exercise rollback ordering."""
+
+ def __init__(self, conn):
+ self._conn = conn
+
+ def __getattr__(self, name):
+ return getattr(self._conn, name)
+
+ def commit(self):
+ raise sqlite3.OperationalError("database is locked")
+
+
+@requires_sqlite_vec
+def test_startup_preserves_foreign_leased_work_until_its_lease_expires(rag_home):
+ from core.rag import ingestion, job_leases
+
+ _, folder = _folder(rag_home)
+ sync_job = folder_sync.request_sync(folder["id"])
+ with _connection() as conn:
+ document_id = store.create_document(
+ conn,
+ scope = folder["scope"],
+ filename = "in-flight.txt",
+ sha256 = "foreign",
+ linked_folder_id = folder["id"],
+ linked_relative_path = "in-flight.txt",
+ )
+ ingestion_job = ingestion._new_job(conn, document_id, folder["scope"])
+ conn.execute("UPDATE linked_folder_sync_jobs SET status='running' WHERE id=?", (sync_job,))
+ conn.execute(
+ "UPDATE rag_job_leases SET owner_id='foreign', expires_at='9999-12-31' "
+ "WHERE kind=? AND job_id=?",
+ (job_leases.INGESTION, ingestion_job),
+ )
+ conn.execute(
+ "INSERT INTO rag_job_leases(kind, job_id, owner_id, expires_at) "
+ "VALUES(?,?,'foreign','9999-12-31')",
+ (job_leases.FOLDER_SYNC, sync_job),
+ )
+ conn.commit()
+
+ folder_sync._recover_startup_state()
+ assert folder_sync.get_job(sync_job)["status"] == "running"
+ assert folder_sync._claim_job(sync_job) is None
+ with _connection() as conn:
+ assert store.get_document(conn, document_id) is not None
+ conn.execute(
+ "DELETE FROM rag_job_leases WHERE kind=? AND job_id=?",
+ (job_leases.INGESTION, ingestion_job),
+ )
+ conn.commit()
+
+ folder_sync._recover_startup_state()
+ with _connection() as conn:
+ assert store.get_document(conn, document_id) is not None
+ conn.execute("UPDATE rag_job_leases SET expires_at='2000-01-01'")
+ conn.commit()
+
+ folder_sync._recover_startup_state()
+ assert folder_sync.get_job(sync_job)["status"] == "pending"
+ with _connection() as conn:
+ assert store.get_document(conn, document_id) is None
+
+
+@requires_sqlite_vec
+def test_failed_replacement_commit_keeps_the_prior_snapshot_readable(
+ rag_home, stub_embeddings, monkeypatch
+):
+ """A rollback restores the old document, so its source must still be on disk."""
+ source, folder = _folder(rag_home)
+ path = source / "notes.txt"
+ path.write_text("first searchable text", encoding = "utf-8")
+ assert _run(folder["id"])["status"] == "completed"
+ before = _mapping(folder)
+ with _connection() as conn:
+ stored_path = store.get_document(conn, before["document_id"])["stored_path"]
+
+ path.write_text("second searchable text", encoding = "utf-8")
+ with _connection() as conn:
+ replacement = store.create_document(
+ conn, scope = folder["scope"], filename = "notes.txt", sha256 = "second"
+ )
+ stat = path.stat()
+ metadata = {
+ "path": str(path),
+ "size_bytes": stat.st_size,
+ "mtime_ns": stat.st_mtime_ns,
+ "device": stat.st_dev,
+ "inode": stat.st_ino,
+ }
+
+ real_connection = folder_sync.rag_db.get_connection
+ with monkeypatch.context() as patched:
+ patched.setattr(
+ folder_sync.rag_db, "get_connection", lambda: _CommitFails(real_connection())
+ )
+ with pytest.raises(sqlite3.OperationalError):
+ folder_sync._install_mapping(folder, "notes.txt", metadata, replacement, "second")
+
+ assert _mapping(folder)["document_id"] == before["document_id"]
+ assert os.path.isfile(stored_path)
+ with _connection() as conn:
+ assert store.search_lexical(conn, folder["scope"], "first", 5)
+
+
+@requires_sqlite_vec
+def test_failed_deletion_commit_keeps_the_snapshot_readable(rag_home, stub_embeddings, monkeypatch):
+ """An auto_sync=0 folder may not reconcile again for a long time."""
+ source, folder = _folder(rag_home)
+ path = source / "notes.txt"
+ path.write_text("only searchable text", encoding = "utf-8")
+ assert _run(folder["id"])["status"] == "completed"
+ before = _mapping(folder)
+ with _connection() as conn:
+ stored_path = store.get_document(conn, before["document_id"])["stored_path"]
+
+ real_connection = folder_sync.rag_db.get_connection
+ with monkeypatch.context() as patched:
+ patched.setattr(
+ folder_sync.rag_db, "get_connection", lambda: _CommitFails(real_connection())
+ )
+ with pytest.raises(sqlite3.OperationalError):
+ folder_sync._delete_mapping(folder["id"], "notes.txt")
+
+ assert _mapping(folder)["document_id"] == before["document_id"]
+ assert os.path.isfile(stored_path)
+ with _connection() as conn:
+ assert store.search_lexical(conn, folder["scope"], "searchable", 5)
+
+
+@requires_sqlite_vec
+def test_skipped_reconciliation_releases_a_claim_the_queue_already_activated(rag_home):
+ """Otherwise the heartbeat renews it forever and the unlink never returns."""
+ from core.rag import job_leases
+
+ _, folder = _folder(rag_home)
+ job_id = folder_sync.request_sync(folder["id"])
+ assert folder_sync._claim_job(job_id) == (job_id, folder["id"])
+ with _connection() as conn:
+ assert job_leases.owned_by_this_process(conn, job_leases.FOLDER_SYNC, job_id)
+ # delete_folder() fails the claimed job before reconciliation starts.
+ conn.execute("UPDATE linked_folder_sync_jobs SET status='failed' WHERE id=?", (job_id,))
+ conn.commit()
+
+ folder_sync.reconcile_folder(job_id)
+
+ assert (
+ _row(
+ "SELECT 1 FROM rag_job_leases WHERE kind=? AND job_id=?",
+ (job_leases.FOLDER_SYNC, job_id),
+ )
+ is None
+ )
+
+
+@requires_sqlite_vec
+def test_unlink_completes_when_the_queue_claimed_the_job_first(rag_home):
+ _, folder = _folder(rag_home)
+ job_id = folder_sync.request_sync(folder["id"])
+ assert folder_sync._claim_job(job_id) == (job_id, folder["id"])
+
+ unlinked = []
+ worker = threading.Thread(
+ target = lambda: unlinked.append(folder_sync.delete_folder(folder["id"])),
+ daemon = True,
+ )
+ worker.start()
+ time.sleep(0.1)
+ folder_sync.reconcile_folder(job_id)
+ worker.join(timeout = 10)
+
+ assert not worker.is_alive(), "unlink is still waiting on a leaked claim"
+ assert unlinked == [True]
+
+
+def test_worker_retries_after_a_failed_queue_selection(monkeypatch):
+ stop = threading.Event()
+ attempts = []
+
+ def flaky_next_job():
+ attempts.append(1)
+ if len(attempts) == 1:
+ raise sqlite3.OperationalError("database is locked")
+ stop.set()
+ return None
+
+ monkeypatch.setattr(folder_sync, "_recover_startup_state", lambda: None)
+ monkeypatch.setattr(folder_sync, "_enqueue_periodic", lambda: None)
+ monkeypatch.setattr(folder_sync, "_next_job", flaky_next_job)
+
+ try:
+ folder_sync._worker(stop)
+ finally:
+ del folder_sync._worker_state.stop_event
+
+ assert len(attempts) == 2
+
+
+@requires_sqlite_vec
+def test_periodic_scheduling_reaps_orphans_a_survivor_never_saw_at_startup(rag_home):
+ """The survivor's own startup pass ran before the other backend crashed."""
+ from core.rag import ingestion, job_leases
+
+ _, folder = _folder(rag_home)
+ folder_sync._recover_startup_state()
+ with _connection() as conn:
+ document_id = store.create_document(
+ conn,
+ scope = folder["scope"],
+ filename = "orphan.txt",
+ sha256 = "orphan",
+ linked_folder_id = folder["id"],
+ linked_relative_path = "orphan.txt",
+ )
+ ingestion_job = ingestion._new_job(conn, document_id, folder["scope"])
+ conn.execute(
+ "UPDATE rag_job_leases SET owner_id='crashed', expires_at='2000-01-01' "
+ "WHERE kind=? AND job_id=?",
+ (job_leases.INGESTION, ingestion_job),
+ )
+ conn.commit()
+
+ folder_sync._enqueue_periodic()
+
+ with _connection() as conn:
+ assert store.get_document(conn, document_id) is None
+ assert (
+ conn.execute("SELECT 1 FROM ingestion_jobs WHERE id=?", (ingestion_job,)).fetchone()
+ is None
+ )
+
+
+@requires_sqlite_vec
+def test_normal_scheduling_reclaims_an_expired_running_job(rag_home):
+ from core.rag import job_leases
+
+ _, folder = _folder(rag_home)
+ job_id = folder_sync.request_sync(folder["id"])
+ with _connection() as conn:
+ conn.execute("UPDATE linked_folder_sync_jobs SET status='running' WHERE id=?", (job_id,))
+ conn.execute(
+ "INSERT INTO rag_job_leases(kind, job_id, owner_id, expires_at) "
+ "VALUES(?,?,'foreign','2000-01-01')",
+ (job_leases.FOLDER_SYNC, job_id),
+ )
+ conn.commit()
+
+ try:
+ assert folder_sync._next_job() == (job_id, folder["id"])
+ finally:
+ job_leases.release(job_leases.FOLDER_SYNC, job_id)
+
+
+@requires_sqlite_vec
+def test_reconcile_add_rename_delete_and_skip_unsupported_and_symlinks(rag_home, stub_embeddings):
+ source, folder = _folder(rag_home)
+ (source / "notes.txt").write_text("alpha original", encoding = "utf-8")
+ (source / "ignored.exe").write_text("alpha ignored", encoding = "utf-8")
+ outside = rag_home / "outside.txt"
+ outside.write_text("alpha outside", encoding = "utf-8")
+ try:
+ (source / "escape.txt").symlink_to(outside)
+ except OSError:
+ pass
+
+ first = _run(folder["id"])
+ assert first["status"] == "completed"
+ assert first["discovered"] == 1
+ with _connection() as conn:
+ mapping = dict(
+ conn.execute(
+ "SELECT * FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchone()
+ )
+ document = store.get_document(conn, mapping["document_id"])
+ assert mapping["relative_path"] == "notes.txt"
+ assert os.path.realpath(document["stored_path"]) != os.path.realpath(source / "notes.txt")
+ assert store.search_lexical(conn, folder["scope"], "original", 5)
+ assert conn.execute("SELECT COUNT(*) FROM ingestion_jobs").fetchone()[0] == 0
+ from routes.rag import _doc_view
+
+ assert _doc_view(document)["managed"] is True
+
+ old_document_id = mapping["document_id"]
+ (source / "notes.txt").rename(source / "renamed.txt")
+ renamed = _run(folder["id"])
+ assert renamed["renamed"] == 1
+ with _connection() as conn:
+ row = conn.execute(
+ "SELECT * FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchone()
+ assert row["relative_path"] == "renamed.txt"
+ assert row["document_id"] == old_document_id
+
+ (source / "renamed.txt").unlink()
+ deleted = _run(folder["id"])
+ assert deleted["deleted"] == 1
+ with _connection() as conn:
+ assert store.get_document(conn, old_document_id) is None
+ assert (
+ conn.execute(
+ "SELECT 1 FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchone()
+ is None
+ )
+
+
+def test_scan_skips_revisited_directory_identity(rag_home, monkeypatch):
+ source = rag_home / "cycle"
+ loop = source / "loop"
+ loop.mkdir(parents = True)
+ (source / "notes.txt").write_text("alpha", encoding = "utf-8")
+ original_scandir = os.scandir
+ scanned = []
+
+ def cycle_scandir(path):
+ path = os.fspath(path)
+ scanned.append(path)
+ if path == str(loop):
+ if scanned.count(path) > 1:
+ raise AssertionError("revisited directory identity")
+ return original_scandir(source)
+ return original_scandir(path)
+
+ monkeypatch.setattr(folder_sync.os, "scandir", cycle_scandir)
+
+ found, _ = folder_sync._scan(str(source))
+
+ assert set(found) == {"notes.txt"}
+ assert scanned.count(str(loop)) == 1
+
+
[email protected]("directory_identity", [(0, 0), (123, 456)])
+def test_scan_keeps_distinct_directories_with_duplicate_identity(
+ rag_home, monkeypatch, directory_identity
+):
+ source = rag_home / "duplicate-identities"
+ first = source / "first"
+ second = source / "second"
+ first.mkdir(parents = True)
+ second.mkdir()
+ (first / "first.txt").write_text("first", encoding = "utf-8")
+ (second / "second.txt").write_text("second", encoding = "utf-8")
+ original_scandir = os.scandir
+
+ class WeakIdentityEntry:
+ def __init__(self, entry):
+ self._entry = entry
+
+ def __getattr__(self, name):
+ return getattr(self._entry, name)
+
+ def stat(self, *, follow_symlinks = True):
+ if self._entry.is_dir(follow_symlinks = follow_symlinks):
+ return SimpleNamespace(st_dev = directory_identity[0], st_ino = directory_identity[1])
+ return self._entry.stat(follow_symlinks = follow_symlinks)
+
+ class WeakIdentityScandir:
+ def __init__(self, path):
+ self._entries = original_scandir(path)
+
+ def __enter__(self):
+ self._entries.__enter__()
+ return self
+
+ def __exit__(self, *args):
+ return self._entries.__exit__(*args)
+
+ def __iter__(self):
+ return (WeakIdentityEntry(entry) for entry in self._entries)
+
+ monkeypatch.setattr(folder_sync, "_root_identity", lambda root: directory_identity)
+ monkeypatch.setattr(folder_sync.os, "scandir", WeakIdentityScandir)
+
+ found, _ = folder_sync._scan(str(source))
+
+ assert set(found) == {"first/first.txt", "second/second.txt"}
+
+
+@requires_sqlite_vec
+def test_reconcile_pins_one_embedding_model_for_every_file(rag_home, stub_embeddings, monkeypatch):
+ source, folder = _folder(rag_home)
+ (source / "first.txt").write_text("first words", encoding = "utf-8")
+ (source / "second.txt").write_text("second words", encoding = "utf-8")
+ resolved = []
+ models = []
+
+ def effective_model():
+ resolved.append(True)
+ return "model/one" if len(resolved) == 1 else "model/two"
+
+ original_start = folder_sync.ingestion.start_ingestion
+
+ def capture_model(*args, **kwargs):
+ models.append(kwargs.get("model_name"))
+ return original_start(*args, **kwargs)
+
+ monkeypatch.setattr(folder_sync.config, "effective_embedding_model", effective_model)
+ monkeypatch.setattr(folder_sync.ingestion, "start_ingestion", capture_model)
+
+ assert _run(folder["id"])["status"] == "completed"
+ assert len(resolved) == 1
+ assert models == ["model/one", "model/one"]
+
+
+@requires_sqlite_vec
+def test_reconcile_retains_mapping_when_missing_file_reappears(
+ rag_home, stub_embeddings, monkeypatch
+):
+ source, folder = _folder(rag_home)
+ linked = source / "notes.txt"
+ linked.write_text("durable words", encoding = "utf-8")
+ assert _run(folder["id"])["status"] == "completed"
+ before = _mapping(folder)
+ linked.unlink()
+ original_scan = folder_sync._scan
+
+ def restore_after_scan(*args, **kwargs):
+ result = original_scan(*args, **kwargs)
+ linked.write_text("durable words", encoding = "utf-8")
+ return result
+
+ monkeypatch.setattr(folder_sync, "_scan", restore_after_scan)
+ result = _run(folder["id"])
+
+ assert result["status"] == "failed"
+ assert result["deleted"] == 0
+ with _connection() as conn:
+ after = dict(
+ conn.execute(
+ "SELECT * FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchone()
+ )
+ assert after["document_id"] == before["document_id"]
+ assert store.search_lexical(conn, folder["scope"], "durable", 5)
+
+
+@requires_sqlite_vec
+def test_extension_changing_rename_reingests_with_the_new_parser(rag_home, stub_embeddings):
+ source, folder = _folder(rag_home)
+ original = source / "notes.html"
+ original.write_text(
+ "<p>visible alpha</p><script>hiddenscripttoken</script>",
+ encoding = "utf-8",
+ )
+ assert _run(folder["id"])["status"] == "completed"
+ with _connection() as conn:
+ before = dict(
+ conn.execute(
+ "SELECT * FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchone()
+ )
+ assert not store.search_lexical(conn, folder["scope"], "hiddenscripttoken", 5)
+
+ original.rename(source / "notes.txt")
+ result = _run(folder["id"])
+ assert result["status"] == "completed"
+ assert result["added"] == 1
+ assert result["deleted"] == 1
+ with _connection() as conn:
+ after = dict(
+ conn.execute(
+ "SELECT * FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchone()
+ )
+ assert after["relative_path"] == "notes.txt"
+ assert after["document_id"] != before["document_id"]
+ assert store.get_document(conn, before["document_id"]) is None
+ assert store.search_lexical(conn, folder["scope"], "hiddenscripttoken", 5)
+
+
+@requires_sqlite_vec
+def test_rename_reuse_verifies_content_before_reusing_the_document(rag_home, stub_embeddings):
+ source, folder = _folder(rag_home)
+ original = source / "original.txt"
+ original.write_text("first words", encoding = "utf-8")
+ assert _run(folder["id"])["status"] == "completed"
+ before = _mapping(folder)
+
+ renamed = source / "renamed.txt"
+ original.rename(renamed)
+ renamed.write_text("other words", encoding = "utf-8")
+ os.utime(renamed, ns = (renamed.stat().st_atime_ns, before["mtime_ns"]))
+ assert renamed.stat().st_ino == before["inode"]
+ assert renamed.stat().st_size == before["size_bytes"]
+
+ result = _run(folder["id"])
+ assert result["renamed"] == 0
+ assert result["added"] == 1
+ assert result["deleted"] == 1
+ with _connection() as conn:
+ after = dict(
+ conn.execute(
+ "SELECT * FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchone()
+ )
+ assert after["document_id"] != before["document_id"]
+ assert store.search_lexical(conn, folder["scope"], "other", 5)
+
+
+@requires_sqlite_vec
+def test_edited_rename_failure_retains_the_prior_mapping(rag_home, stub_embeddings, monkeypatch):
+ source, folder = _folder(rag_home)
+ original = source / "original.txt"
+ original.write_text("durable prior words", encoding = "utf-8")
+ assert _run(folder["id"])["status"] == "completed"
+ before = _mapping(folder)
+
+ renamed = source / "renamed.txt"
+ original.rename(renamed)
+ renamed.write_text("replacement content that fails", encoding = "utf-8")
+ assert renamed.stat().st_ino == before["inode"]
+ monkeypatch.setattr(
+ folder_sync.ingestion,
+ "start_ingestion",
+ lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("embed unavailable")),
+ )
+
+ result = _run(folder["id"])
+ assert result["status"] == "failed"
+ with _connection() as conn:
+ current = dict(
+ conn.execute(
+ "SELECT * FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchone()
+ )
+ assert current["relative_path"] == "original.txt"
+ assert current["document_id"] == before["document_id"]
+ assert store.search_lexical(conn, folder["scope"], "durable", 5)
+
+
+@requires_sqlite_vec
+def test_rename_over_existing_path_failure_retains_both_prior_mappings(
+ rag_home, stub_embeddings, monkeypatch
+):
+ source, folder = _folder(rag_home)
+ old = source / "old.txt"
+ destination = source / "destination.txt"
+ old.write_text("durable source", encoding = "utf-8")
+ destination.write_text("durable destination", encoding = "utf-8")
+ assert _run(folder["id"])["status"] == "completed"
+ os.replace(old, destination)
+ monkeypatch.setattr(
+ folder_sync.ingestion,
+ "start_ingestion",
+ lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("embed unavailable")),
+ )
+
+ result = _run(folder["id"])
+
+ assert result["status"] == "failed"
+ 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 == {"old.txt", "destination.txt"}
+ assert store.search_lexical(conn, folder["scope"], "source", 5)
+ assert store.search_lexical(conn, folder["scope"], "destination", 5)
+
+
+@requires_sqlite_vec
+def test_changed_file_failure_and_unavailable_scan_retain_prior_index(
+ rag_home, stub_embeddings, monkeypatch
+):
+ source, folder = _folder(rag_home, scope_type = "project")
+ path = source / "notes.txt"
+ path.write_text("durable prior words", encoding = "utf-8")
+ assert _run(folder["id"])["status"] == "completed"
+ prior = _mapping(folder)
+
+ path.write_text("replacement content that fails", encoding = "utf-8")
+ monkeypatch.setattr(
+ folder_sync.ingestion,
+ "start_ingestion",
+ lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("embed unavailable")),
+ )
+ failed = _run(folder["id"])
+ assert failed["status"] == "failed"
+ with _connection() as conn:
+ current = conn.execute(
+ "SELECT document_id FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchone()
+ assert current["document_id"] == prior["document_id"]
+ assert store.search_lexical(conn, folder["scope"], "durable", 5)
+
+ source.rename(rag_home / "unavailable")
+ unavailable = _run(folder["id"])
+ assert unavailable["status"] == "failed"
+ with _connection() as conn:
+ assert (
+ conn.execute(
+ "SELECT document_id FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchone()["document_id"]
+ == prior["document_id"]
+ )
+
+
+@requires_sqlite_vec
+def test_replaced_empty_root_fails_and_retains_prior_index(rag_home, stub_embeddings):
+ source, folder = _folder(rag_home)
+ (source / "notes.txt").write_text("retained root document", encoding = "utf-8")
+ assert _run(folder["id"])["status"] == "completed"
+ prior = _mapping(folder)
+
+ source.rename(rag_home / "replaced-source")
+ source.mkdir()
+ result = _run(folder["id"])
+ assert result["status"] == "failed"
+ assert "identity changed" in result["error"]
+ with _connection() as conn:
+ current = conn.execute(
+ "SELECT document_id FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchone()
+ assert current["document_id"] == prior["document_id"]
+ assert store.get_document(conn, prior["document_id"]) is not None
+ assert store.search_lexical(conn, folder["scope"], "retained", 5)
+
+
+@requires_sqlite_vec
+def test_reauthorizing_same_path_refreshes_root_identity_and_retains_mappings(
+ rag_home, stub_embeddings
+):
+ source, folder = _folder(rag_home)
+ (source / "notes.txt").write_text("retained after remount", encoding = "utf-8")
+ assert _run(folder["id"])["status"] == "completed"
+ with _connection() as conn:
+ mapping_before = dict(
+ conn.execute(
+ "SELECT * FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchone()
+ )
+ conn.execute(
+ "UPDATE linked_folders SET root_device=-1, root_inode=-1 WHERE id=?", (folder["id"],)
+ )
+ conn.commit()
+
+ refreshed = {}
+ reauthorized = threading.Event()
+
+ def reauthorize():
+ refreshed.update(
+ folder_sync.create_folder(
+ scope_type = "knowledge_base",
+ scope_id = "scope-1",
+ path = str(source),
+ )
+ )
+ reauthorized.set()
+
+ with folder_sync._folder_lock(folder["id"]):
+ thread = threading.Thread(target = reauthorize)
+ thread.start()
+ assert not reauthorized.wait(0.1)
+ thread.join(timeout = 1)
+
+ source_stat = source.stat()
+ assert reauthorized.is_set()
+ assert refreshed["id"] == folder["id"]
+ assert (refreshed["root_device"], refreshed["root_inode"]) == (
+ source_stat.st_dev,
+ source_stat.st_ino,
+ )
+ with _connection() as conn:
+ mapping_after = dict(
+ conn.execute(
+ "SELECT * FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchone()
+ )
+ assert mapping_after["document_id"] == mapping_before["document_id"]
+ assert store.search_lexical(conn, folder["scope"], "remount", 5)
+
+
[email protected]("source_name", ["source", "source "])
+def test_directory_lease_contract_preserves_path_and_purpose(rag_home, source_name):
+ source = rag_home / source_name
+ source.mkdir()
+ if source_name.endswith(" "):
+ (rag_home / source_name.rstrip()).mkdir()
+ calls = []
+ identity = (source.stat().st_dev, source.stat().st_ino)
+
+ def verify(lease, **kwargs):
+ calls.append((lease, kwargs))
+ return SimpleNamespace(
+ canonical_path = source,
+ device_id = identity[0],
+ file_id = identity[1],
+ )
+
+ from routes.rag import _resolve_linked_folder_path
+
+ assert _resolve_linked_folder_path("signed", verifier = verify) == (str(source), identity)
+ assert calls[0][0] == "signed"
+ assert calls[0][1] == {
+ "operation": "link-documents",
+ "expected_kind": "document-folder",
+ "expected_path_type": "directory",
+ }
+
+
+@requires_sqlite_vec
+def test_registration_rechecks_the_signed_folder_identity(rag_home, monkeypatch):
+ source = rag_home / "identity-race"
+ source.mkdir()
+ signed_identity = (source.stat().st_dev, source.stat().st_ino)
+ replacement_identity = (signed_identity[0], signed_identity[1] + 1)
+ identities = iter((signed_identity, replacement_identity))
+ monkeypatch.setattr(folder_sync, "_root_identity", lambda path: next(identities))
+
+ with pytest.raises(ValueError, match = "changed after it was selected"):
+ folder_sync.create_folder(
+ scope_type = "project",
+ scope_id = "identity-race",
+ path = str(source),
+ expected_identity = signed_identity,
+ )
+
+ assert folder_sync.list_folders(store.project_scope("identity-race")) == []
+
+
+@requires_sqlite_vec
+def test_large_windows_root_identity_round_trips_through_sqlite(rag_home, monkeypatch):
+ source = rag_home / "large-identity"
+ source.mkdir()
+ identity = (1 << 63, 1 << 127)
+ monkeypatch.setattr(folder_sync, "_root_identity", lambda path: identity)
+
+ folder = folder_sync.create_folder(
+ scope_type = "knowledge_base",
+ scope_id = "large-identity",
+ path = str(source),
+ expected_identity = identity,
+ )
+
+ assert folder_sync._load_identity(folder["root_device"], folder["root_inode"]) == identity
+
+
+@requires_sqlite_vec
+def test_large_windows_file_identity_round_trips_through_sqlite(
+ rag_home, stub_embeddings, monkeypatch
+):
+ """CPython 3.12+ reads st_ino from FILE_ID_INFO, so a ReFS file id is 128-bit."""
+ source, folder = _folder(rag_home)
+ (source / "notes.txt").write_text("large identity text", encoding = "utf-8")
+ identity = (1 << 63, 1 << 127)
+ real_scan, real_snapshot = folder_sync._scan, folder_sync._snapshot
+
+ def scan(root, expected_identity = None):
+ found, root_identity = real_scan(root, expected_identity)
+ for metadata in found.values():
+ metadata["scanned"], (metadata["device"], metadata["inode"]) = (
+ (metadata["device"], metadata["inode"]),
+ identity,
+ )
+ return found, root_identity
+
+ monkeypatch.setattr(folder_sync, "_scan", scan)
+ monkeypatch.setattr(
+ folder_sync,
+ "_snapshot",
+ lambda root, metadata: real_snapshot(
+ root, {**metadata, "device": metadata["scanned"][0], "inode": metadata["scanned"][1]}
+ ),
+ )
+
+ assert _run(folder["id"])["status"] == "completed"
+ row = _mapping(folder)
+ assert folder_sync._load_identity(row["device"], row["inode"]) == identity
+ # The same identity must still compare equal, so nothing re-embeds every sync.
+ assert _run(folder["id"])["changed"] == 0
+
+
+def test_validate_folder_rejects_symlink_root(rag_home):
+ source = rag_home / "source"
+ source.mkdir()
+ alias = rag_home / "alias"
+ try:
+ alias.symlink_to(source, target_is_directory = True)
+ except OSError:
+ pytest.skip("directory symlinks are unavailable")
+ with pytest.raises(ValueError, match = "Symbolic-link"):
+ folder_sync.validate_folder_path(str(alias))
+
+
+def test_snapshot_copy_is_bounded_to_the_validated_size():
+ target = io.BytesIO()
+ with pytest.raises(RuntimeError, match = "changed while it was copied"):
+ folder_sync._copy_exact(io.BytesIO(b"validated-and-growing"), target, 9)
+ assert target.getvalue() == b"validated"
+
+
+@requires_sqlite_vec
+def test_linked_folders_cannot_overlap_within_a_scope(rag_home):
+ parent = rag_home / "parent"
+ child = parent / "child"
+ child.mkdir(parents = True)
+ folder_sync.create_folder(scope_type = "project", scope_id = "one", path = str(parent))
+
+ with pytest.raises(ValueError, match = "cannot overlap"):
+ folder_sync.create_folder(scope_type = "project", scope_id = "one", path = str(child))
+
+ other_scope = folder_sync.create_folder(scope_type = "project", scope_id = "two", path = str(child))
+ assert other_scope["path"] == str(child)
+
+
+@requires_sqlite_vec
+def test_linked_folder_rejects_managed_rag_uploads_overlap(rag_home):
+ from utils.paths import ensure_dir, rag_uploads_root
+
+ uploads = ensure_dir(rag_uploads_root())
+ uploads_child = uploads / "child"
+ uploads_child.mkdir()
+ for path in [uploads.parent, uploads, uploads_child]:
+ with pytest.raises(ValueError, match = "managed RAG uploads"):
+ folder_sync.create_folder(scope_type = "project", scope_id = "one", path = str(path))
+
+
+def test_backend_routes_match_linked_folder_client_contract():
+ from routes.rag import LinkFolderRequest, router
+
+ paths = {route.path for route in router.routes}
+ assert {
+ "/linked-folders",
+ "/knowledge-bases/{kb_id}/linked-folders",
+ "/projects/{project_id}/linked-folders",
+ "/linked-folders/{folder_id}/sync",
+ "/linked-folders/{folder_id}/rebuild",
+ "/linked-folder-jobs/{job_id}",
+ "/linked-folder-jobs/{job_id}/events",
+ } <= paths
+ assert "path" not in LinkFolderRequest.model_fields
+ assert LinkFolderRequest.model_fields["native_path_lease"].is_required()
+
+
+@requires_sqlite_vec
+def test_same_size_same_mtime_inode_replacement_is_reconciled(rag_home, stub_embeddings):
+ source, folder = _folder(rag_home)
+ path = source / "notes.txt"
+ path.write_text("first text", encoding = "utf-8")
+ assert _run(folder["id"])["status"] == "completed"
+ before = _mapping(folder)
+
+ replacement = source / "replacement.txt"
+ replacement.write_text("other text", encoding = "utf-8")
+ os.utime(replacement, ns = (path.stat().st_atime_ns, path.stat().st_mtime_ns))
+ replacement.replace(path)
+ assert path.stat().st_size == before["size_bytes"]
+ assert path.stat().st_mtime_ns == before["mtime_ns"]
+
+ result = _run(folder["id"])
+ assert result["changed"] == 1
+ with _connection() as conn:
+ after = dict(
+ conn.execute(
+ "SELECT * FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchone()
+ )
+ assert after["inode"] != before["inode"]
+ assert after["document_id"] != before["document_id"]
+ assert store.search_lexical(conn, folder["scope"], "other", 5)
+
+
+@requires_sqlite_vec
+def test_content_identical_touch_updates_metadata_without_reembedding(
+ rag_home, stub_embeddings, monkeypatch
+):
+ source, folder = _folder(rag_home)
+ path = source / "notes.txt"
+ path.write_text("stable searchable text", encoding = "utf-8")
+ assert _run(folder["id"])["status"] == "completed"
+ before = _mapping(folder)
+ assert before["content_hash"]
+
+ os.utime(path, ns = (path.stat().st_atime_ns, path.stat().st_mtime_ns + 1_000_000))
+ monkeypatch.setattr(
+ folder_sync.ingestion,
+ "start_ingestion",
+ lambda *args, **kwargs: pytest.fail("content-identical touch was re-ingested"),
+ )
+ result = _run(folder["id"])
+ assert result["status"] == "completed"
+ assert result["changed"] == 0
+ with _connection() as conn:
+ after = dict(
+ conn.execute(
+ "SELECT * FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchone()
+ )
+ assert after["document_id"] == before["document_id"]
+ assert after["mtime_ns"] != before["mtime_ns"]
+ assert store.search_lexical(conn, folder["scope"], "stable", 5)
+
+
+@requires_sqlite_vec
+def test_sync_requests_are_atomically_deduplicated_and_history_is_pruned(rag_home, monkeypatch):
+ _, folder = _folder(rag_home)
+ barrier = threading.Barrier(3)
+ results = []
+
+ def request():
+ barrier.wait()
+ results.append(folder_sync.request_sync(folder["id"]))
+
+ threads = [threading.Thread(target = request) for _ in range(2)]
+ for thread in threads:
+ thread.start()
+ barrier.wait()
+ for thread in threads:
+ thread.join()
+ assert len(set(results)) == 1
+ folder_sync._enqueue_periodic()
+
+ with _connection() as conn:
+ assert (
+ conn.execute(
+ "SELECT COUNT(*) AS n FROM linked_folder_sync_jobs "
+ "WHERE folder_id=? AND status IN ('pending','running')",
+ (folder["id"],),
+ ).fetchone()["n"]
+ == 1
+ )
+ conn.execute(
+ "UPDATE linked_folder_sync_jobs SET status='completed', completed_at=created_at"
+ )
+ conn.commit()
+
+ monkeypatch.setattr(folder_sync.config, "FOLDER_JOB_HISTORY_LIMIT", 1)
+ active = folder_sync.request_sync(folder["id"])
+ with _connection() as conn:
+ terminal_count = conn.execute(
+ "SELECT COUNT(*) AS n FROM linked_folder_sync_jobs "
+ "WHERE status IN ('completed','failed')"
+ ).fetchone()["n"]
+ assert terminal_count <= 1
+ assert (
+ conn.execute(
+ "SELECT id FROM linked_folder_sync_jobs WHERE status='pending'"
+ ).fetchone()["id"]
+ == active
+ )
+
+
+@requires_sqlite_vec
+def test_rebuild_requested_during_running_sync_queues_a_successor(rag_home):
+ _, folder = _folder(rag_home)
+ sync_job = folder_sync.request_sync(folder["id"])
+ with _connection() as conn:
+ conn.execute("UPDATE linked_folder_sync_jobs SET status='running' WHERE id=?", (sync_job,))
+ conn.commit()
+
+ assert folder_sync.request_sync(folder["id"], rebuild = True) == sync_job
+ folder_sync.reconcile_folder(sync_job)
+
+ with _connection() as conn:
+ successor = conn.execute(
+ "SELECT * FROM linked_folder_sync_jobs WHERE folder_id=? AND status='pending'",
+ (folder["id"],),
+ ).fetchone()
+ assert successor is not None
+ assert successor["id"] != sync_job
+ assert successor["kind"] == "rebuild"
+
+
+@requires_sqlite_vec
+def test_requested_rebuild_promotes_an_intervening_pending_sync(rag_home):
+ _, folder = _folder(rag_home)
+ completed = folder_sync.request_sync(folder["id"])
+ with _connection() as conn:
+ conn.execute(
+ "UPDATE linked_folder_sync_jobs SET status='completed', successor_kind='rebuild' "
+ "WHERE id=?",
+ (completed,),
+ )
+ pending = "intervening-sync"
+ conn.execute(
+ "INSERT INTO linked_folder_sync_jobs"
+ "(id, folder_id, kind, status, stage, created_at) "
+ "VALUES(?,?,'sync','pending','queued',?)",
+ (pending, folder["id"], folder_sync._now()),
+ )
+ conn.commit()
+
+ folder_sync._queue_successor(completed)
+ with _connection() as conn:
+ successor = conn.execute(
+ "SELECT kind, successor_kind FROM linked_folder_sync_jobs WHERE id=?", (pending,)
+ ).fetchone()
+ assert tuple(successor) == ("rebuild", None)
+ assert (
+ conn.execute(
+ "SELECT successor_kind FROM linked_folder_sync_jobs WHERE id=?", (completed,)
+ ).fetchone()["successor_kind"]
+ is None
+ )
+
+
+@requires_sqlite_vec
+def test_pending_rebuild_promotion_clears_a_recovered_successor_flag(rag_home):
+ _, folder = _folder(rag_home)
+ job_id = folder_sync.request_sync(folder["id"])
+ with _connection() as conn:
+ conn.execute(
+ "UPDATE linked_folder_sync_jobs SET successor_kind='rebuild' WHERE id=?", (job_id,)
+ )
+ conn.commit()
+
+ assert folder_sync.request_sync(folder["id"], rebuild = True) == job_id
+ with _connection() as conn:
+ job = conn.execute(
+ "SELECT kind, successor_kind FROM linked_folder_sync_jobs WHERE id=?", (job_id,)
+ ).fetchone()
+ assert tuple(job) == ("rebuild", None)
+
+
+@requires_sqlite_vec
+def test_startup_recovers_terminal_rebuild_handoff(rag_home):
+ _, folder = _folder(rag_home)
+ completed = folder_sync.request_sync(folder["id"])
+ with _connection() as conn:
+ conn.execute(
+ "UPDATE linked_folder_sync_jobs SET status='completed', successor_kind='rebuild', "
+ "completed_at=created_at WHERE id=?",
+ (completed,),
+ )
+ conn.commit()
+
+ folder_sync._recover_startup_state()
+
+ with _connection() as conn:
+ successor = conn.execute(
+ "SELECT * FROM linked_folder_sync_jobs WHERE folder_id=? AND status='pending'",
+ (folder["id"],),
+ ).fetchone()
+ assert successor is not None
+ assert successor["kind"] == "rebuild"
+ assert (
+ conn.execute(
+ "SELECT successor_kind FROM linked_folder_sync_jobs WHERE id=?", (completed,)
+ ).fetchone()["successor_kind"]
+ is None
+ )
+
+
+@requires_sqlite_vec
+def test_global_folder_list_resolves_scope_name(rag_home, monkeypatch):
+ from routes.rag import list_linked_folders
+ from storage import studio_db
+
+ monkeypatch.setattr(studio_db, "list_chat_projects", lambda **kwargs: [])
+
+ with _connection() as conn:
+ store.create_kb(conn, name = "Knowledge One", kb_id = "kb1")
+ source = rag_home / "source"
+ source.mkdir()
+ folder_sync.create_folder(scope_type = "knowledge_base", scope_id = "kb1", path = str(source))
+ result = list_linked_folders(scope_type = None, scope_id = None, subject = "test")
+ assert result["linkedFolders"][0]["scopeName"] == "Knowledge One"
+
+
+@requires_sqlite_vec
+def test_unexpected_reconcile_failure_resets_folder_status(rag_home, monkeypatch):
+ _, folder = _folder(rag_home)
+ job_id = folder_sync.request_sync(folder["id"])
+ with _connection() as conn:
+ conn.execute("UPDATE linked_folders SET status='syncing' WHERE id=?", (folder["id"],))
+ conn.commit()
+ monkeypatch.setattr(
+ folder_sync,
+ "_reconcile_folder",
+ lambda value: (_ for _ in ()).throw(RuntimeError("unexpected")),
+ )
+ folder_sync.reconcile_folder(job_id)
+ current = folder_sync.get_folder(folder["id"])
+ assert current["status"] == "error"
+ assert current["last_error"] == "unexpected"
+
+
+@requires_sqlite_vec
+def test_reconcile_errors_do_not_persist_native_paths(rag_home, monkeypatch):
+ source, folder = _folder(rag_home)
+ private_path = source / "private" / "notes.txt"
+ monkeypatch.setattr(
+ folder_sync,
+ "_scan",
+ lambda *args: (_ for _ in ()).throw(OSError(f"cannot read {private_path}")),
+ )
+
+ result = _run(folder["id"])
+ current = folder_sync.get_folder(folder["id"])
+ assert result["status"] == "failed"
+ assert str(source) not in result["error"]
+ assert str(source) not in current["last_error"]
+ assert "<native_path>" in result["error"]
+
+
+@requires_sqlite_vec
+def test_shutdown_requeues_a_scan_before_it_mutates_mappings(rag_home, monkeypatch):
+ source, folder = _folder(rag_home)
+ (source / "notes.txt").write_text("pending shutdown", encoding = "utf-8")
+ original_scan = folder_sync._scan
+
+ def stop_after_scan(*args, **kwargs):
+ result = original_scan(*args, **kwargs)
+ folder_sync._stop.set()
+ return result
+
+ monkeypatch.setattr(folder_sync, "_scan", stop_after_scan)
+ try:
+ job_id = folder_sync.request_sync(folder["id"])
+ folder_sync.reconcile_folder(job_id)
+ result = folder_sync.get_job(job_id)
+ finally:
+ folder_sync._stop.clear()
+
+ assert result["status"] == "pending"
+ assert result["stage"] == "queued"
+ with _connection() as conn:
+ assert (
+ conn.execute(
+ "SELECT 1 FROM linked_folder_files WHERE folder_id=?", (folder["id"],)
+ ).fetchone()
+ is None
+ )
+
+
+def test_start_auto_sync_queues_replacement_for_retired_live_worker(monkeypatch):
+ blocker = threading.Event()
+ released = threading.Event()
+
+ monkeypatch.setattr(folder_sync.rag_db, "RAG_AVAILABLE", True)
+ monkeypatch.setattr(folder_sync.rag_db, "rag_available", lambda: True)
+ monkeypatch.setattr(folder_sync, "_recover_startup_state", lambda: None)
+ monkeypatch.setattr(folder_sync, "_enqueue_periodic", lambda: None)
+ monkeypatch.setattr(folder_sync, "_next_job", lambda: None)
+
+ def parked():
+ blocker.wait()
+ released.set()
+
+ thread = threading.Thread(target = parked)
+ thread.start()
+ original_thread = folder_sync._thread
+ original_thread_stop = folder_sync._thread_stop
+ original_stop = folder_sync._stop.is_set()
+ folder_sync._worker_lock.acquire()
+ try:
+ folder_sync._thread = thread
+ folder_sync._thread_stop = threading.Event()
+ folder_sync._thread_stop.set()
+ folder_sync._stop.set()
+ assert folder_sync.start_auto_sync() is True
+ assert thread.is_alive()
+ assert folder_sync._thread is not thread
+ assert folder_sync._thread.is_alive()
+ finally:
+ blocker.set()
+ thread.join(timeout = 1)
+ folder_sync._worker_lock.release()
+ folder_sync.stop_auto_sync(timeout = 1)
+ if not original_stop:
+ folder_sync._stop.clear()
+ folder_sync._thread = original_thread
+ folder_sync._thread_stop = original_thread_stop
+ assert released.is_set()
+
+
+def test_start_auto_sync_skips_runtime_unavailable_rag(monkeypatch):
+ monkeypatch.setattr(folder_sync.rag_db, "RAG_AVAILABLE", True)
+ monkeypatch.setattr(folder_sync.rag_db, "rag_available", lambda: False)
+ monkeypatch.setattr(
+ folder_sync.threading,
+ "Thread",
+ lambda *args, **kwargs: pytest.fail("worker must not be created"),
+ )
+
+ assert folder_sync.start_auto_sync() is False
+
+
+def test_start_auto_sync_launches_worker_after_transient_database_error(monkeypatch):
+ created = []
+
+ class FakeThread:
+ def __init__(self, *args, **kwargs):
+ self.started = False
+ created.append(self)
+
+ def start(self):
+ self.started = True
+
+ def is_alive(self):
+ return self.started
+
+ def unavailable_while_locked():
+ raise sqlite3.OperationalError("database is locked")
+
+ original_thread = folder_sync._thread
+ original_thread_stop = folder_sync._thread_stop
+ original_stop = folder_sync._stop.is_set()
+ monkeypatch.setattr(folder_sync.rag_db, "rag_available", unavailable_while_locked)
+ monkeypatch.setattr(folder_sync.threading, "Thread", FakeThread)
+ folder_sync._thread = None
+ folder_sync._thread_stop = None
+ folder_sync._stop.clear()
+ try:
+ assert folder_sync.start_auto_sync() is True
+ assert len(created) == 1
+ assert created[0].started is True
+ finally:
+ if original_stop:
+ folder_sync._stop.set()
+ else:
+ folder_sync._stop.clear()
+ folder_sync._thread = original_thread
+ folder_sync._thread_stop = original_thread_stop
+
+
+def test_worker_reconciles_retired_scopes_before_scheduling(monkeypatch):
+ stop = threading.Event()
+ calls = []
+
+ def project_exists(project_id):
+ return project_id == "project"
+
+ monkeypatch.setattr(folder_sync, "_recover_startup_state", lambda: calls.append("jobs"))
+ monkeypatch.setattr(
+ folder_sync,
+ "reconcile_retired_scopes",
+ lambda callback: calls.append(("scopes", callback is project_exists)),
+ )
+
+ def enqueue():
+ calls.append("periodic")
+ stop.set()
+
+ monkeypatch.setattr(folder_sync, "_enqueue_periodic", enqueue)
+
+ try:
+ folder_sync._worker(stop, project_exists)
+ finally:
+ del folder_sync._worker_state.stop_event
+
+ assert calls == ["jobs", ("scopes", True), "periodic"]
+
+
+@requires_sqlite_vec
+def test_unlink_does_not_wait_to_signal_a_locally_syncing_folder(rag_home):
+ _, folder = _folder(rag_home)
+ deleted = threading.Event()
+
+ with folder_sync._folder_lock(folder["id"]):
+ thread = threading.Thread(
+ target = lambda: (folder_sync.delete_folder(folder["id"]), deleted.set())
+ )
+ thread.start()
+ thread.join(timeout = 1)
+
+ assert deleted.is_set()
+ assert folder_sync.get_folder(folder["id"]) is None
+
+
+@requires_sqlite_vec
+def test_unlink_keeps_snapshot_cleanup_retryable(rag_home, stub_embeddings, monkeypatch):
+ source, folder = _folder(rag_home)
+ (source / "notes.txt").write_text("durable unlink", encoding = "utf-8")
+ assert _run(folder["id"])["status"] == "completed"
+ with _connection() as conn:
+ document = conn.execute(
+ "SELECT id, stored_path FROM documents WHERE linked_folder_id=?",
+ (folder["id"],),
+ ).fetchone()
+ original_remove = folder_sync._remove_retired_snapshot
+ monkeypatch.setattr(
+ folder_sync,
+ "_remove_retired_snapshot",
+ lambda path: (_ for _ in ()).throw(OSError("snapshot is busy")),
+ )
+
+ with pytest.raises(OSError, match = "snapshot is busy"):
+ folder_sync.delete_folder(folder["id"])
+
+ assert folder_sync.get_folder(folder["id"])["status"] == "retired"
+ with _connection() as conn:
+ assert store.get_document(conn, document["id"]) is not None
+ assert os.path.exists(document["stored_path"])
+
+ monkeypatch.setattr(folder_sync, "_remove_retired_snapshot", original_remove)
+ assert folder_sync.delete_folder(folder["id"]) is True
+ assert folder_sync.get_folder(folder["id"]) is None
+ assert not os.path.exists(document["stored_path"])
+
+
+@requires_sqlite_vec
+def test_unlink_waits_for_a_foreign_sync_lease(rag_home):
+ from core.rag import job_leases
+
+ _, folder = _folder(rag_home)
+ job_id = folder_sync.request_sync(folder["id"])
+ with _connection() as conn:
+ conn.execute("UPDATE linked_folder_sync_jobs SET status='running' WHERE id=?", (job_id,))
+ conn.execute(
+ "INSERT INTO rag_job_leases(kind, job_id, owner_id, expires_at) "
+ "VALUES(?,?,'foreign','9999-12-31')",
+ (job_leases.FOLDER_SYNC, job_id),
+ )
+ conn.commit()
+
+ deletion = threading.Thread(target = folder_sync.delete_folder, args = (folder["id"],))
+ deletion.start()
+ deadline = time.time() + 2
+ while time.time() < deadline and folder_sync.get_folder(folder["id"])["status"] != "retired":
+ time.sleep(0.01)
+ assert deletion.is_alive()
+ with _connection() as conn:
+ conn.execute("UPDATE rag_job_leases SET expires_at='2000-01-01' WHERE job_id=?", (job_id,))
+ conn.commit()
+ deletion.join(2)
+ assert not deletion.is_alive()
+ assert folder_sync.get_folder(folder["id"]) is None
+
+
+def test_project_delete_runs_before_best_effort_rag_cleanup(monkeypatch):
+ from routes import chat_history
+
+ project = {
+ "id": "p1",
+ "name": "Project",
+ "createdAt": 1,
+ "updatedAt": 1,
+ }
+ calls = []
+ monkeypatch.setattr(chat_history, "get_chat_project", lambda project_id: project)
+ monkeypatch.setattr(chat_history, "list_chat_threads", lambda **kwargs: [])
+ monkeypatch.setattr(chat_history, "_cancel_active_research", lambda request, ids: None)
+
+ def delete(*args, **kwargs):
+ calls.append(("delete", threading.get_ident()))
+ return project
+
+ def cleanup(project_id):
+ calls.append(("cleanup", threading.get_ident(), project_id))
+ raise sqlite3.OperationalError("database is busy")
+
+ monkeypatch.setattr(chat_history, "delete_chat_project", delete)
+ monkeypatch.setattr(chat_history, "_delete_project_rag_sources", cleanup)
+
+ event_loop_thread = threading.get_ident()
+ result = asyncio.run(
+ chat_history.delete_project("p1", SimpleNamespace(), current_subject = "test")
+ )
+
+ assert result.id == "p1"
+ assert [call[0] for call in calls] == ["delete", "cleanup"]
+ assert all(call[1] != event_loop_thread for call in calls)
+ assert calls[1][2] == "p1"
+
+
+def test_project_post_commit_file_failure_still_retires_rag(monkeypatch):
+ from routes import chat_history
+
+ project = {"id": "p1", "name": "Project", "createdAt": 1, "updatedAt": 1}
+ owner_exists = True
+ calls = []
+
+ def get_project(project_id):
+ return project if owner_exists else None
+
+ def delete(*args, **kwargs):
+ nonlocal owner_exists
+ calls.append("delete")
+ owner_exists = False
+ raise OSError("workspace cleanup failed")
+
+ def cleanup(project_id):
+ calls.append(f"cleanup:{project_id}")
+
+ monkeypatch.setattr(chat_history, "get_chat_project", get_project)
+ monkeypatch.setattr(chat_history, "list_chat_threads", lambda **kwargs: [])
+ monkeypatch.setattr(chat_history, "_cancel_active_research", lambda request, ids: None)
+ monkeypatch.setattr(chat_history, "delete_chat_project", delete)
+ monkeypatch.setattr(chat_history, "_delete_project_rag_sources", cleanup)
+
+ with pytest.raises(OSError, match = "workspace cleanup failed"):
+ asyncio.run(chat_history.delete_project("p1", SimpleNamespace(), current_subject = "test"))
+
+ assert calls == ["delete", "cleanup:p1"]
+
+
+@requires_sqlite_vec
+def test_project_cleanup_persists_retirement_when_rag_is_unavailable(rag_home, monkeypatch):
+ from routes import chat_history
+
+ source = rag_home / "unavailable-project"
+ source.mkdir()
+ folder = folder_sync.create_folder(scope_type = "project", scope_id = "p1", path = str(source))
+ monkeypatch.setattr(rag_db, "rag_available", lambda: False)
+
+ chat_history._delete_project_rag_sources("p1")
+
+ with _connection(metadata = True) as metadata:
+ retired = metadata.execute(
+ "SELECT purged_at FROM linked_folder_retired_scopes WHERE scope=?",
+ (store.project_scope("p1"),),
+ ).fetchone()
+ persisted = metadata.execute(
+ "SELECT auto_sync, status FROM linked_folders WHERE id=?", (folder["id"],)
+ ).fetchone()
+ assert retired is not None
+ assert retired["purged_at"] is None
+ assert dict(persisted) == {"auto_sync": 0, "status": "retired"}
+
+
+@requires_sqlite_vec
+def test_startup_retires_and_deletes_an_orphaned_project_scope(rag_home, stub_embeddings):
+ scope = store.project_scope("deleted-project")
+ source = rag_home / "deleted-project"
+ source.mkdir()
+ (source / "notes.txt").write_text("managed snapshot", encoding = "utf-8")
+ folder = folder_sync.create_folder(
+ scope_type = "project", scope_id = "deleted-project", path = str(source)
+ )
+ assert _run(folder["id"])["status"] == "completed"
+ with _connection() as conn:
+ document = conn.execute(
+ "SELECT id, stored_path FROM documents WHERE scope=?", (scope,)
+ ).fetchone()
+ assert document is not None
+ assert os.path.isfile(document["stored_path"])
+
+ reconciled = folder_sync.reconcile_retired_scopes(lambda project_id: False)
+
+ assert reconciled == {"retired": [scope], "deleted": [scope], "restored": []}
+ assert folder_sync.get_folder(folder["id"]) is None
+ assert folder_sync.scope_retired(scope) is True
+ with _connection() as conn:
+ assert conn.execute("SELECT 1 FROM documents WHERE scope=?", (scope,)).fetchone() is None
+ tombstone = conn.execute(
+ "SELECT purged_at FROM linked_folder_retired_scopes WHERE scope=?", (scope,)
+ ).fetchone()
+ assert tombstone["purged_at"] is not None
+ assert not os.path.exists(document["stored_path"])
+
+
+@requires_sqlite_vec
+def test_retired_scope_waits_for_manual_ingestion_before_purging(
+ rag_home, stub_embeddings, monkeypatch
+):
+ from core.rag import ingestion
+ from utils.paths import ensure_dir, rag_uploads_root
+
+ scope = store.project_scope("uploading-project")
+ upload = ensure_dir(rag_uploads_root()) / "in-flight.txt"
+ upload.write_text("durable in-flight words", encoding = "utf-8")
+ parsing = threading.Event()
+ release = threading.Event()
+ original_parse = ingestion.parsers.parse
+
+ def blocked_parse(path):
+ parsing.set()
+ assert release.wait(5)
+ return original_parse(path)
+
+ monkeypatch.setattr(ingestion.parsers, "parse", blocked_parse)
+ document_id, job_id = ingestion.start_ingestion(
+ scope, None, None, upload.name, str(upload), project_id = "uploading-project"
+ )
+ assert parsing.wait(5)
+ folder_sync.retire_scope(scope)
+ assert folder_sync.delete_retired_scope(scope) is False
+
+ release.set()
+ deadline = time.time() + 5
+ while time.time() < deadline and ingestion.get_job_status(job_id)["status"] != "completed":
+ time.sleep(0.05)
+ while time.time() < deadline and not folder_sync.delete_retired_scope(scope):
+ time.sleep(0.05)
+
+ assert folder_sync.scope_retired(scope) is True
+ with _connection() as conn:
+ assert store.get_document(conn, document_id) is None
+ assert conn.execute("SELECT 1 FROM ingestion_jobs WHERE id=?", (job_id,)).fetchone() is None
+ tombstone = conn.execute(
+ "SELECT purged_at FROM linked_folder_retired_scopes WHERE scope=?", (scope,)
+ ).fetchone()
+ assert tombstone["purged_at"] is not None
+ assert not upload.exists()
+
+
+@requires_sqlite_vec
+def test_retired_scope_cleanup_keeps_retry_state_when_file_removal_fails(
+ rag_home, stub_embeddings, monkeypatch
+):
+ scope = store.project_scope("retry-project")
+ source = rag_home / "retry-project"
+ source.mkdir()
+ (source / "notes.txt").write_text("managed snapshot", encoding = "utf-8")
+ folder = folder_sync.create_folder(
+ scope_type = "project", scope_id = "retry-project", path = str(source)
+ )
+ assert _run(folder["id"])["status"] == "completed"
+ folder_sync.retire_scope(scope)
+ monkeypatch.setattr(
+ folder_sync,
+ "_remove_retired_snapshot",
+ lambda path: (_ for _ in ()).throw(OSError("snapshot is busy")),
+ )
+
+ with pytest.raises(OSError, match = "snapshot is busy"):
+ folder_sync.delete_retired_scope(scope)
+
+ assert folder_sync.scope_retired(scope) is True
+ assert folder_sync.get_folder(folder["id"])["status"] == "retired"
+ with _connection() as conn:
+ assert (
+ conn.execute("SELECT 1 FROM documents WHERE scope=?", (scope,)).fetchone() is not None
+ )
+ tombstone = conn.execute(
+ "SELECT purged_at FROM linked_folder_retired_scopes WHERE scope=?", (scope,)
+ ).fetchone()
+ assert tombstone["purged_at"] is None
+
+
+@requires_sqlite_vec
+def test_project_writer_contention_does_not_retire_a_live_project(rag_home, monkeypatch):
+ from routes import chat_history
+ from storage import studio_db
+
+ project = studio_db.upsert_chat_project(
+ {
+ "id": "p1",
+ "name": "Project",
+ "createdAt": 1,
+ "updatedAt": 1,
+ }
+ )
+ source = rag_home / "locked-project-delete"
+ source.mkdir()
+ folder = folder_sync.create_folder(
+ scope_type = "project", scope_id = project["id"], path = str(source)
+ )
+ blocker = studio_db.get_connection()
+ original_get_connection = studio_db.get_connection
+
+ def short_timeout_connection(*args, **kwargs):
+ conn = original_get_connection()
+ conn.execute("PRAGMA busy_timeout = 10")
+ return conn
+
+ blocker.execute("BEGIN IMMEDIATE")
+ monkeypatch.setattr(studio_db, "get_connection", short_timeout_connection)
+ try:
+ with pytest.raises(sqlite3.OperationalError, match = "database is locked"):
+ asyncio.run(
+ chat_history.delete_project(
+ project["id"], SimpleNamespace(), current_subject = "test"
+ )
+ )
+ assert folder_sync.scope_retired(store.project_scope(project["id"])) is False
+ assert folder_sync.get_folder(folder["id"])["status"] == folder["status"]
+ finally:
+ blocker.rollback()
+ blocker.close()
+
+
+def test_project_upload_cleans_saved_file_when_scope_retires_after_save(rag_home, monkeypatch):
+ from routes import rag as rag_routes
+ from storage import studio_db
+ from utils.paths import ensure_dir, rag_uploads_root
+
+ project_id = "project"
+ scope = store.project_scope(project_id)
+ saved_path = ensure_dir(rag_uploads_root()) / "race.txt"
+ retired = False
+
+ def resolve_upload(*args, **kwargs):
+ nonlocal retired
+ saved_path.write_text("saved", encoding = "utf-8")
+ retired = True
+ return str(saved_path), "race.txt"
+
+ monkeypatch.setattr(rag_routes.rag_db, "rag_available", lambda: True)
+ monkeypatch.setattr(studio_db, "get_chat_project", lambda value: {"id": value})
+ monkeypatch.setattr(
+ rag_routes.folder_sync,
+ "scope_retired",
+ lambda value: value == scope and retired,
+ )
+ monkeypatch.setattr(rag_routes, "_resolve_document_upload", resolve_upload)
+ monkeypatch.setattr(
+ rag_routes.ingestion,
+ "start_ingestion",
+ lambda *args, **kwargs: pytest.fail("retired project upload must not ingest"),
+ )
+
+ with pytest.raises(Exception) as exc_info:
+ asyncio.run(rag_routes.upload_project_document(project_id, subject = "test"))
+
+ assert getattr(exc_info.value, "status_code", None) == 409
+ assert not saved_path.exists()
+
+
+@requires_sqlite_vec
[email protected]("scope_type", ["knowledge_base", "project"])
+def test_upload_rechecks_owner_after_saving_file(rag_home, monkeypatch, scope_type):
+ from routes import rag as rag_routes
+ from storage import studio_db
+ from utils.paths import ensure_dir, rag_uploads_root
+
+ owner_id = "owner"
+ owner_exists = True
+ saved_path = ensure_dir(rag_uploads_root()) / f"missing-{scope_type}.txt"
+
+ def resolve_upload(*args, **kwargs):
+ nonlocal owner_exists
+ saved_path.write_text("saved", encoding = "utf-8")
+ owner_exists = False
+ return str(saved_path), saved_path.name
+
+ monkeypatch.setattr(rag_routes.rag_db, "rag_available", lambda: True)
+ monkeypatch.setattr(rag_routes.folder_sync, "scope_retired", lambda scope: False)
+ monkeypatch.setattr(rag_routes, "_resolve_document_upload", resolve_upload)
+ monkeypatch.setattr(
+ rag_routes.ingestion,
+ "start_ingestion",
+ lambda *args, **kwargs: pytest.fail("an ownerless upload must not ingest"),
+ )
+ if scope_type == "knowledge_base":
+ monkeypatch.setattr(
+ rag_routes.store,
+ "get_kb",
+ lambda conn, value: {"id": value} if owner_exists else None,
+ )
+ upload = 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")
+
+ with pytest.raises(Exception) as exc_info:
+ asyncio.run(upload)
+
+ assert getattr(exc_info.value, "status_code", None) == 404
+ assert not saved_path.exists()
+
+
[email protected]("scope_type", ["knowledge_base", "project"])
+def test_linked_folder_rechecks_owner_after_resolving_lease(rag_home, monkeypatch, scope_type):
+ from fastapi import HTTPException
+ from routes import rag as rag_routes
+
+ owner_exists = True
+
+ def resolve_path(lease):
+ nonlocal owner_exists
+ owner_exists = False
+ return str(rag_home), (rag_home.stat().st_dev, rag_home.stat().st_ino)
+
+ def require_owner(kind, owner_id):
+ if not owner_exists:
+ raise HTTPException(status_code = 404, detail = "Owner not found")
+
+ monkeypatch.setattr(rag_routes, "_resolve_linked_folder_path", resolve_path)
+ monkeypatch.setattr(rag_routes, "_require_scope_owner", require_owner)
+ monkeypatch.setattr(
+ rag_routes.folder_sync,
+ "create_folder_with_sync",
+ lambda **kwargs: pytest.fail("an ownerless folder must not be linked"),
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ rag_routes._create_linked_folder(
+ scope_type,
+ "owner",
+ rag_routes.LinkFolderRequest(nativePathLease = "lease"),
+ )
+
+ assert exc_info.value.status_code == 404
+
+
+@requires_sqlite_vec
+def test_project_rag_cleanup_atomically_removes_retired_scope(rag_home):
+ from routes import chat_history
+
+ scope = store.project_scope("project")
+ folders = []
+ for name in ("first", "second"):
+ source = rag_home / name
+ source.mkdir()
+ folders.append(
+ folder_sync.create_folder(scope_type = "project", scope_id = "project", path = str(source))
+ )
+ chat_history._delete_project_rag_sources("project")
+
+ assert folder_sync.list_folders(scope) == []
+ assert folder_sync.scope_retired(scope) is True
+ replacement = rag_home / "replacement"
+ replacement.mkdir()
+ with pytest.raises(ValueError, match = "no longer exists"):
+ folder_sync.create_folder(
+ scope_type = "project",
+ scope_id = "project",
+ path = str(replacement),
+ )
+
+
+@requires_sqlite_vec
+def test_kb_deletion_retries_retired_scope_cleanup_after_failure(
+ rag_home, stub_embeddings, monkeypatch
+):
+ from routes import rag as rag_routes
+
+ with _connection() as conn:
+ store.create_kb(conn, name = "Knowledge", kb_id = "knowledge")
+ folders = []
+ for name in ("kb-first", "kb-second"):
+ source = rag_home / name
+ source.mkdir()
+ folders.append(
+ folder_sync.create_folder(
+ scope_type = "knowledge_base", scope_id = "knowledge", path = str(source)
+ )
+ )
+ (rag_home / "kb-first" / "notes.txt").write_text("managed snapshot", encoding = "utf-8")
+ assert _run(folders[0]["id"])["status"] == "completed"
+ with _connection() as conn:
+ document = conn.execute(
+ "SELECT id, stored_path FROM documents WHERE linked_folder_id=?", (folders[0]["id"],)
+ ).fetchone()
+ stored_path = document["stored_path"]
+ assert os.path.isfile(stored_path)
+ original_cleanup = folder_sync.delete_retired_scope
+ monkeypatch.setattr(
+ folder_sync,
+ "delete_retired_scope",
+ lambda scope, **kwargs: (_ for _ in ()).throw(sqlite3.OperationalError("database is busy")),
+ )
+ assert rag_routes.delete_knowledge_base("knowledge", subject = "test") == {"ok": True}
+
+ remaining = folder_sync.list_folders(store.kb_scope("knowledge"))
+ assert {folder["id"] for folder in remaining} == {folder["id"] for folder in folders}
+ assert {folder["status"] for folder in remaining} == {"retired"}
+ assert folder_sync.scope_retired(store.kb_scope("knowledge")) is True
+ assert os.path.exists(stored_path)
+ assert rag_routes.list_kb_documents("knowledge", subject = "test") == {"documents": []}
+ assert rag_routes.list_all_uploaded_documents(subject = "test") == {"documents": []}
+ with pytest.raises(Exception) as exc_info:
+ rag_routes.search(
+ rag_routes.SearchRequest(query = "managed", kb_id = "knowledge", mode = "lexical"),
+ subject = "test",
+ )
+ assert getattr(exc_info.value, "status_code", None) == 404
+ with pytest.raises(Exception) as exc_info:
+ rag_routes.preview_target(document["id"], subject = "test")
+ assert getattr(exc_info.value, "status_code", None) == 404
+ with _connection() as conn:
+ assert (
+ conn.execute(
+ "SELECT 1 FROM documents WHERE scope=?", (store.kb_scope("knowledge"),)
+ ).fetchone()
+ is not None
+ )
+ assert store.all_chunks_for_scope(conn, store.kb_scope("knowledge")) == []
+ assert store.scope_token_estimate(conn, store.kb_scope("knowledge")) == 0
+ monkeypatch.setattr(folder_sync, "delete_retired_scope", original_cleanup)
+
+ reconciled = folder_sync.reconcile_retired_scopes(lambda project_id: False)
+
+ assert reconciled == {
+ "retired": [],
+ "deleted": [store.kb_scope("knowledge")],
+ "restored": [],
+ }
+ assert folder_sync.list_folders(store.kb_scope("knowledge")) == []
+ assert folder_sync.scope_retired(store.kb_scope("knowledge")) is True
+ assert not os.path.exists(stored_path)
+
+
+@requires_sqlite_vec
+def test_kb_deletion_rolls_back_scope_before_any_folder_cleanup_on_failure(rag_home, monkeypatch):
+ from routes import rag as rag_routes
+
+ with _connection() as conn:
+ store.create_kb(conn, name = "Knowledge", kb_id = "knowledge")
+ source = rag_home / "failed-kb-delete"
+ source.mkdir()
+ folder = folder_sync.create_folder(
+ scope_type = "knowledge_base",
+ scope_id = "knowledge",
+ path = str(source),
+ auto_sync = False,
+ )
+ cleaned = []
+ monkeypatch.setattr(
+ rag_routes.store,
+ "delete_kb",
+ lambda *args, **kwargs: (_ for _ in ()).throw(sqlite3.OperationalError("database is busy")),
+ )
+ monkeypatch.setattr(
+ rag_routes.folder_sync,
+ "delete_folder",
+ lambda folder_id: cleaned.append(folder_id),
+ )
+
+ with pytest.raises(sqlite3.OperationalError, match = "database is busy"):
+ rag_routes.delete_knowledge_base("knowledge", subject = "test")
+
+ assert cleaned == []
+ assert folder_sync.scope_retired(store.kb_scope("knowledge")) is False
+ restored = folder_sync.get_folder(folder["id"])
+ assert restored["auto_sync"] == folder["auto_sync"]
+ assert restored["status"] == folder["status"]
+ with _connection() as conn:
+ assert store.get_kb(conn, "knowledge") is not None
+
+
+@requires_sqlite_vec
+def test_kb_writer_contention_cannot_commit_retirement_without_deletion(rag_home, monkeypatch):
+ from routes import rag as rag_routes
+
+ with _connection() as conn:
+ store.create_kb(conn, name = "Knowledge", kb_id = "knowledge")
+ source = rag_home / "locked-kb-delete"
+ source.mkdir()
+ folder = folder_sync.create_folder(
+ scope_type = "knowledge_base", scope_id = "knowledge", path = str(source)
+ )
+ blocker = rag_db.get_metadata_connection()
+ original_get_connection = rag_db.get_connection
+
+ def short_timeout_connection(*args, **kwargs):
+ conn = original_get_connection()
+ conn.execute("PRAGMA busy_timeout = 10")
+ return conn
+
+ blocker.execute("BEGIN IMMEDIATE")
+ monkeypatch.setattr(rag_db, "get_connection", short_timeout_connection)
+ try:
+ with pytest.raises(sqlite3.OperationalError, match = "database is locked"):
+ rag_routes.delete_knowledge_base("knowledge", subject = "test")
+ assert (
+ blocker.execute("SELECT 1 FROM knowledge_bases WHERE id='knowledge'").fetchone()
+ is not None
+ )
+ assert (
+ blocker.execute(
+ "SELECT 1 FROM linked_folder_retired_scopes WHERE scope=?",
+ (store.kb_scope("knowledge"),),
+ ).fetchone()
+ is None
+ )
+ persisted = blocker.execute(
+ "SELECT auto_sync, status FROM linked_folders WHERE id=?", (folder["id"],)
+ ).fetchone()
+ assert dict(persisted) == {"auto_sync": folder["auto_sync"], "status": folder["status"]}
+ finally:
+ blocker.rollback()
+ blocker.close()
+
+
+@requires_sqlite_vec
+def test_kb_upload_rejects_retired_scope_before_saving(rag_home, monkeypatch):
+ from routes import rag as rag_routes
+
+ with _connection() as conn:
+ store.create_kb(conn, name = "Knowledge", kb_id = "knowledge")
+ folder_sync.retire_scope(store.kb_scope("knowledge"))
+ monkeypatch.setattr(
+ rag_routes,
+ "_resolve_document_upload",
+ lambda *args, **kwargs: pytest.fail("retired KB upload must be rejected before saving"),
+ )
+
+ with pytest.raises(Exception) as exc_info:
+ asyncio.run(rag_routes.upload_kb_document("knowledge", subject = "test"))
+ assert getattr(exc_info.value, "status_code", None) == 409
+
+
+def test_preview_containment_is_component_aware(rag_home):
+ from routes.rag import _is_managed_preview_path
+ from utils.paths import ensure_dir, rag_uploads_root
+
+ uploads = ensure_dir(rag_uploads_root())
+ inside = uploads / "doc.txt"
+ inside.write_text("inside", encoding = "utf-8")
+ prefix_sibling = uploads.parent / f"{uploads.name}-evil" / "doc.txt"
+ prefix_sibling.parent.mkdir()
+ prefix_sibling.write_text("outside", encoding = "utf-8")
+
+ assert _is_managed_preview_path(str(inside))
+ assert not _is_managed_preview_path(str(prefix_sibling))
+
+
+@requires_sqlite_vec
+def test_unrelated_ingest_failure_still_removes_deleted_sources(
+ rag_home, stub_embeddings, monkeypatch
+):
+ source, folder = _folder(rag_home)
+ (source / "keep.txt").write_text("durable keeper", encoding = "utf-8")
+ (source / "doomed.txt").write_text("removable words", encoding = "utf-8")
+ assert _run(folder["id"])["status"] == "completed"
+
+ (source / "doomed.txt").unlink()
+ (source / "poison.txt").write_text("never indexes", encoding = "utf-8")
+ real_start = folder_sync.ingestion.start_ingestion
+ monkeypatch.setattr(
+ folder_sync.ingestion,
+ "start_ingestion",
+ lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("embed unavailable"))
+ if args[3] == "poison.txt"
+ else real_start(*args, **kwargs),
+ )
+
+ # each vanished path gets one grace pass before it is removed anyway
+ assert _run(folder["id"])["deleted"] == 0
+ result = _run(folder["id"])
+
+ assert result["status"] == "failed"
+ assert result["deleted"] == 1
+ assert "poison.txt" in result["error"]
+ 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 == {"keep.txt"}
+ assert not store.search_lexical(conn, folder["scope"], "removable", 5)
+
+
+@requires_sqlite_vec
+def test_sync_requested_during_a_running_sync_queues_a_successor(rag_home):
+ _, folder = _folder(rag_home)
+ running = folder_sync.request_sync(folder["id"])
+ with _connection() as conn:
+ conn.execute("UPDATE linked_folder_sync_jobs SET status='running' WHERE id=?", (running,))
+ conn.commit()
+
+ assert folder_sync.request_sync(folder["id"]) == running
+ folder_sync.reconcile_folder(running)
+
+ successor = _row(
+ "SELECT id, kind FROM linked_folder_sync_jobs WHERE folder_id=? AND status='pending'",
+ (folder["id"],),
+ )
+ assert successor is not None
+ assert successor["id"] != running
+ assert successor["kind"] == "sync"
+
+
+@requires_sqlite_vec
+def test_a_queued_rebuild_is_not_downgraded_by_a_later_sync_request(rag_home):
+ _, folder = _folder(rag_home)
+ running = folder_sync.request_sync(folder["id"])
+ with _connection() as conn:
+ conn.execute("UPDATE linked_folder_sync_jobs SET status='running' WHERE id=?", (running,))
+ conn.commit()
+
+ folder_sync.request_sync(folder["id"], rebuild = True)
+ folder_sync.request_sync(folder["id"])
+
+ assert (
+ _row("SELECT successor_kind FROM linked_folder_sync_jobs WHERE id=?", (running,))[
+ "successor_kind"
+ ]
+ == "rebuild"
+ )
+
+
+def test_failure_summary_names_the_files_and_caps_the_list():
+ assert folder_sync._failure_summary([]) is None
+ assert folder_sync._failure_summary(["b.txt", "a.txt"]) == (
+ "2 file(s) could not be indexed (a.txt, b.txt)"
+ )
+ summary = folder_sync._failure_summary([f"f{index}.txt" for index in range(6)])
+ assert summary.startswith("6 file(s) could not be indexed (f0.txt, f1.txt, f2.txt and 3 more)")
+
+
+@requires_sqlite_vec
+def test_a_rewritten_rename_retains_the_prior_document_until_it_reindexes(
+ rag_home, stub_embeddings, monkeypatch
+):
+ source, folder = _folder(rag_home)
+ original = source / "report.txt"
+ original.write_text("durable travelling words", encoding = "utf-8")
+ assert _run(folder["id"])["status"] == "completed"
+
+ # an atomic re-save after a rename shares neither inode nor content with the original
+ renamed = source / "report-final.txt"
+ renamed.write_text("rewritten content that fails", encoding = "utf-8")
+ original.unlink()
+ monkeypatch.setattr(
+ folder_sync.ingestion,
+ "start_ingestion",
+ lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("embed unavailable")),
+ )
+
+ result = _run(folder["id"])
+
+ assert result["status"] == "failed"
+ assert result["deleted"] == 0
+ with _connection() as conn:
+ assert store.search_lexical(conn, folder["scope"], "travelling", 5)
+
+
+@requires_sqlite_vec
+def test_an_unreadable_file_stops_withholding_removals_after_one_pass(
+ rag_home, stub_embeddings, monkeypatch
+):
+ source, folder = _folder(rag_home)
+ (source / "keep.txt").write_text("durable keeper", encoding = "utf-8")
+ (source / "doomed.txt").write_text("removable words", encoding = "utf-8")
+ assert _run(folder["id"])["status"] == "completed"
+
+ (source / "doomed.txt").unlink()
+ (source / "unreadable.txt").write_text("cannot be copied", encoding = "utf-8")
+ monkeypatch.setattr(
+ folder_sync,
+ "_snapshot",
+ lambda *args, **kwargs: (_ for _ in ()).throw(OSError("source unreadable")),
+ )
+
+ assert _run(folder["id"])["deleted"] == 0
+ assert _run(folder["id"])["deleted"] == 1
+ with _connection() as conn:
+ assert not store.search_lexical(conn, folder["scope"], "removable", 5)
+
+
+@requires_sqlite_vec
+def test_a_failing_file_that_keeps_changing_cannot_block_removals(
+ rag_home, stub_embeddings, monkeypatch
+):
+ source, folder = _folder(rag_home)
+ (source / "keep.txt").write_text("durable keeper", encoding = "utf-8")
+ (source / "doomed.txt").write_text("removable words", encoding = "utf-8")
+ assert _run(folder["id"])["status"] == "completed"
+
+ (source / "doomed.txt").unlink()
+ churn = source / "churn.txt"
+ monkeypatch.setattr(
+ folder_sync.ingestion,
+ "start_ingestion",
+ lambda *args, **kwargs: (_ for _ in ()).throw(RuntimeError("embed unavailable")),
+ )
+ churn.write_text("attempt one", encoding = "utf-8")
+ assert _run(folder["id"])["deleted"] == 0
+ churn.write_text("attempt two, a different size entirely", encoding = "utf-8")
+
+ assert _run(folder["id"])["deleted"] == 1
+ with _connection() as conn:
+ assert not store.search_lexical(conn, folder["scope"], "removable", 5)
+
+
+@requires_sqlite_vec
+def test_job_events_emits_a_keepalive_while_a_job_is_quiet(rag_home, monkeypatch):
+ _, folder = _folder(rag_home)
+ job_id = folder_sync.request_sync(folder["id"])
+ monkeypatch.setattr(folder_sync, "_JOB_EVENT_KEEPALIVE_S", 0.0)
+ monkeypatch.setattr(folder_sync.time, "sleep", lambda _seconds: None)
+
+ events = []
+ for event in folder_sync.job_events(job_id):
+ events.append(event)
+ if len(events) == 3:
+ break
+
+ assert events[0] is not None
+ assert events[1:] == [None, None]
+
+
+@requires_sqlite_vec
+def test_a_project_recreated_during_delete_keeps_its_rag_scope(rag_home, monkeypatch):
+ from routes import chat_history
+
+ scope = store.project_scope("p1")
+ # the row delete has committed and another client has already created the id again
+ monkeypatch.setattr(chat_history, "get_chat_project", lambda project_id: {"id": project_id})
+
+ chat_history._delete_project_rag_sources("p1")
+
+ assert folder_sync.scope_retired(scope) is False
+
+
+@requires_sqlite_vec
+def test_reconciliation_restores_a_scope_whose_project_came_back(rag_home):
+ scope = store.project_scope("p1")
+ source = rag_home / "recreated-project"
+ source.mkdir()
+ folder_sync.create_folder(scope_type = "project", scope_id = "p1", path = str(source))
+ folder_sync.retire_scope(scope)
+ assert folder_sync.scope_retired(scope) is True
+
+ result = folder_sync.reconcile_retired_scopes(lambda project_id: project_id == "p1")
+
+ assert result["restored"] == [scope]
+ assert result["deleted"] == []
+ assert folder_sync.scope_retired(scope) is False
+
+
+@requires_sqlite_vec
+def test_periodic_retirement_checks_ownership_under_the_scope_lock(rag_home):
+ scope = store.project_scope("p1")
+ source = rag_home / "recreated-under-lock"
+ source.mkdir()
+ folder = folder_sync.create_folder(scope_type = "project", scope_id = "p1", path = str(source))
+ held = []
+
+ def project_exists(project_id):
+ # create_folder and upload admission take this lock, so holding it here is what
+ # stops a project recreated mid-pass from having its new folders retired
+ lock = folder_sync._scope_lock(scope)
+ acquired = []
+ probe = threading.Thread(target = lambda: acquired.append(lock.acquire(blocking = False)))
+ probe.start()
+ probe.join()
+ held.append(not acquired[0])
+ return True
+
+ result = folder_sync.reconcile_retired_scopes(project_exists)
+
+ assert held and all(held)
+ assert result["retired"] == []
+ assert folder_sync.scope_retired(scope) is False
+ current = folder_sync.get_folder(folder["id"])
+ assert current["status"] == folder["status"]
+ assert current["auto_sync"] == folder["auto_sync"]
+
+
+@requires_sqlite_vec
+def test_retirement_leaves_a_folder_linked_after_the_ownership_check(rag_home):
+ scope = store.project_scope("p1")
+ source = rag_home / "before-check"
+ source.mkdir()
+ existing = folder_sync.create_folder(scope_type = "project", scope_id = "p1", path = str(source))
+ checked_at = folder_sync.now_iso()
+ # a second backend process links this one after the check and before the write
+ later = rag_home / "after-check"
+ later.mkdir()
+ fresh = folder_sync.create_folder(scope_type = "project", scope_id = "p1", path = str(later))
+
+ folder_sync.retire_scope(scope, checked_at)
+
+ assert folder_sync.get_folder(existing["id"])["status"] == "retired"
+ survivor = folder_sync.get_folder(fresh["id"])
+ assert survivor["status"] == fresh["status"]
+ assert survivor["auto_sync"] == fresh["auto_sync"]
+ assert survivor["last_error"] is None
diff --git a/studio/backend/tests/test_rag_native_drop_upload.py b/studio/backend/tests/test_rag_native_drop_upload.py
index 7e78401c47b..bd46b8998f8 100644
--- a/studio/backend/tests/test_rag_native_drop_upload.py
+++ b/studio/backend/tests/test_rag_native_drop_upload.py
@@ -41,26 +41,31 @@ def _sign(
*,
operation = "attach",
path_kind = "attachment",
+ identity_options = None,
nonce = None,
secret = SECRET,
):
"""Mint the grant Rust would sign for a dropped file."""
st = os.stat(path)
+ path_type = "directory" if os.path.isdir(path) else "file"
now_ms = int(time.time() * 1000)
+ identities = identity_options or ((st.st_dev, st.st_ino),)
payload = {
"version": 1,
"operation": operation,
"canonical_path": str(path),
"path_kind": path_kind,
- "path_type": "file",
+ "path_type": path_type,
"source_kind": "drop",
"token_id_hash": hashlib.sha256(b"path_token").hexdigest(),
"issued_at_ms": now_ms,
"expires_at_ms": now_ms + 120_000,
"nonce": nonce or os.urandom(16).hex(),
"display_label": os.path.basename(path),
- "size_bytes": st.st_size,
- "modified_ms": int(st.st_mtime_ns // 1_000_000),
+ "size_bytes": st.st_size if path_type == "file" else None,
+ "modified_ms": int(st.st_mtime_ns // 1_000_000) if path_type == "file" else None,
+ "device_id": ":".join(format(identity[0], "x") for identity in identities),
+ "file_id": ":".join(format(identity[1], "x") for identity in identities),
}
payload_b64 = _b64(json.dumps(payload).encode("utf-8"))
signature = hmac.new(secret, payload_b64.encode("ascii"), hashlib.sha256).digest()
@@ -141,6 +146,77 @@ def test_grant_is_single_use(rag_home, tmp_path):
_save_native_path_upload(lease)
+def test_document_folder_grant_binds_identity_but_allows_content_changes(tmp_path):
+ folder = tmp_path / "documents"
+ folder.mkdir()
+ lease = _sign(folder, operation = "link-documents", path_kind = "document-folder")
+ (folder / "new.txt").write_text("new content", encoding = "utf-8")
+
+ grant = leases.verify_native_path_lease(
+ lease,
+ operation = "link-documents",
+ expected_kind = "document-folder",
+ expected_path_type = "directory",
+ )
+
+ assert grant.canonical_path == folder
+
+ replaced_lease = _sign(folder, operation = "link-documents", path_kind = "document-folder")
+ old_folder = tmp_path / "old-documents"
+ folder.rename(old_folder)
+ folder.mkdir()
+ with pytest.raises(leases.NativePathLeaseError, match = "changed"):
+ leases.verify_native_path_lease(
+ replaced_lease,
+ operation = "link-documents",
+ expected_kind = "document-folder",
+ expected_path_type = "directory",
+ )
+
+
[email protected](("uses_extended_identity", "matching_index"), [(False, 0), (True, 1)])
+def test_grant_uses_the_identity_exposed_by_its_python_runtime(
+ tmp_path, monkeypatch, uses_extended_identity, matching_index
+):
+ folder = tmp_path / "documents"
+ folder.mkdir()
+ current = (folder.stat().st_dev, folder.stat().st_ino)
+ other = (current[0] + 1, current[1] + 1)
+ accepted = [other, other]
+ accepted[matching_index] = current
+ lease = _sign(
+ folder,
+ operation = "link-documents",
+ path_kind = "document-folder",
+ identity_options = accepted,
+ )
+ rejected = [other, other]
+ rejected[1 - matching_index] = current
+ rejected_lease = _sign(
+ folder,
+ operation = "link-documents",
+ path_kind = "document-folder",
+ identity_options = rejected,
+ )
+ monkeypatch.setattr(leases, "_WINDOWS_STAT_USES_FILE_ID_INFO", uses_extended_identity)
+
+ grant = leases.verify_native_path_lease(
+ lease,
+ operation = "link-documents",
+ expected_kind = "document-folder",
+ expected_path_type = "directory",
+ )
+
+ assert (grant.device_id, grant.file_id) == current
+ with pytest.raises(leases.NativePathLeaseError, match = "changed"):
+ leases.verify_native_path_lease(
+ rejected_lease,
+ operation = "link-documents",
+ expected_kind = "document-folder",
+ expected_path_type = "directory",
+ )
+
+
def test_resolver_needs_one_of_file_or_lease(rag_home):
with pytest.raises(HTTPException) as excinfo:
_resolve_document_upload(None, None)
diff --git a/studio/backend/tests/test_rag_reconcile_orphaned.py b/studio/backend/tests/test_rag_reconcile_orphaned.py
index 13787ba1aea..6c7fbefe491 100644
--- a/studio/backend/tests/test_rag_reconcile_orphaned.py
+++ b/studio/backend/tests/test_rag_reconcile_orphaned.py
@@ -114,6 +114,38 @@ def test_already_failed_doc_has_its_chunks_dropped(rag_conn):
assert _chunk_count(rag_conn, "failed_doc") == 0
+def test_live_foreign_lease_is_preserved_then_reconciled_after_expiry(rag_conn):
+ _add_doc(rag_conn, "kb_a", "foreign", "processing", ["alpha bravo"])
+ _orphan_job(rag_conn, "foreign", "kb_a")
+ rag_conn.execute(
+ "INSERT INTO rag_job_leases(kind, job_id, owner_id, expires_at) "
+ "VALUES('ingestion', 'job-foreign', 'other-backend', '9999-12-31T00:00:00+00:00')"
+ )
+ rag_conn.commit()
+
+ assert rag_db.reconcile_orphaned_ingestion_jobs() == 0
+ assert store.get_document(rag_conn, "foreign")["status"] == "processing"
+ assert _job_status(rag_conn, "foreign") == "running"
+ assert _chunk_count(rag_conn, "foreign") == 1
+
+ rag_conn.execute(
+ "UPDATE rag_job_leases SET expires_at='2000-01-01T00:00:00+00:00' "
+ "WHERE kind='ingestion' AND job_id='job-foreign'"
+ )
+ rag_conn.commit()
+
+ assert rag_db.reconcile_orphaned_ingestion_jobs() == 1
+ assert store.get_document(rag_conn, "foreign")["status"] == "failed"
+ assert _job_status(rag_conn, "foreign") == "failed"
+ assert _chunk_count(rag_conn, "foreign") == 0
+ assert (
+ rag_conn.execute(
+ "SELECT 1 FROM rag_job_leases WHERE kind='ingestion' AND job_id='job-foreign'"
+ ).fetchone()
+ is None
+ )
+
+
def test_cancelled_job_is_terminal_and_survives_a_restart(rag_conn):
# The worker cancelled itself because the document was deleted mid-ingestion.
# A restart must leave that verdict alone: rewriting it to 'failed' reports a
diff --git a/studio/backend/tests/test_rag_store.py b/studio/backend/tests/test_rag_store.py
index 4c54b02ea70..14df7b44697 100644
--- a/studio/backend/tests/test_rag_store.py
+++ b/studio/backend/tests/test_rag_store.py
@@ -4,6 +4,9 @@
"""Store tests: incremental writes, dedupe, delete, scope, dense + lexical."""
import math
+import sqlite3
+
+import pytest
from core.rag import store
from core.rag.chunking import Chunk
@@ -123,3 +126,33 @@ def test_kb_crud_and_delete_cascades(rag_conn):
assert store.get_kb(rag_conn, "K1") is None
assert store.list_documents(rag_conn, scope) == []
assert store.search_lexical(rag_conn, scope, "alpha", 10) == []
+
+
+def test_kb_delete_rolls_back_when_document_cleanup_fails(rag_conn, monkeypatch):
+ store.create_kb(rag_conn, name = "My KB", kb_id = "K1")
+ scope = store.kb_scope("K1")
+ _add_doc(rag_conn, scope, "doc1", "one.txt", "h1", ["alpha bravo"])
+ _add_doc(rag_conn, scope, "doc2", "two.txt", "h2", ["charlie delta"])
+ original_delete = store.delete_document
+ calls = []
+
+ def fail_after_delete(
+ conn,
+ document_id,
+ *,
+ commit = True,
+ ):
+ calls.append((document_id, commit))
+ original_delete(conn, document_id, commit = commit)
+ raise sqlite3.OperationalError("database is busy")
+
+ monkeypatch.setattr(store, "delete_document", fail_after_delete)
+ with pytest.raises(sqlite3.OperationalError, match = "database is busy"):
+ store.delete_kb(rag_conn, "K1")
+
+ assert calls == [("doc1", False)]
+ assert store.get_kb(rag_conn, "K1") is not None
+ assert sorted(document["id"] for document in store.list_documents(rag_conn, scope)) == [
+ "doc1",
+ "doc2",
+ ]
diff --git a/studio/backend/tests/test_warm_window_review_fixes.py b/studio/backend/tests/test_warm_window_review_fixes.py
index ef6cd379f52..6b20441f968 100644
--- a/studio/backend/tests/test_warm_window_review_fixes.py
+++ b/studio/backend/tests/test_warm_window_review_fixes.py
@@ -378,6 +378,26 @@ def test_the_torch_kill_switch_leaves_mlx_selfheal_running():
)
+def test_the_torch_kill_switch_leaves_linked_folder_sync_running(monkeypatch):
+ import main as main_mod
+ import utils.mlx_repair as mlx_repair
+
+ calls = []
+ monkeypatch.setattr(main_mod, "join_background_warm", lambda: None)
+ monkeypatch.setattr(mlx_repair, "start_mlx_autorepair_if_needed", lambda: None)
+ monkeypatch.setattr(main_mod, "_post_warm_retired", lambda generation: False)
+ monkeypatch.setattr(
+ main_mod,
+ "_start_linked_folder_auto_sync",
+ lambda generation: calls.append(generation),
+ )
+ monkeypatch.setenv(main_mod.DISABLE_ENV_VAR, "1")
+
+ main_mod._post_warm_background_work(123)
+
+ assert calls == [123]
+
+
def test_the_purge_rechecks_before_touching_sys_modules():
"""A racing retry republishes the parent; do not strip modules under it."""
src = (_BACKEND / "utils" / "torch_warmup.py").read_text(encoding = "utf-8")
diff --git a/studio/backend/utils/native_path_leases.py b/studio/backend/utils/native_path_leases.py
index 9edec69bb28..b66087f128c 100644
--- a/studio/backend/utils/native_path_leases.py
+++ b/studio/backend/utils/native_path_leases.py
@@ -19,10 +19,11 @@ import importlib
import json
import os
import stat as _stat_module
+import sys
import threading
import time
from contextlib import contextmanager
-from dataclasses import dataclass
+from dataclasses import dataclass, replace
from pathlib import Path
from typing import Any, Callable, Collection, Iterable, Iterator, Mapping
@@ -30,6 +31,7 @@ LEASE_SECRET_ENV = "UNSLOTH_STUDIO_NATIVE_PATH_LEASE_SECRET"
_MAX_NATIVE_PATH_REDACTIONS = 100
_MAX_NATIVE_PATH_LABELS = 10_000
_MIN_LEASE_SECRET_BYTES = 32
+_WINDOWS_STAT_USES_FILE_ID_INFO = os.name == "nt" and sys.version_info >= (3, 12)
_REPLAY_LOCK = threading.Lock()
_USED_NONCES: dict[str, int] = {}
@@ -88,6 +90,8 @@ class NativePathGrant:
expires_at_ms: int
size_bytes: int | None
modified_ms: int | None
+ device_id: int | None
+ file_id: int | None
def native_path_leases_supported() -> bool:
@@ -194,6 +198,7 @@ def verify_native_path_lease(
if not _same_native_path(resolved, path):
raise NativePathLeaseError("Native path grant no longer resolves to the selected path.")
+ identity_options = _identity_options(payload)
grant = NativePathGrant(
operation = str(payload["operation"]),
canonical_path = resolved,
@@ -205,6 +210,8 @@ def verify_native_path_lease(
expires_at_ms = _required_int(payload, "expires_at_ms"),
size_bytes = _optional_int(payload.get("size_bytes")),
modified_ms = _optional_int(payload.get("modified_ms")),
+ device_id = identity_options[0][0] if identity_options else None,
+ file_id = identity_options[0][1] if identity_options else None,
)
if expected_path_type and grant.path_type != expected_path_type:
@@ -213,7 +220,9 @@ def verify_native_path_lease(
if suffixes and resolved.suffix.lower() not in suffixes:
raise NativePathLeaseError("Native path grant has an unsupported file type.")
- _validate_current_stat(grant)
+ current_identity = _validate_current_stat(grant, identity_options)
+ if current_identity is not None:
+ grant = replace(grant, device_id = current_identity[0], file_id = current_identity[1])
_consume_nonce(str(payload["nonce"]), grant.expires_at_ms)
_remember_native_path_for_redaction(str(resolved), grant.display_label)
return grant
@@ -331,7 +340,9 @@ def _validate_payload(
raise NativePathLeaseError("Native path grant contains invalid characters.")
-def _validate_current_stat(grant: NativePathGrant) -> None:
+def _validate_current_stat(
+ grant: NativePathGrant, identity_options: tuple[tuple[int, int], ...]
+) -> tuple[int, int] | None:
try:
st = os.lstat(grant.canonical_path)
except OSError as exc:
@@ -352,6 +363,13 @@ def _validate_current_stat(grant: NativePathGrant) -> None:
current_modified_ms = int(st.st_mtime_ns // 1_000_000)
if grant.modified_ms is not None and current_modified_ms != grant.modified_ms:
raise NativePathLeaseError("Native path changed after it was selected.")
+ if grant.path_kind == "document-folder" and not identity_options:
+ raise NativePathLeaseError("Native path grant is missing its folder identity.")
+ current_identity = (st.st_dev, st.st_ino)
+ expected_identity = _runtime_identity(identity_options)
+ if expected_identity is not None and current_identity != expected_identity:
+ raise NativePathLeaseError("Native path changed after it was selected.")
+ return current_identity if expected_identity is not None else None
def _consume_nonce(nonce: str, expires_at_ms: int) -> None:
@@ -421,6 +439,41 @@ def _optional_int(value: Any) -> int | None:
raise NativePathLeaseError("Native path grant payload is invalid.") from exc
+def _identity_options(payload: dict[str, Any]) -> tuple[tuple[int, int], ...]:
+ devices = _optional_identities(payload.get("device_id"))
+ files = _optional_identities(payload.get("file_id"))
+ if devices is None and files is None:
+ return ()
+ if devices is None or files is None or len(devices) != len(files):
+ raise NativePathLeaseError("Native path grant payload is invalid.")
+ return tuple(zip(devices, files))
+
+
+def _runtime_identity(identity_options: tuple[tuple[int, int], ...]) -> tuple[int, int] | None:
+ if not identity_options:
+ return None
+ if len(identity_options) == 1:
+ return identity_options[0]
+ # Rust encodes the legacy Win32 pair first and FILE_ID_INFO second.
+ return identity_options[1] if _WINDOWS_STAT_USES_FILE_ID_INFO else identity_options[0]
+
+
+def _optional_identities(value: Any) -> tuple[int, ...] | None:
+ if value is None:
+ return None
+ if not isinstance(value, str) or value != value.lower():
+ raise NativePathLeaseError("Native path grant payload is invalid.")
+ parts = value.split(":")
+ if not 1 <= len(parts) <= 2 or any(
+ not part or any(char not in "0123456789abcdef" for char in part) for part in parts
+ ):
+ raise NativePathLeaseError("Native path grant payload is invalid.")
+ try:
+ return tuple(int(part, 16) for part in parts)
+ except ValueError as exc:
+ raise NativePathLeaseError("Native path grant payload is invalid.") from exc
+
+
def _required_int(payload: dict[str, Any], key: str) -> int:
raw = payload.get(key)
if raw is None:
diff --git a/studio/frontend/src/features/native-intents/api.ts b/studio/frontend/src/features/native-intents/api.ts
index a89d04eebd4..3a95744e12c 100644
--- a/studio/frontend/src/features/native-intents/api.ts
+++ b/studio/frontend/src/features/native-intents/api.ts
@@ -5,14 +5,36 @@ import type {
NativePathOperation,
} from "./types";
-async function invokeNative<T>(command: string, args?: Record<string, unknown>): Promise<T> {
+async function invokeNative<T>(
+ command: string,
+ args?: Record<string, unknown>,
+): Promise<T> {
if (!isTauri) {
- throw new Error("Native desktop features are only available in the Tauri app.");
+ throw new Error(
+ "Native desktop features are only available in the Tauri app.",
+ );
}
const { invoke } = await import("@tauri-apps/api/core");
return invoke<T>(command, args);
}
+export interface NativeDocumentFolderSelection {
+ /** Opaque directory lease. This is deliberately not a filesystem path. */
+ token: string;
+ displayName: string;
+}
+
+export async function pickNativeDocumentFolder(): Promise<NativeDocumentFolderSelection | null> {
+ if (!isTauri) {
+ throw new Error(
+ "Persistent local folder sync is only available in the desktop app.",
+ );
+ }
+ return invokeNative<NativeDocumentFolderSelection | null>(
+ "pick_native_document_folder",
+ );
+}
+
export async function drainNativeIntents(): Promise<NativeIntent[]> {
if (!isTauri) return [];
return invokeNative<NativeIntent[]>("drain_native_intents");
@@ -28,15 +50,23 @@ export async function pickHuggingFaceCacheDir(): Promise<string | null> {
return invokeNative<string | null>("pick_hugging_face_cache_dir");
}
-export async function registerNativeModelPath(path: string): Promise<NativeIntent> {
+export async function registerNativeModelPath(
+ path: string,
+): Promise<NativeIntent> {
return invokeNative<NativeIntent>("register_native_model_path", { path });
}
-export async function registerNativeAttachmentPath(path: string): Promise<NativeIntent> {
- return invokeNative<NativeIntent>("register_native_attachment_path", { path });
+export async function registerNativeAttachmentPath(
+ path: string,
+): Promise<NativeIntent> {
+ return invokeNative<NativeIntent>("register_native_attachment_path", {
+ path,
+ });
}
-export async function registerNativeDatasetPath(path: string): Promise<NativeIntent> {
+export async function registerNativeDatasetPath(
+ path: string,
+): Promise<NativeIntent> {
return invokeNative<NativeIntent>("register_native_dataset_path", { path });
}
diff --git a/studio/frontend/src/features/native-intents/index.ts b/studio/frontend/src/features/native-intents/index.ts
index 822f17fac87..2261cd3747d 100644
--- a/studio/frontend/src/features/native-intents/index.ts
+++ b/studio/frontend/src/features/native-intents/index.ts
@@ -6,11 +6,13 @@ export { NativeModelDropOverlay } from "./components/native-model-drop-overlay";
export {
consumeNativePathToken,
openModelsDir,
+ pickNativeDocumentFolder,
pickHuggingFaceCacheDir,
readNativeAttachmentFile,
registerNativeAttachmentPath,
registerNativeDatasetPath,
} from "./api";
+export type { NativeDocumentFolderSelection } from "./api";
export { nativeDropTargetAt } from "./native-drop-targets";
export { useNativeDropTarget } from "./use-native-drop-target";
export {
diff --git a/studio/frontend/src/features/rag/api/rag-api.ts b/studio/frontend/src/features/rag/api/rag-api.ts
index 3c7f759084d..cba02c9c019 100644
--- a/studio/frontend/src/features/rag/api/rag-api.ts
+++ b/studio/frontend/src/features/rag/api/rag-api.ts
@@ -4,11 +4,16 @@
import { authFetch } from "@/features/auth";
import { apiUrl } from "@/lib/api-base";
import { formatFastApiDetail } from "@/lib/format-fastapi-error";
+import { readSseJsonEvents } from "@/lib/sse-json-events";
import type {
DocumentUploadResult,
+ FolderSyncJob,
+ FolderSyncJobEvent,
IndexJob,
JobEvent,
KnowledgeBase,
+ LinkedFolder,
+ LinkedFolderScope,
PreviewTarget,
RagDocument,
UploadedDocument,
@@ -218,6 +223,75 @@ export function invalidateProjectSources(projectId: string): void {
projectSourcesCache.delete(projectId);
}
+export async function listLinkedFolders(
+ scope?: LinkedFolderScope,
+): Promise<LinkedFolder[]> {
+ const query = scope
+ ? `?scope_type=${encodeURIComponent(scope.type)}&scope_id=${encodeURIComponent(scope.id)}`
+ : "";
+ const data = await ragRequest<{ linkedFolders: LinkedFolder[] }>(
+ `/linked-folders${query}`,
+ );
+ return data.linkedFolders ?? [];
+}
+
+interface LinkedFolderMutationResult {
+ linkedFolder: LinkedFolder;
+ job: FolderSyncJob;
+}
+
+export function createLinkedFolder(
+ scope: LinkedFolderScope,
+ nativePathLease: string,
+ displayName: string,
+): Promise<LinkedFolderMutationResult> {
+ const parent =
+ scope.type === "knowledge_base" ? "knowledge-bases" : "projects";
+ return ragRequest(
+ `/${parent}/${encodeURIComponent(scope.id)}/linked-folders`,
+ {
+ method: "POST",
+ body: { nativePathLease, displayName },
+ },
+ );
+}
+
+export function deleteLinkedFolder(
+ linkedFolderId: string,
+ removeIndex: boolean,
+): Promise<{ ok: boolean }> {
+ return ragRequest(
+ `/linked-folders/${encodeURIComponent(linkedFolderId)}?remove_index=${removeIndex}`,
+ { method: "DELETE" },
+ );
+}
+
+function startLinkedFolderJob(
+ linkedFolderId: string,
+ action: "sync" | "rebuild",
+): Promise<{ job: FolderSyncJob }> {
+ return ragRequest(
+ `/linked-folders/${encodeURIComponent(linkedFolderId)}/${action}`,
+ { method: "POST" },
+ );
+}
+
+export function syncLinkedFolder(
+ linkedFolderId: string,
+): Promise<{ job: FolderSyncJob }> {
+ return startLinkedFolderJob(linkedFolderId, "sync");
+}
+
+export function rebuildLinkedFolder(
+ linkedFolderId: string,
+): Promise<{ job: FolderSyncJob }> {
+ return startLinkedFolderJob(linkedFolderId, "rebuild");
+}
+
+export function getFolderSyncJob(jobId: string): Promise<FolderSyncJob> {
+ return ragRequest(`/linked-folder-jobs/${encodeURIComponent(jobId)}`);
+}
+
export async function listAllDocuments(): Promise<UploadedDocument[]> {
const data = await ragRequest<{ documents: UploadedDocument[] }>(
"/documents",
@@ -243,64 +317,46 @@ export function getJob(jobId: string): Promise<IndexJob> {
return ragRequest(`/jobs/${encodeURIComponent(jobId)}`);
}
-// SSE; returns on [DONE]. Transport errors propagate so callers can poll getJob.
-export async function* streamJobEvents(
- jobId: string,
- signal?: AbortSignal,
-): AsyncGenerator<JobEvent> {
- const response = await authFetch(
- `${RAG_BASE}/jobs/${encodeURIComponent(jobId)}/events`,
- signal ? { signal } : undefined,
- );
+/** Longest gap between frames before a stream is treated as buffered by a proxy. */
+const SSE_STALL_MS = 12000;
+
+async function openEventStream(
+ url: string,
+ signal: AbortSignal | undefined,
+): Promise<ReadableStream<Uint8Array>> {
+ const response = await authFetch(url, signal ? { signal } : undefined);
if (!response.ok) {
const body = await response.json().catch(() => null);
- // Also gated on the extension, and also not routed through ragRequest.
+ // also gated on the extension, and also not routed through ragRequest
noteRagResponse(response.status, body);
throw new Error(parseErrorText(response.status, body));
}
if (!response.body) throw new Error("Stream response missing body");
+ return response.body;
+}
- const reader = response.body.getReader();
- const decoder = new TextDecoder();
- let buffer = "";
+// sse; returns on [DONE]. transport errors propagate so callers can poll getJob
+export async function* streamJobEvents(
+ jobId: string,
+ signal?: AbortSignal,
+): AsyncGenerator<JobEvent> {
+ // no stall bound: this consumer reads an early end as a finished job
+ const body = await openEventStream(
+ `${RAG_BASE}/jobs/${encodeURIComponent(jobId)}/events`,
+ signal,
+ );
+ yield* readSseJsonEvents<JobEvent>(body);
+}
- try {
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
-
- let separatorIndex = buffer.search(/\r?\n\r?\n/);
- while (separatorIndex >= 0) {
- const rawEvent = buffer.slice(0, separatorIndex);
- const separatorLength = buffer[separatorIndex] === "\r" ? 4 : 2;
- buffer = buffer.slice(separatorIndex + separatorLength);
-
- const dataLines: string[] = [];
- for (const line of rawEvent.split(/\r?\n/)) {
- if (line.startsWith("data:"))
- dataLines.push(line.slice(5).trimStart());
- }
- if (dataLines.length > 0) {
- const dataText = dataLines.join("\n");
- if (dataText === "[DONE]") return;
- try {
- yield JSON.parse(dataText) as JobEvent;
- } catch {
- // Ignore unparseable frames; [DONE] still ends the loop.
- }
- }
- separatorIndex = buffer.search(/\r?\n\r?\n/);
- }
- }
- } finally {
- // Release the stream lock now instead of leaking the reader until GC.
- try {
- await reader.cancel();
- } catch {
- // already closed
- }
- }
+export async function* streamFolderSyncJobEvents(
+ jobId: string,
+ signal?: AbortSignal,
+): AsyncGenerator<FolderSyncJobEvent> {
+ const body = await openEventStream(
+ `${RAG_BASE}/linked-folder-jobs/${encodeURIComponent(jobId)}/events`,
+ signal,
+ );
+ yield* readSseJsonEvents<FolderSyncJobEvent>(body, SSE_STALL_MS);
}
export function getPreviewTarget(
diff --git a/studio/frontend/src/features/rag/components/document-status-chip.tsx b/studio/frontend/src/features/rag/components/document-status-chip.tsx
index 839541871a1..c0cc180daa0 100644
--- a/studio/frontend/src/features/rag/components/document-status-chip.tsx
+++ b/studio/frontend/src/features/rag/components/document-status-chip.tsx
@@ -1,17 +1,18 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-import { XIcon } from "lucide-react";
-import { Spinner } from "@/components/ui/spinner";
-import { HugeiconsIcon } from "@hugeicons/react";
-import { File02Icon } from "@hugeicons/core-free-icons";
import { Badge } from "@/components/assistant-ui/badge";
+import { Spinner } from "@/components/ui/spinner";
import { cn } from "@/lib/utils";
+import { File02Icon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { XIcon } from "lucide-react";
import type { DocumentStatus } from "../types/rag";
export function DocumentStatusChip({
filename,
status,
+ progress,
error,
onRemove,
}: {
@@ -41,7 +42,12 @@ export function DocumentStatusChip({
<span className="truncate">{filename}</span>
{/* spinner while indexing, else close button */}
{processing ? (
- <Spinner className="shrink-0 size-3.5 text-muted-foreground" />
+ <span className="flex shrink-0 items-center gap-1 text-ui-10 text-muted-foreground">
+ {progress != null
+ ? `${Math.round(progress <= 1 ? progress * 100 : progress)}%`
+ : null}
+ <Spinner className="size-3.5" />
+ </span>
) : onRemove ? (
<button
type="button"
diff --git a/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx b/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx
index 8245b353be7..23082ca64c4 100644
--- a/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx
+++ b/studio/frontend/src/features/rag/components/knowledge-base-dialog.tsx
@@ -1,7 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-import { useCallback, useEffect, useRef, useState } from "react";
import {
Delete02Icon,
Edit03Icon,
@@ -9,6 +8,7 @@ import {
} from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import { ChevronLeftIcon, UploadIcon } from "lucide-react";
+import { useCallback, useEffect, useRef, useState } from "react";
import {
AlertDialog,
@@ -42,8 +42,13 @@ import {
updateKnowledgeBase,
} from "../api/rag-api";
import { useRagAvailabilityStore } from "../api/rag-availability";
-import { RAG_UPLOAD_ACCEPT, type KnowledgeBase } from "../types/rag";
+import {
+ type KnowledgeBase,
+ RAG_UPLOAD_ACCEPT,
+ isLinkedFolderManaged,
+} from "../types/rag";
import { DocumentStatusChip } from "./document-status-chip";
+import { LinkedFoldersManager } from "./linked-folders-manager";
import { useRagDocuments } from "./use-rag-documents";
type View =
@@ -173,9 +178,7 @@ export function KnowledgeBaseDialog({
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>
- {view.kind === "documents"
- ? view.kb.name
- : "Knowledge bases"}
+ {view.kind === "documents" ? view.kb.name : "Knowledge bases"}
</DialogTitle>
<DialogDescription>
{view.kind === "documents"
@@ -332,15 +335,13 @@ function KnowledgeBaseDocuments({
kb: KnowledgeBase;
onBack: () => void;
}) {
- const lister = useCallback(
- () => listKnowledgeBaseDocuments(kb.id),
- [kb.id],
- );
- const { documents, loading, uploading, upload, remove } = useRagDocuments(
- { type: "kb", kbId: kb.id },
- lister,
- );
+ const lister = useCallback(() => listKnowledgeBaseDocuments(kb.id), [kb.id]);
+ const { documents, loading, uploading, refresh, upload, remove } =
+ useRagDocuments({ type: "kb", kbId: kb.id }, lister);
const fileInputRef = useRef<HTMLInputElement>(null);
+ const handleLinkedSourcesChanged = useCallback(() => {
+ void refresh({ quiet: true });
+ }, [refresh]);
return (
<div className="flex min-w-0 flex-col gap-3">
@@ -360,7 +361,7 @@ function KnowledgeBaseDocuments({
<input
ref={fileInputRef}
type="file"
- multiple
+ multiple={true}
accept={RAG_UPLOAD_ACCEPT}
className="hidden"
onChange={(e) => {
@@ -387,7 +388,7 @@ function KnowledgeBaseDocuments({
progress={doc.progress}
error={doc.error}
onRemove={
- doc.id.startsWith("pending_")
+ doc.id.startsWith("pending_") || isLinkedFolderManaged(doc)
? undefined
: () => void remove(doc.id)
}
@@ -395,6 +396,13 @@ function KnowledgeBaseDocuments({
))}
</div>
)}
+ <div className="border-t pt-3">
+ <LinkedFoldersManager
+ scope={{ type: "knowledge_base", id: kb.id }}
+ compact={true}
+ onSourcesChanged={handleLinkedSourcesChanged}
+ />
+ </div>
</div>
);
}
diff --git a/studio/frontend/src/features/rag/components/linked-folders-manager.tsx b/studio/frontend/src/features/rag/components/linked-folders-manager.tsx
new file mode 100644
index 00000000000..d81c22adbc7
--- /dev/null
+++ b/studio/frontend/src/features/rag/components/linked-folders-manager.tsx
@@ -0,0 +1,251 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { Progress } from "@/components/ui/progress";
+import { Spinner } from "@/components/ui/spinner";
+import { cn } from "@/lib/utils";
+import { FolderSyncIcon, MoreHorizontalIcon, RotateCwIcon } from "lucide-react";
+import { useState } from "react";
+import type { FolderSyncJob, LinkedFolderScope } from "../types/rag";
+import { useLinkedFolders } from "./use-linked-folders";
+
+function percent(progress?: number | null): number | null {
+ if (progress == null || !Number.isFinite(progress)) return null;
+ return Math.max(0, Math.min(100, progress <= 1 ? progress * 100 : progress));
+}
+
+function jobSummary(job: FolderSyncJob): string {
+ if (job.status === "failed") return job.error ?? "Sync failed";
+ if (job.status === "completed") {
+ const indexed = job.indexedFiles ?? job.processedFiles;
+ return indexed == null
+ ? "Sync complete"
+ : `${indexed} file${indexed === 1 ? "" : "s"} indexed`;
+ }
+ const processed = job.processedFiles ?? 0;
+ const discovered = job.discoveredFiles;
+ return discovered == null
+ ? job.stage || "Scanning folder"
+ : `${processed} of ${discovered} files`;
+}
+
+export function LinkedFoldersManager({
+ scope,
+ compact = false,
+ onSourcesChanged,
+}: {
+ scope?: LinkedFolderScope;
+ compact?: boolean;
+ onSourcesChanged?: () => void;
+}) {
+ const manager = useLinkedFolders(scope, onSourcesChanged);
+ const [removeIndexFolder, setRemoveIndexFolder] = useState<{
+ id: string;
+ name: string;
+ } | null>(null);
+
+ return (
+ <section className={cn("flex min-w-0 flex-col gap-3", compact && "gap-2")}>
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <h3 className="text-sm font-medium text-foreground">
+ Linked local folders
+ </h3>
+ <p className="text-xs leading-snug text-muted-foreground">
+ {manager.desktopSupported
+ ? "Keep supported documents indexed as this folder changes."
+ : "Existing linked folders stay synced; link new folders in the desktop app."}
+ </p>
+ </div>
+ {scope ? (
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="shrink-0"
+ disabled={!manager.desktopSupported || manager.mutating}
+ onClick={() => void manager.link()}
+ title={
+ manager.desktopSupported
+ ? "Choose a local folder"
+ : "Requires the desktop app"
+ }
+ >
+ {manager.mutating ? (
+ <Spinner className="size-3.5" />
+ ) : (
+ <FolderSyncIcon className="size-3.5" />
+ )}
+ Link folder
+ </Button>
+ ) : null}
+ </div>
+
+ {manager.loading && manager.folders.length === 0 ? (
+ <div className="flex justify-center py-4">
+ <Spinner />
+ </div>
+ ) : manager.folders.length === 0 ? (
+ <div className="rounded-xl border border-dashed px-4 py-5 text-center text-xs text-muted-foreground">
+ No linked folders.
+ </div>
+ ) : (
+ <ul className="flex flex-col gap-1.5">
+ {manager.folders.map((folder) => {
+ const job = manager.jobs[folder.id];
+ const running =
+ job?.status === "pending" || job?.status === "running";
+ const progress = percent(job?.progress);
+ return (
+ <li
+ key={folder.id}
+ className="flex min-w-0 items-start gap-3 rounded-xl border border-border/70 bg-background px-3 py-2.5"
+ >
+ <FolderSyncIcon className="mt-0.5 size-4 shrink-0 text-muted-foreground" />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-baseline gap-2">
+ <span
+ className="truncate text-sm font-medium"
+ title={folder.displayName}
+ >
+ {folder.displayName}
+ </span>
+ {scope ? null : (
+ <span
+ className="max-w-48 shrink truncate text-ui-11 text-muted-foreground"
+ title={
+ folder.scopeName ||
+ `${folder.scopeType === "knowledge_base" ? "Knowledge base" : "Project"} ${folder.scopeId}`
+ }
+ >
+ {folder.scopeName ||
+ `${folder.scopeType === "knowledge_base" ? "Knowledge base" : "Project"} ${folder.scopeId}`}
+ </span>
+ )}
+ </div>
+ <p
+ className={cn(
+ "text-ui-11 text-muted-foreground",
+ (folder.status === "error" || job?.status === "failed") &&
+ "text-destructive",
+ )}
+ >
+ {job
+ ? jobSummary(job)
+ : folder.error ||
+ (folder.lastSyncedAt
+ ? `Last synced ${new Date(folder.lastSyncedAt).toLocaleString()}`
+ : `${folder.documentCount ?? 0} indexed documents`)}
+ </p>
+ {running ? (
+ <Progress
+ value={progress ?? 0}
+ aria-label={`Sync progress for ${folder.displayName}`}
+ className="mt-2 h-1.5"
+ />
+ ) : null}
+ </div>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild={true}>
+ <Button
+ type="button"
+ size="icon-sm"
+ variant="ghost"
+ className="shrink-0 rounded-full"
+ aria-label={`Actions for ${folder.displayName}`}
+ >
+ {running ? (
+ <Spinner className="size-3.5" />
+ ) : (
+ <MoreHorizontalIcon className="size-4" />
+ )}
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ disabled={running}
+ onSelect={() => void manager.sync(folder.id)}
+ >
+ <FolderSyncIcon className="size-3.5" /> Sync changes
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={running}
+ onSelect={() => void manager.rebuild(folder.id)}
+ >
+ <RotateCwIcon className="size-3.5" /> Rebuild index
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onSelect={() => void manager.remove(folder.id, false)}
+ >
+ Unlink and keep indexed files
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ variant="destructive"
+ onSelect={() =>
+ setRemoveIndexFolder({
+ id: folder.id,
+ name: folder.displayName,
+ })
+ }
+ >
+ Unlink and remove indexed files
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ <AlertDialog
+ open={removeIndexFolder !== null}
+ onOpenChange={(open) => {
+ if (!open) setRemoveIndexFolder(null);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Unlink folder and remove files?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This will unlink &quot;{removeIndexFolder?.name}&quot; and remove
+ all documents it manages from the index. The files on disk will
+ not be changed.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={() => {
+ const folder = removeIndexFolder;
+ setRemoveIndexFolder(null);
+ if (folder) void manager.remove(folder.id, true);
+ }}
+ >
+ Unlink and remove
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </section>
+ );
+}
diff --git a/studio/frontend/src/features/rag/components/project-sources-panel.tsx b/studio/frontend/src/features/rag/components/project-sources-panel.tsx
index 1bbbc58c0c3..e5b16f0d2e5 100644
--- a/studio/frontend/src/features/rag/components/project-sources-panel.tsx
+++ b/studio/frontend/src/features/rag/components/project-sources-panel.tsx
@@ -1,27 +1,26 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-import { useCallback, useRef } from "react";
-import { HugeiconsIcon } from "@hugeicons/react";
-import { FolderAddIcon } from "@hugeicons/core-free-icons";
import { Button } from "@/components/ui/button";
-import {
- invalidateProjectSources,
- listProjectDocuments,
-} from "../api/rag-api";
-import { RAG_UPLOAD_ACCEPT } from "../types/rag";
+import { FolderAddIcon } from "@hugeicons/core-free-icons";
+import { HugeiconsIcon } from "@hugeicons/react";
+import { useCallback, useRef } from "react";
+import { invalidateProjectSources, listProjectDocuments } from "../api/rag-api";
+import { RAG_UPLOAD_ACCEPT, isLinkedFolderManaged } from "../types/rag";
import { DocumentStatusChip } from "./document-status-chip";
+import { LinkedFoldersManager } from "./linked-folders-manager";
import { useRagDocuments } from "./use-rag-documents";
/** Project "Sources" tab: documents indexed for retrieval in every chat that
* belongs to the project. */
export function ProjectSourcesPanel({ projectId }: { projectId: string }) {
const fileInputRef = useRef<HTMLInputElement>(null);
- const lister = useCallback(() => listProjectDocuments(projectId), [projectId]);
- const { documents, loading, uploading, upload, remove } = useRagDocuments(
- { type: "project", projectId },
- lister,
+ const lister = useCallback(
+ () => listProjectDocuments(projectId),
+ [projectId],
);
+ const { documents, loading, uploading, refresh, upload, remove } =
+ useRagDocuments({ type: "project", projectId }, lister);
// Invalidate the sources probe before and after each mutation: a chat sent
// mid-upload must not cache "no sources" for the probe's TTL.
@@ -43,6 +42,10 @@ export function ProjectSourcesPanel({ projectId }: { projectId: string }) {
},
[projectId, remove],
);
+ const handleLinkedSourcesChanged = useCallback(() => {
+ invalidateProjectSources(projectId);
+ void refresh({ quiet: true });
+ }, [projectId, refresh]);
const empty = documents.length === 0;
@@ -58,7 +61,7 @@ export function ProjectSourcesPanel({ projectId }: { projectId: string }) {
<input
ref={fileInputRef}
type="file"
- multiple
+ multiple={true}
accept={RAG_UPLOAD_ACCEPT}
className="hidden"
onChange={(e) => {
@@ -67,6 +70,13 @@ export function ProjectSourcesPanel({ projectId }: { projectId: string }) {
void handleFiles(files);
}}
/>
+ <div className="mb-4 rounded-[22px] bg-muted/30 px-5 py-4">
+ <LinkedFoldersManager
+ scope={{ type: "project", id: projectId }}
+ compact={true}
+ onSourcesChanged={handleLinkedSourcesChanged}
+ />
+ </div>
{empty ? (
<div className="flex flex-col items-center justify-center gap-3 rounded-[26px] bg-muted/30 px-6 py-16 text-center">
<span className="flex size-12 items-center justify-center rounded-full bg-muted text-muted-foreground">
@@ -124,7 +134,7 @@ export function ProjectSourcesPanel({ projectId }: { projectId: string }) {
progress={doc.progress}
error={doc.error}
onRemove={
- doc.id.startsWith("pending_")
+ doc.id.startsWith("pending_") || isLinkedFolderManaged(doc)
? undefined
: () => void handleRemove(doc.id)
}
diff --git a/studio/frontend/src/features/rag/components/use-linked-folders.ts b/studio/frontend/src/features/rag/components/use-linked-folders.ts
new file mode 100644
index 00000000000..075c011ff06
--- /dev/null
+++ b/studio/frontend/src/features/rag/components/use-linked-folders.ts
@@ -0,0 +1,332 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { pickNativeDocumentFolder } from "@/features/native-intents";
+import { isTauri } from "@/lib/api-base";
+import { createScopedSingleFlightRequest } from "@/lib/single-flight-request";
+import { toast } from "@/lib/toast";
+import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ createLinkedFolder,
+ deleteLinkedFolder,
+ getFolderSyncJob,
+ listLinkedFolders,
+ rebuildLinkedFolder,
+ streamFolderSyncJobEvents,
+ syncLinkedFolder,
+} from "../api/rag-api";
+import type {
+ FolderSyncJob,
+ LinkedFolder,
+ LinkedFolderScope,
+} from "../types/rag";
+import {
+ linkedFolderSourcesChanged,
+ retainActiveFolderJobs,
+} from "../types/rag";
+export function useLinkedFolders(
+ scope?: LinkedFolderScope,
+ onSourcesChanged?: () => void,
+) {
+ const scopeType = scope?.type;
+ const scopeId = scope?.id;
+ const scopeKey = scope ? `${scope.type}:${scope.id}` : "global";
+ const [folders, setFolders] = useState<LinkedFolder[]>([]);
+ const [jobs, setJobs] = useState<Record<string, FolderSyncJob>>({});
+ const [stateScopeKey, setStateScopeKey] = useState(scopeKey);
+ const [loading, setLoading] = useState(true);
+ const [mutating, setMutating] = useState(false);
+ const controllers = useRef(new Map<string, AbortController>());
+ const refreshGate = useRef(
+ createScopedSingleFlightRequest<
+ (signal: AbortSignal) => Promise<boolean>,
+ boolean
+ >((_scope, execute, signal) => execute(signal)),
+ );
+ const currentScopeKey = useRef(scopeKey);
+ const folderSnapshot = useRef<LinkedFolder[] | null>(null);
+ const notifiedJobs = useRef(new Set<string>());
+
+ const notifySourcesChanged = useCallback(
+ (job: FolderSyncJob) => {
+ if (notifiedJobs.current.has(job.id)) return;
+ notifiedJobs.current.add(job.id);
+ onSourcesChanged?.();
+ },
+ [onSourcesChanged],
+ );
+
+ const trackJob = useCallback(
+ (initial: FolderSyncJob) => {
+ if (controllers.current.has(initial.id)) return;
+ setJobs((current) => ({ ...current, [initial.linkedFolderId]: initial }));
+ setFolders((current) =>
+ current.map((folder) =>
+ folder.id === initial.linkedFolderId
+ ? { ...folder, status: "syncing", activeJobId: initial.id }
+ : folder,
+ ),
+ );
+ const controller = new AbortController();
+ controllers.current.set(initial.id, controller);
+
+ const releaseController = () => {
+ if (controllers.current.get(initial.id) === controller) {
+ controllers.current.delete(initial.id);
+ }
+ };
+ const apply = (job: FolderSyncJob) => {
+ if (controller.signal.aborted) return;
+ setJobs((current) => ({ ...current, [job.linkedFolderId]: job }));
+ };
+ const finish = (job: FolderSyncJob) => {
+ if (controller.signal.aborted) return;
+ apply(job);
+ releaseController();
+ notifySourcesChanged(job);
+ if (job.status === "failed") {
+ toast.error("Folder sync failed", {
+ description: job.error ?? "The folder could not be indexed.",
+ });
+ }
+ };
+
+ void (async () => {
+ let latest = initial;
+ try {
+ for await (const event of streamFolderSyncJobEvents(
+ initial.id,
+ controller.signal,
+ )) {
+ if (controller.signal.aborted) return;
+ latest = {
+ ...latest,
+ ...event,
+ status:
+ event.type === "complete"
+ ? "completed"
+ : event.type === "error"
+ ? "failed"
+ : (event.status ?? "running"),
+ };
+ apply(latest);
+ if (latest.status === "completed" || latest.status === "failed") {
+ finish(latest);
+ return;
+ }
+ }
+ } catch {
+ if (controller.signal.aborted) return;
+ }
+
+ try {
+ for (let attempt = 0; attempt < 600; attempt += 1) {
+ if (controller.signal.aborted) return;
+ latest = await getFolderSyncJob(initial.id);
+ apply(latest);
+ if (latest.status === "completed" || latest.status === "failed") {
+ finish(latest);
+ return;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 1500));
+ }
+ // Exhausted: release too, or refresh keeps seeing the job as tracked
+ // and never restarts polling, freezing progress until unmount.
+ releaseController();
+ } catch {
+ releaseController();
+ }
+ })();
+ },
+ [notifySourcesChanged],
+ );
+
+ const refresh = useCallback(
+ (options?: { quiet?: boolean }): Promise<boolean> => {
+ if (!options?.quiet) setLoading(true);
+ return refreshGate.current.run(scopeKey, async (signal) => {
+ const isCurrent = () =>
+ !signal.aborted && currentScopeKey.current === scopeKey;
+ try {
+ const rows = await listLinkedFolders(
+ scopeType && scopeId ? { type: scopeType, id: scopeId } : undefined,
+ );
+ if (!isCurrent()) return false;
+ const sourcesChanged = linkedFolderSourcesChanged(
+ folderSnapshot.current,
+ rows,
+ );
+ folderSnapshot.current = rows;
+ setStateScopeKey(scopeKey);
+ setFolders(rows);
+ setJobs((current) => retainActiveFolderJobs(rows, current));
+ if (sourcesChanged) onSourcesChanged?.();
+ for (const folder of rows) {
+ if (
+ !folder.activeJobId ||
+ controllers.current.has(folder.activeJobId)
+ ) {
+ continue;
+ }
+ try {
+ const job = await getFolderSyncJob(folder.activeJobId);
+ if (!isCurrent()) return false;
+ if (job.status === "pending" || job.status === "running") {
+ trackJob(job);
+ } else {
+ setJobs((current) => ({ ...current, [folder.id]: job }));
+ if (sourcesChanged) notifiedJobs.current.add(job.id);
+ else notifySourcesChanged(job);
+ }
+ } catch {
+ // The next refresh can reconcile a job that disappeared mid-request.
+ }
+ }
+ return sourcesChanged;
+ } catch (error) {
+ if (isCurrent() && !options?.quiet) {
+ toast.error("Failed to load linked folders", {
+ description:
+ error instanceof Error ? error.message : String(error),
+ });
+ }
+ return false;
+ } finally {
+ if (isCurrent() && !options?.quiet) setLoading(false);
+ }
+ });
+ },
+ [
+ scopeKey,
+ scopeType,
+ scopeId,
+ trackJob,
+ notifySourcesChanged,
+ onSourcesChanged,
+ ],
+ );
+
+ useEffect(() => {
+ currentScopeKey.current = scopeKey;
+ folderSnapshot.current = null;
+ notifiedJobs.current.clear();
+ const initialRefresh = window.setTimeout(() => void refresh(), 0);
+ const interval = window.setInterval(
+ () => void refresh({ quiet: true }),
+ 4000,
+ );
+ const activeControllers = controllers.current;
+ return () => {
+ window.clearTimeout(initialRefresh);
+ window.clearInterval(interval);
+ for (const controller of activeControllers.values()) controller.abort();
+ activeControllers.clear();
+ };
+ }, [refresh, scopeKey]);
+
+ const link = useCallback(async () => {
+ if (!scopeType || !scopeId || !isTauri) return;
+ const operationScopeKey = scopeKey;
+ setMutating(true);
+ try {
+ const selected = await pickNativeDocumentFolder();
+ if (!selected || currentScopeKey.current !== operationScopeKey) return;
+ const result = await createLinkedFolder(
+ { type: scopeType, id: scopeId },
+ selected.token,
+ selected.displayName,
+ );
+ if (currentScopeKey.current !== operationScopeKey) return;
+ setStateScopeKey(operationScopeKey);
+ setFolders((current) => [
+ ...current.filter((folder) => folder.id !== result.linkedFolder.id),
+ result.linkedFolder,
+ ]);
+ trackJob(result.job);
+ onSourcesChanged?.();
+ } catch (error) {
+ toast.error("Could not link folder", {
+ description: error instanceof Error ? error.message : String(error),
+ });
+ } finally {
+ setMutating(false);
+ }
+ }, [scopeKey, scopeType, scopeId, trackJob, onSourcesChanged]);
+
+ const run = useCallback(
+ async (folderId: string, mode: "sync" | "rebuild") => {
+ const operationScopeKey = scopeKey;
+ try {
+ const { job } =
+ mode === "rebuild"
+ ? await rebuildLinkedFolder(folderId)
+ : await syncLinkedFolder(folderId);
+ if (currentScopeKey.current !== operationScopeKey) return;
+ trackJob(job);
+ onSourcesChanged?.();
+ } catch (error) {
+ toast.error(`Could not ${mode} folder`, {
+ description: error instanceof Error ? error.message : String(error),
+ });
+ }
+ },
+ [scopeKey, trackJob, onSourcesChanged],
+ );
+
+ const remove = useCallback(
+ async (folderId: string, removeIndex: boolean) => {
+ const operationScopeKey = scopeKey;
+ const previous = folders;
+ const activeJobId =
+ folders.find((folder) => folder.id === folderId)?.activeJobId ??
+ jobs[folderId]?.id;
+ const activeJob =
+ jobs[folderId]?.id === activeJobId ? jobs[folderId] : undefined;
+ if (activeJobId) {
+ controllers.current.get(activeJobId)?.abort();
+ controllers.current.delete(activeJobId);
+ }
+ setFolders((current) =>
+ current.filter((folder) => folder.id !== folderId),
+ );
+ try {
+ await deleteLinkedFolder(folderId, removeIndex);
+ if (currentScopeKey.current !== operationScopeKey) return;
+ onSourcesChanged?.();
+ setJobs((current) => {
+ const next = { ...current };
+ delete next[folderId];
+ return next;
+ });
+ } catch (error) {
+ if (currentScopeKey.current !== operationScopeKey) return;
+ setFolders(previous);
+ if (
+ activeJob &&
+ (activeJob.status === "pending" || activeJob.status === "running")
+ ) {
+ trackJob(activeJob);
+ } else {
+ void refresh({ quiet: true });
+ }
+ toast.error("Could not unlink folder", {
+ description: error instanceof Error ? error.message : String(error),
+ });
+ }
+ },
+ [scopeKey, folders, jobs, trackJob, refresh, onSourcesChanged],
+ );
+
+ return {
+ folders: stateScopeKey === scopeKey ? folders : [],
+ jobs: stateScopeKey === scopeKey ? jobs : {},
+ loading: stateScopeKey === scopeKey ? loading : true,
+ mutating,
+ desktopSupported: isTauri,
+ link,
+ sync: (folderId: string) => run(folderId, "sync"),
+ rebuild: (folderId: string) => run(folderId, "rebuild"),
+ remove,
+ refresh,
+ };
+}
diff --git a/studio/frontend/src/features/rag/components/use-rag-documents.ts b/studio/frontend/src/features/rag/components/use-rag-documents.ts
index d75d98ad45a..cef0bbd2a0a 100644
--- a/studio/frontend/src/features/rag/components/use-rag-documents.ts
+++ b/studio/frontend/src/features/rag/components/use-rag-documents.ts
@@ -1,8 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-import { toast } from "@/lib/toast";
import { consumeNativePathToken } from "@/features/native-intents";
+import { toast } from "@/lib/toast";
import { useCallback, useEffect, useRef, useState } from "react";
import {
deleteDocument,
@@ -205,7 +205,7 @@ export function useRagDocuments(
const refresh = useCallback(
async (opts?: { quiet?: boolean }) => {
- if (!scope) return;
+ if (!scopeKey) return;
if (!opts?.quiet) setLoading(true);
try {
// Merge server truth with local progress so a refresh mid-index keeps a
@@ -236,7 +236,7 @@ export function useRagDocuments(
if (!opts?.quiet) setLoading(false);
}
},
- [scope, lister],
+ [scopeKey, lister],
);
// A real switch (thread/KB swap) resets + reloads; first acquiring a scope just
@@ -330,7 +330,9 @@ export function useRagDocuments(
sigByDocId.current.set(result.documentId, itemSignature(item));
if (seenIds.has(result.documentId)) {
setDocuments((rows) => rows.filter((row) => row.id !== tempId));
- toast.info(`${result.filename || name} is already indexed - skipping`);
+ toast.info(
+ `${result.filename || name} is already indexed - skipping`,
+ );
return;
}
seenIds.add(result.documentId);
@@ -397,6 +399,7 @@ export function useRagDocuments(
id: tempId,
filename: itemName(item),
status: "pending" as const,
+ managed: false,
progress: null,
})),
]);
diff --git a/studio/frontend/src/features/rag/index.ts b/studio/frontend/src/features/rag/index.ts
index b06c7e09cca..24b0c9ac607 100644
--- a/studio/frontend/src/features/rag/index.ts
+++ b/studio/frontend/src/features/rag/index.ts
@@ -3,11 +3,15 @@
export { KnowledgeBaseComposerButton } from "./components/knowledge-base-composer-button";
export { KnowledgeBaseDialog } from "./components/knowledge-base-dialog";
+export { LinkedFoldersManager } from "./components/linked-folders-manager";
export { RetrievalSettingsSection } from "./components/retrieval-settings-section";
export { ThreadDocumentsBar } from "./components/thread-documents-bar";
export {
deleteDocument,
getDocumentFileUrl,
listAllDocuments,
+ listKnowledgeBases,
} from "./api/rag-api";
+export { useRagAvailabilityStore } from "./api/rag-availability";
+export { isLinkedFolderManaged } from "./types/rag";
export type { KnowledgeBase, RagDocument, UploadedDocument } from "./types/rag";
diff --git a/studio/frontend/src/features/rag/types/rag.ts b/studio/frontend/src/features/rag/types/rag.ts
index 992dc1ba7b9..0ceafac9fe8 100644
--- a/studio/frontend/src/features/rag/types/rag.ts
+++ b/studio/frontend/src/features/rag/types/rag.ts
@@ -21,9 +21,15 @@ export interface RagDocument {
kbId?: string | null;
threadId?: string | null;
projectId?: string | null;
+ linkedFolderId?: string | null;
+ managed: boolean;
createdAt?: string | null;
}
+export function isLinkedFolderManaged(document: RagDocument): boolean {
+ return Boolean(document.managed || document.linkedFolderId);
+}
+
/** RagDocument enriched for the global uploaded-files list (settings Data tab). */
export interface UploadedDocument extends RagDocument {
sizeBytes?: number | null;
@@ -74,6 +80,87 @@ export interface JobEvent {
num_chunks?: number | null;
}
+export type LinkedFolderScopeType = "knowledge_base" | "project";
+
+export interface LinkedFolderScope {
+ type: LinkedFolderScopeType;
+ id: string;
+}
+
+export type LinkedFolderStatus = "idle" | "syncing" | "error";
+
+/** A local directory whose durable access grant is held by the desktop backend. */
+export interface LinkedFolder {
+ id: string;
+ displayName: string;
+ scopeType: LinkedFolderScopeType;
+ scopeId: string;
+ scopeName?: string | null;
+ status: LinkedFolderStatus;
+ documentCount?: number;
+ lastSyncedAt?: string | null;
+ error?: string | null;
+ activeJobId?: string | null;
+ createdAt?: string | null;
+}
+
+export function linkedFolderSourcesChanged(
+ previous: LinkedFolder[] | null,
+ current: LinkedFolder[],
+): boolean {
+ if (!previous) return false;
+ const previousById = new Map(previous.map((folder) => [folder.id, folder]));
+ if (
+ previous.length !== current.length ||
+ previous.some((folder) => !current.some((row) => row.id === folder.id))
+ ) {
+ return true;
+ }
+ return current.some((folder) => {
+ const prior = previousById.get(folder.id);
+ return (
+ prior !== undefined &&
+ (prior.documentCount !== folder.documentCount ||
+ prior.lastSyncedAt !== folder.lastSyncedAt)
+ );
+ });
+}
+
+export type FolderSyncMode = "sync" | "rebuild";
+
+/** Aggregate job for discovering and indexing all changes in a linked folder. */
+export interface FolderSyncJob {
+ id: string;
+ linkedFolderId: string;
+ mode: FolderSyncMode;
+ status: JobStatus;
+ stage?: string | null;
+ progress?: number | null;
+ discoveredFiles?: number;
+ processedFiles?: number;
+ indexedFiles?: number;
+ removedFiles?: number;
+ failedFiles?: number;
+ error?: string | null;
+}
+
+/** One SSE frame from /linked-folder-jobs/{jobId}/events. */
+export interface FolderSyncJobEvent extends Partial<FolderSyncJob> {
+ type: "progress" | "complete" | "error";
+}
+
+export function retainActiveFolderJobs(
+ folders: LinkedFolder[],
+ jobs: Record<string, FolderSyncJob>,
+): Record<string, FolderSyncJob> {
+ const retained: Record<string, FolderSyncJob> = {};
+ for (const folder of folders) {
+ const job = jobs[folder.id];
+ if (job && folder.activeJobId === job.id) retained[folder.id] = job;
+ }
+ return retained;
+}
+
/** Coords 0..1, top-left origin. */
export interface PdfRegion {
pageIndex: number;
diff --git a/studio/frontend/src/features/settings/components/uploaded-files-dialog.tsx b/studio/frontend/src/features/settings/components/uploaded-files-dialog.tsx
index e8d3a8a1b42..4e063ff9bb4 100644
--- a/studio/frontend/src/features/settings/components/uploaded-files-dialog.tsx
+++ b/studio/frontend/src/features/settings/components/uploaded-files-dialog.tsx
@@ -20,10 +20,11 @@ import {
listChatAttachments,
} from "@/features/chat";
import {
+ type UploadedDocument,
deleteDocument,
getDocumentFileUrl,
+ isLinkedFolderManaged,
listAllDocuments,
- type UploadedDocument,
} from "@/features/rag";
import { isTauri } from "@/lib/api-base";
import { downloadFile, isDownloadCancelled } from "@/lib/native-files";
@@ -178,8 +179,8 @@ interface UploadedFileRow {
/** Compare-chat rows navigate by pair id instead of opening one pane alone. */
pairId?: string | null;
open: () => Promise<void>;
- remove: () => Promise<void>;
- deleteDescription: string;
+ remove?: () => Promise<void>;
+ deleteDescription?: string;
}
function toSortTime(value: string | number | null | undefined): number {
@@ -231,11 +232,14 @@ function ragRow(doc: UploadedDocument): UploadedFileRow {
// RAG uploads are documents (pdf, txt, md, docx, html), not images.
thumb: <FileIconThumb />,
open: () => openResolvedUrl(() => getDocumentFileUrl(doc.id)),
- remove: async () => {
- await deleteDocument(doc.id, doc.projectId);
- },
- deleteDescription:
- "The file and its indexed content are removed. This cannot be undone.",
+ remove: isLinkedFolderManaged(doc)
+ ? undefined
+ : async () => {
+ await deleteDocument(doc.id, doc.projectId);
+ },
+ deleteDescription: isLinkedFolderManaged(doc)
+ ? undefined
+ : "The file and its indexed content are removed. This cannot be undone.",
};
}
@@ -483,7 +487,7 @@ export function UploadedFilesView() {
async function handleDelete(row: UploadedFileRow) {
// Offset pages and destructive mutations must not race: a deletion shifts
// the boundary used by an in-flight page request.
- if (loadingMore) return;
+ if (loadingMore || !row.remove) return;
try {
await row.remove();
if (row.source === "rag") {
@@ -637,20 +641,22 @@ export function UploadedFilesView() {
className="size-4"
/>
</button>
- <button
- type="button"
- disabled={loadingMore}
- onClick={() => setConfirmingDelete(row)}
- aria-label={`Delete ${row.name}`}
- title="Delete"
- className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive disabled:cursor-wait disabled:opacity-50"
- >
- <HugeiconsIcon
- icon={Delete02Icon}
- strokeWidth={1.75}
- className="size-4"
- />
- </button>
+ {row.remove ? (
+ <button
+ type="button"
+ disabled={loadingMore}
+ onClick={() => setConfirmingDelete(row)}
+ aria-label={`Delete ${row.name}`}
+ title="Delete"
+ className="inline-flex size-7 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive disabled:cursor-wait disabled:opacity-50"
+ >
+ <HugeiconsIcon
+ icon={Delete02Icon}
+ strokeWidth={1.75}
+ className="size-4"
+ />
+ </button>
+ ) : null}
</span>
</div>
))}
diff --git a/studio/frontend/src/features/settings/tabs/data-tab.tsx b/studio/frontend/src/features/settings/tabs/data-tab.tsx
index 9e4737c4a65..2f8cb414608 100644
--- a/studio/frontend/src/features/settings/tabs/data-tab.tsx
+++ b/studio/frontend/src/features/settings/tabs/data-tab.tsx
@@ -39,14 +39,19 @@ import {
useChatRuntimeStore,
useChatSidebarItems,
} from "@/features/chat";
+import {
+ LinkedFoldersManager,
+ listKnowledgeBases,
+ useRagAvailabilityStore,
+} from "@/features/rag";
import { useT } from "@/i18n";
import { isTauri } from "@/lib/api-base";
-import { isDownloadCancelled, pickNativeChatImport } from "@/lib/native-files";
import {
ChevronDownStandardIcon,
ChevronRightStandardIcon,
} from "@/lib/chevron-icons";
+import { isDownloadCancelled, pickNativeChatImport } from "@/lib/native-files";
import { toast } from "@/lib/toast";
import {
Archive02Icon,
@@ -105,6 +110,10 @@ export function DataTab() {
// the Train tab would upload it and then strand the user; gate the action
// the same way the sidebar gates Train.
const chatOnly = usePlatformStore((s) => s.isChatOnly());
+ const ragUnavailable = useRagAvailabilityStore((s) => s.isUnavailable());
+ const ragAvailabilityUnknown = useRagAvailabilityStore((s) =>
+ s.availabilityUnknown(),
+ );
const storedFineTuneAction = useSettingsPanelPrefsStore(
(s) => s.fineTuneAction,
);
@@ -134,6 +143,31 @@ export function DataTab() {
};
}, [archivedChatsRequested, consumeArchivedChatsRequest]);
+ useEffect(() => {
+ if (!ragAvailabilityUnknown) return;
+ let cancelled = false;
+ let retryTimer: number | undefined;
+ let retryDelayMs = 1_000;
+
+ const probeAvailability = async () => {
+ try {
+ await listKnowledgeBases();
+ } catch {
+ if (cancelled) return;
+ retryTimer = window.setTimeout(() => {
+ retryDelayMs = Math.min(retryDelayMs * 2, 30_000);
+ void probeAvailability();
+ }, retryDelayMs);
+ }
+ };
+
+ void probeAvailability();
+ return () => {
+ cancelled = true;
+ if (retryTimer !== undefined) window.clearTimeout(retryTimer);
+ };
+ }, [ragAvailabilityUnknown]);
+
const confirmDeleteChats = useChatPreferencesStore(
(state) => state.confirmDeleteChats,
);
@@ -707,6 +741,11 @@ export function DataTab() {
{t("settings.data.manageAction")}
</Button>
</SettingsRow>
+ {!ragAvailabilityUnknown && !ragUnavailable ? (
+ <div className="py-3">
+ <LinkedFoldersManager />
+ </div>
+ ) : null}
</SettingsSection>
<Dialog open={archiveConfirmOpen} onOpenChange={setArchiveConfirmOpen}>
diff --git a/studio/frontend/src/features/training/api/train-api.ts b/studio/frontend/src/features/training/api/train-api.ts
index 0fb61dcddcc..06fe537cd9d 100644
--- a/studio/frontend/src/features/training/api/train-api.ts
+++ b/studio/frontend/src/features/training/api/train-api.ts
@@ -3,7 +3,7 @@
import { authFetch } from "@/features/auth";
import { readFastApiError } from "@/lib/format-fastapi-error";
-import { createScopedSingleFlightRequest } from "../lib/single-flight-request";
+import { createScopedSingleFlightRequest } from "@/lib/single-flight-request";
import {
type ParsedTrainingProgressEvent,
consumeTrainingProgressStream,
diff --git a/studio/frontend/src/features/training/hooks/use-training-completion-watch.ts b/studio/frontend/src/features/training/hooks/use-training-completion-watch.ts
index efe68562984..3d161c6b813 100644
--- a/studio/frontend/src/features/training/hooks/use-training-completion-watch.ts
+++ b/studio/frontend/src/features/training/hooks/use-training-completion-watch.ts
@@ -4,7 +4,7 @@
import { useEffect } from "react";
import { getTrainingStatus } from "../api/train-api";
-import { createSingleFlightRequest } from "../lib/single-flight-request";
+import { createSingleFlightRequest } from "@/lib/single-flight-request";
import {
isTrainingStatusRequestCurrent,
trainingStatusRequestKey,
@@ -17,12 +17,12 @@ import {
const WATCH_INTERVAL_MS = 6000;
/**
-* Keep training state fresh while a run is active, even off the Train page.
-*
-* The lifecycle poll (`useTrainingRuntimeLifecycle`) only runs while Train is mounted, so a run
-* finishing on another tab would leave the sidebar spinner stuck. Polls `/api/train/status` only
-* while a run is in progress. Mount once in an always-rendered shell.
-*/
+ * Keep training state fresh while a run is active, even off the Train page.
+ *
+ * The lifecycle poll (`useTrainingRuntimeLifecycle`) only runs while Train is mounted, so a run
+ * finishing on another tab would leave the sidebar spinner stuck. Polls `/api/train/status` only
+ * while a run is in progress. Mount once in an always-rendered shell.
+ */
export function useTrainingCompletionWatch(): void {
const active = useTrainingRuntimeStore(isTrainingStartPending);
diff --git a/studio/frontend/src/features/training/lib/training-sse-stream.ts b/studio/frontend/src/features/training/lib/training-sse-stream.ts
index ae23701bcb9..72d5f460b4a 100644
--- a/studio/frontend/src/features/training/lib/training-sse-stream.ts
+++ b/studio/frontend/src/features/training/lib/training-sse-stream.ts
@@ -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
-import { takeSseFrame } from "../api/sse-framing.ts";
+import { takeSseFrame } from "../../../lib/sse-framing.ts";
import type { TrainingProgressPayload } from "../types/runtime";
export type TrainingProgressEventName =
diff --git a/studio/frontend/src/features/training/lib/single-flight-request.ts b/studio/frontend/src/lib/single-flight-request.ts
similarity index 81%
rename from studio/frontend/src/features/training/lib/single-flight-request.ts
rename to studio/frontend/src/lib/single-flight-request.ts
index 0a6a7f85c82..2a08140b631 100644
--- a/studio/frontend/src/features/training/lib/single-flight-request.ts
+++ b/studio/frontend/src/lib/single-flight-request.ts
@@ -7,16 +7,12 @@ export function createSingleFlightRequest<TResult>(
let inFlight: Promise<TResult> | null = null;
return () => {
- if (inFlight) {
- return inFlight;
- }
+ if (inFlight) return inFlight;
const current = Promise.resolve().then(request);
inFlight = current;
const clear = () => {
- if (inFlight === current) {
- inFlight = null;
- }
+ if (inFlight === current) inFlight = null;
};
void current.then(clear, clear);
return current;
@@ -49,9 +45,7 @@ export function createScopedSingleFlightRequest<TInput, TResult>(
const current = { scope, controller, promise };
inFlight = current;
const clear = () => {
- if (inFlight === current) {
- inFlight = null;
- }
+ if (inFlight === current) inFlight = null;
};
void promise.then(clear, clear);
return promise;
@@ -64,13 +58,10 @@ export function createScopedSingleFlightRequest<TInput, TResult>(
return {
run: (scope, input) => {
- if (!inFlight) {
- return start(scope, input);
- }
- if (inFlight.scope === scope) {
- return inFlight.promise;
- }
- return supersede(scope, input);
+ if (!inFlight) return start(scope, input);
+ return inFlight.scope === scope
+ ? inFlight.promise
+ : supersede(scope, input);
},
refresh: supersede,
};
diff --git a/studio/frontend/src/features/training/api/sse-framing.ts b/studio/frontend/src/lib/sse-framing.ts
similarity index 100%
rename from studio/frontend/src/features/training/api/sse-framing.ts
rename to studio/frontend/src/lib/sse-framing.ts
diff --git a/studio/frontend/src/lib/sse-json-events.ts b/studio/frontend/src/lib/sse-json-events.ts
new file mode 100644
index 00000000000..dcb2daec382
--- /dev/null
+++ b/studio/frontend/src/lib/sse-json-events.ts
@@ -0,0 +1,77 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import { takeSseFrame } from "./sse-framing.ts";
+
+const LINE_BREAK = /\r?\n/;
+
+/** Pull every complete frame out of `buffer`, returning their data payloads and the rest. */
+function drainFrames(buffer: string): { payloads: string[]; rest: string } {
+ const payloads: string[] = [];
+ let rest = buffer;
+ let frame = takeSseFrame(rest);
+ while (frame) {
+ rest = frame.remainder;
+ const data = frame.event
+ .split(LINE_BREAK)
+ .filter((line) => line.startsWith("data:"))
+ .map((line) => line.slice(5).trimStart())
+ .join("\n");
+ if (data) payloads.push(data);
+ frame = takeSseFrame(rest);
+ }
+ return { payloads, rest };
+}
+
+function readWithStall(
+ reader: ReadableStreamDefaultReader<Uint8Array>,
+ onStall: () => void,
+ stallMs: number | undefined,
+): Promise<ReadableStreamReadResult<Uint8Array>> {
+ if (stallMs === undefined) return reader.read();
+ const stall = setTimeout(onStall, stallMs);
+ return reader.read().finally(() => clearTimeout(stall));
+}
+
+/**
+ * Yield the JSON payload of each `data:` frame until the stream ends or sends [DONE].
+ *
+ * `stallMs` bounds the silence between frames. A reverse proxy such as a Cloudflare
+ * tunnel can hold a whole event stream until the response completes, and no origin
+ * header or padding prevents it, so the only recourse is to abandon a silent stream.
+ * The generator ends rather than throwing, which is indistinguishable from a normal
+ * close and lets a caller reconcile by polling.
+ */
+export async function* readSseJsonEvents<T>(
+ body: ReadableStream<Uint8Array>,
+ stallMs?: number,
+): AsyncGenerator<T> {
+ const reader = body.getReader();
+ const decoder = new TextDecoder();
+ // cancelling resolves the pending read as done, so the generator ends without an error
+ const cancel = () => {
+ reader.cancel().catch(() => undefined);
+ };
+ let buffer = "";
+ try {
+ while (true) {
+ const chunk = await readWithStall(reader, cancel, stallMs);
+ if (chunk.done) break;
+ const { payloads, rest } = drainFrames(
+ buffer + decoder.decode(chunk.value, { stream: true }),
+ );
+ buffer = rest;
+ for (const data of payloads) {
+ if (data === "[DONE]") return;
+ try {
+ yield JSON.parse(data) as T;
+ } catch {
+ // ignore unparseable frames; [DONE] still ends the loop
+ }
+ }
+ }
+ } finally {
+ // release the stream lock now instead of leaking the reader until GC
+ cancel();
+ }
+}
diff --git a/studio/frontend/tests/linked-folders-contract.test.ts b/studio/frontend/tests/linked-folders-contract.test.ts
new file mode 100644
index 00000000000..22f431c05f6
--- /dev/null
+++ b/studio/frontend/tests/linked-folders-contract.test.ts
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ isLinkedFolderManaged,
+ linkedFolderSourcesChanged,
+ retainActiveFolderJobs,
+} from "../src/features/rag/types/rag.ts";
+
+test("documents managed by linked folders cannot be treated as individual uploads", () => {
+ const document = {
+ id: "doc",
+ filename: "notes.md",
+ status: "completed",
+ managed: false,
+ } as const;
+ assert.equal(isLinkedFolderManaged(document), false);
+ assert.equal(
+ isLinkedFolderManaged({ ...document, linkedFolderId: "folder" }),
+ true,
+ );
+ assert.equal(isLinkedFolderManaged({ ...document, managed: true }), true);
+});
+
+test("only the folder's currently active job remains visible after polling", () => {
+ const folder = {
+ id: "folder",
+ displayName: "Docs",
+ scopeType: "project",
+ scopeId: "project",
+ status: "idle",
+ activeJobId: "job-2",
+ } as const;
+ const jobs = {
+ folder: {
+ id: "job-1",
+ linkedFolderId: "folder",
+ mode: "sync",
+ status: "completed",
+ },
+ } as const;
+ assert.deepEqual(retainActiveFolderJobs([folder], jobs), {});
+ assert.deepEqual(
+ retainActiveFolderJobs([{ ...folder, activeJobId: "job-1" }], jobs),
+ jobs,
+ );
+ assert.deepEqual(
+ retainActiveFolderJobs([{ ...folder, activeJobId: null }], jobs),
+ {},
+ );
+});
+
+test("folder polling detects completed backend work without a visible active job", () => {
+ const folder = {
+ id: "folder",
+ displayName: "Docs",
+ scopeType: "project",
+ scopeId: "project",
+ status: "idle",
+ documentCount: 2,
+ lastSyncedAt: "2026-08-06T10:00:00Z",
+ } as const;
+ assert.equal(linkedFolderSourcesChanged(null, [folder]), false);
+ assert.equal(linkedFolderSourcesChanged([folder], [folder]), false);
+ assert.equal(
+ linkedFolderSourcesChanged(
+ [folder],
+ [
+ {
+ ...folder,
+ documentCount: 3,
+ lastSyncedAt: "2026-08-06T10:01:00Z",
+ },
+ ],
+ ),
+ true,
+ );
+});
diff --git a/studio/frontend/tests/rag-availability-marker.test.ts b/studio/frontend/tests/rag-availability-marker.test.ts
index 9e661f1ca9a..827e600b601 100644
--- a/studio/frontend/tests/rag-availability-marker.test.ts
+++ b/studio/frontend/tests/rag-availability-marker.test.ts
@@ -204,7 +204,7 @@ test("the KB list's own 200 does not overrule its marker", () => {
);
});
-// Three call sites, because two of them bypass ragRequest.
+// four call sites, because three of them bypass ragRequest
test("every RAG response path reports availability", async () => {
const src = await readSrc("features/rag/api/rag-api.ts");
assert.match(
@@ -229,12 +229,19 @@ test("every RAG response path reports availability", async () => {
/noteRagResponse\(response\.status, json\)/,
"ragUpload bypasses ragRequest, so its 503 is still dropped",
);
- const stream = functionBody(src, "streamJobEvents");
+ const stream = functionBody(src, "openEventStream");
assert.match(
stream,
/noteRagResponse\(response\.status, body\)/,
- "the SSE endpoint bypasses ragRequest too",
+ "the SSE endpoints bypass ragRequest too",
);
+ for (const generator of ["streamJobEvents", "streamFolderSyncJobEvents"]) {
+ assert.match(
+ functionBody(src, generator),
+ /openEventStream\(/,
+ `${generator} opens its stream without the availability check`,
+ );
+ }
});
test("listKnowledgeBases reads the marker before returning the array", async () => {
diff --git a/studio/frontend/tests/single-flight-request.test.ts b/studio/frontend/tests/single-flight-request.test.ts
index 7e5935a140d..b265666565f 100644
--- a/studio/frontend/tests/single-flight-request.test.ts
+++ b/studio/frontend/tests/single-flight-request.test.ts
@@ -7,7 +7,7 @@ import test from "node:test";
import {
createScopedSingleFlightRequest,
createSingleFlightRequest,
-} from "../src/features/training/lib/single-flight-request.ts";
+} from "../src/lib/single-flight-request.ts";
function deferred<T>() {
let resolve!: (value: T) => void;
diff --git a/studio/frontend/tests/sse-framing.test.ts b/studio/frontend/tests/sse-framing.test.ts
index 7965865cf37..7e412d341f2 100644
--- a/studio/frontend/tests/sse-framing.test.ts
+++ b/studio/frontend/tests/sse-framing.test.ts
@@ -3,7 +3,7 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { takeSseFrame } from "../src/features/training/api/sse-framing.ts";
+import { takeSseFrame } from "../src/lib/sse-framing.ts";
test("preserves the next SSE frame across every supported delimiter", () => {
for (const separator of ["\n\n", "\r\n\r\n", "\n\r\n", "\r\n\n"]) {
diff --git a/studio/frontend/tests/sse-json-events.test.ts b/studio/frontend/tests/sse-json-events.test.ts
new file mode 100644
index 00000000000..e24dafb562b
--- /dev/null
+++ b/studio/frontend/tests/sse-json-events.test.ts
@@ -0,0 +1,79 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import { readSseJsonEvents } from "../src/lib/sse-json-events.ts";
+
+function streamOf(
+ chunks: string[],
+ { gapMs = 0, trailingSilence = false } = {},
+): ReadableStream<Uint8Array> {
+ const encoder = new TextEncoder();
+ let index = 0;
+ return new ReadableStream({
+ async pull(controller) {
+ if (index >= chunks.length) {
+ if (!trailingSilence) controller.close();
+ return;
+ }
+ if (gapMs) await new Promise((resolve) => setTimeout(resolve, gapMs));
+ controller.enqueue(encoder.encode(chunks[index++]));
+ },
+ });
+}
+
+async function collect<T>(events: AsyncGenerator<T>): Promise<T[]> {
+ const out: T[] = [];
+ for await (const event of events) out.push(event);
+ return out;
+}
+
+test("frames split on any CRLF or LF blank-line separator", async () => {
+ const events = await collect(
+ readSseJsonEvents<{ n: number }>(
+ streamOf([
+ 'data: {"n": 1}\n\n',
+ 'data: {"n": 2}\r\n\r\n',
+ 'data: {"n"',
+ ': 3}\n\n',
+ ]),
+ ),
+ );
+ assert.deepEqual(events, [{ n: 1 }, { n: 2 }, { n: 3 }]);
+});
+
+test("[DONE] ends the stream and unparseable frames are skipped", async () => {
+ const events = await collect(
+ readSseJsonEvents<{ n: number }>(
+ streamOf([
+ "data: not json\n\n",
+ 'data: {"n": 9}\n\n',
+ "data: [DONE]\n\n",
+ 'data: {"n": 10}\n\n',
+ ]),
+ ),
+ );
+ assert.deepEqual(events, [{ n: 9 }]);
+});
+
+test("a stream that goes silent ends instead of hanging, keeping frames already seen", async () => {
+ const started = Date.now();
+ const events = await collect(
+ readSseJsonEvents<{ n: number }>(
+ streamOf(['data: {"n": 1}\n\n'], { trailingSilence: true }),
+ 60,
+ ),
+ );
+ assert.deepEqual(events, [{ n: 1 }]);
+ assert.ok(Date.now() - started < 2000);
+});
+
+test("without a stall bound a slow stream still delivers every frame", async () => {
+ const events = await collect(
+ readSseJsonEvents<{ n: number }>(
+ streamOf(['data: {"n": 1}\n\n', 'data: {"n": 2}\n\n'], { gapMs: 40 }),
+ ),
+ );
+ assert.deepEqual(events, [{ n: 1 }, { n: 2 }]);
+});
diff --git a/studio/src-tauri/Cargo.toml b/studio/src-tauri/Cargo.toml
index ad95c3a85e3..5e1f26b8f36 100644
--- a/studio/src-tauri/Cargo.toml
+++ b/studio/src-tauri/Cargo.toml
@@ -65,7 +65,7 @@ webview2-com = "0.38"
winreg = "0.55"
windows = { version = "0.62.2", features = ["Win32_System_Threading"] }
windows-core = "0.61.2"
-windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse"] }
+windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse"] }
[build-dependencies]
tauri-build = { version = "2", features = [] }
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index d838b9d46bf..6d725af9b03 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -1558,6 +1558,7 @@ fn main() {
native_intents::read_native_attachment_file,
native_intents::pick_native_model,
native_intents::pick_hugging_face_cache_dir,
+ native_intents::pick_native_document_folder,
native_intents::consume_native_path_token,
native_intents::register_artifact_path,
native_intents::reveal_path_token,
diff --git a/studio/src-tauri/src/native_backend_lease.rs b/studio/src-tauri/src/native_backend_lease.rs
index 33ee4bbfb42..6e94dc19e41 100644
--- a/studio/src-tauri/src/native_backend_lease.rs
+++ b/studio/src-tauri/src/native_backend_lease.rs
@@ -18,6 +18,7 @@ pub enum NativePathOperation {
DatasetPreview,
DatasetImport,
Attach,
+ LinkDocuments,
Reveal,
Open,
}
@@ -28,6 +29,7 @@ pub enum NativePathKind {
Model,
Dataset,
Attachment,
+ DocumentFolder,
Artifact,
}
@@ -41,7 +43,7 @@ pub enum NativePathSourceKind {
Artifact,
}
-#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
+#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum NativePathType {
File,
@@ -64,6 +66,8 @@ pub struct NativePathLeasePayload {
pub display_label: String,
pub size_bytes: Option<u64>,
pub modified_ms: Option<u64>,
+ pub device_id: Option<String>,
+ pub file_id: Option<String>,
}
#[derive(Clone, Debug, Serialize)]
@@ -111,6 +115,8 @@ pub struct NativePathLeaseRequest {
pub display_label: String,
pub size_bytes: Option<u64>,
pub modified_ms: Option<u64>,
+ pub device_id: Option<String>,
+ pub file_id: Option<String>,
}
pub fn sign_path_lease(
@@ -133,6 +139,8 @@ pub fn sign_path_lease(
display_label: request.display_label.clone(),
size_bytes: request.size_bytes,
modified_ms: request.modified_ms,
+ device_id: request.device_id,
+ file_id: request.file_id,
};
sign_payload(secret, &payload).map(|native_path_lease| NativePathLeaseResponse {
native_path_lease,
@@ -172,6 +180,11 @@ pub fn hex_bytes(bytes: &[u8]) -> String {
mod tests {
use super::*;
+ fn decode_payload(lease: &str) -> serde_json::Value {
+ let payload = lease.split('.').next().unwrap();
+ serde_json::from_slice(&URL_SAFE_NO_PAD.decode(payload).unwrap()).unwrap()
+ }
+
#[test]
fn token_hash_is_stable_hex_sha256() {
assert_eq!(
@@ -194,6 +207,8 @@ mod tests {
display_label: "model.gguf".to_string(),
size_bytes: Some(123),
modified_ms: Some(456),
+ device_id: Some("7".to_string()),
+ file_id: Some("8".to_string()),
},
)
.unwrap();
@@ -202,4 +217,39 @@ mod tests {
assert!(!parts[0].contains('='));
assert!(!parts[1].contains('='));
}
+
+ #[test]
+ fn document_folder_lease_payload_has_backend_contract_values() {
+ let lease = sign_path_lease(
+ b"01234567890123456789012345678901",
+ NativePathLeaseRequest {
+ operation: NativePathOperation::LinkDocuments,
+ canonical_path: "/tmp/knowledge".to_string(),
+ path_kind: NativePathKind::DocumentFolder,
+ path_type: NativePathType::Directory,
+ source_kind: NativePathSourceKind::Dialog,
+ token: "path_token".to_string(),
+ display_label: "knowledge".to_string(),
+ size_bytes: None,
+ modified_ms: None,
+ device_id: Some("7".to_string()),
+ file_id: Some("8".to_string()),
+ },
+ )
+ .unwrap();
+ let payload = decode_payload(&lease.native_path_lease);
+
+ assert_eq!(payload["operation"], "link-documents");
+ assert_eq!(payload["path_kind"], "document-folder");
+ assert_eq!(payload["path_type"], "directory");
+ assert_eq!(payload["source_kind"], "dialog");
+ assert_eq!(payload["token_id_hash"], token_hash("path_token"));
+ let issued_at_ms = payload["issued_at_ms"].as_u64().unwrap();
+ let expires_at_ms = payload["expires_at_ms"].as_u64().unwrap();
+ assert!(expires_at_ms > issued_at_ms);
+ assert_eq!(expires_at_ms - issued_at_ms, 120_000);
+ assert!(payload["modified_ms"].is_null());
+ assert_eq!(payload["device_id"], "7");
+ assert_eq!(payload["file_id"], "8");
+ }
}
diff --git a/studio/src-tauri/src/native_intents.rs b/studio/src-tauri/src/native_intents.rs
index 5ea1d8bb51c..6831aab300d 100644
--- a/studio/src-tauri/src/native_intents.rs
+++ b/studio/src-tauri/src/native_intents.rs
@@ -5,7 +5,8 @@ use crate::native_backend_lease::{
};
use crate::native_path_policy::{
classify_artifact_path, classify_native_attachment_path, classify_native_dataset_path,
- classify_native_model_path, reveal_target, ClassifiedPath, NativeArtifactKind,
+ classify_native_document_folder, classify_native_model_path, reveal_target, ClassifiedPath,
+ NativeArtifactKind,
};
use serde::Serialize;
use std::collections::{HashMap, VecDeque};
@@ -56,6 +57,8 @@ struct NativePathEntry {
expires_at_ms: u64,
size_bytes: Option<u64>,
modified_ms: Option<u64>,
+ device_id: String,
+ file_id: String,
}
#[derive(Clone, Copy, Debug)]
@@ -89,6 +92,13 @@ pub struct NativeIntent {
display_label: String,
}
+#[derive(Clone, Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NativeDocumentFolderSelection {
+ token: String,
+ display_name: String,
+}
+
#[derive(Default)]
struct NativeIntakeInner {
tokens: HashMap<String, NativePathEntry>,
@@ -203,6 +213,34 @@ impl NativeIntakeState {
Ok(entry.to_ref())
}
+ fn sign_document_folder_path(
+ &self,
+ path: impl AsRef<Path>,
+ ) -> Result<NativeDocumentFolderSelection, String> {
+ let classified = classify_native_document_folder(path.as_ref())?;
+ let token = random_token("path_");
+ let lease = sign_path_lease(
+ &self.lease_secret,
+ NativePathLeaseRequest {
+ operation: NativePathOperation::LinkDocuments,
+ canonical_path: portable_path_string(&classified.canonical_path),
+ path_kind: classified.path_kind,
+ path_type: classified.path_type,
+ source_kind: NativePathSourceKind::Dialog,
+ token,
+ display_label: classified.display_label,
+ size_bytes: classified.size_bytes,
+ modified_ms: None,
+ device_id: Some(classified.device_id),
+ file_id: Some(classified.file_id),
+ },
+ )?;
+ Ok(NativeDocumentFolderSelection {
+ token: lease.native_path_lease,
+ display_name: lease.display_label,
+ })
+ }
+
fn register_classified_path(
&self,
classified: ClassifiedPath,
@@ -239,6 +277,8 @@ impl NativeIntakeState {
expires_at_ms,
size_bytes: classified.size_bytes,
modified_ms: classified.modified_ms,
+ device_id: classified.device_id,
+ file_id: classified.file_id,
};
let mut inner = self.inner.lock().map_err(|e| e.to_string())?;
inner.tokens.insert(token, entry.clone());
@@ -287,6 +327,8 @@ impl NativeIntakeState {
display_label: entry.display_label,
size_bytes: entry.size_bytes,
modified_ms: entry.modified_ms,
+ device_id: Some(entry.device_id),
+ file_id: Some(entry.file_id),
},
)
}
@@ -326,6 +368,8 @@ fn validate_entry_path(
|| !classified.allowed_operations.contains(&operation)
|| (check_fingerprint && classified.size_bytes != entry.size_bytes)
|| (check_fingerprint && classified.modified_ms != entry.modified_ms)
+ || (check_fingerprint && classified.device_id != entry.device_id)
+ || (check_fingerprint && classified.file_id != entry.file_id)
{
return Err("Native path changed after it was selected.".to_string());
}
@@ -455,6 +499,29 @@ pub async fn pick_hugging_face_cache_dir(
Ok(Some(portable_path_string(&canonical)))
}
+#[tauri::command]
+pub async fn pick_native_document_folder(
+ window: WebviewWindow,
+ app: AppHandle,
+ state: tauri::State<'_, NativeIntakeState>,
+) -> Result<Option<NativeDocumentFolderSelection>, String> {
+ ensure_main_window(&window)?;
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ app.dialog()
+ .file()
+ .set_title("Link a document folder")
+ .pick_folder(move |path| {
+ let _ = tx.send(path);
+ });
+ let Some(folder_path) = rx.await.map_err(|_| "Dialog closed".to_string())? else {
+ return Ok(None);
+ };
+ let path = folder_path
+ .into_path()
+ .map_err(|_| "Only local filesystem folders are supported.".to_string())?;
+ state.sign_document_folder_path(path).map(Some)
+}
+
#[tauri::command]
pub fn consume_native_path_token(
window: WebviewWindow,
@@ -666,6 +733,7 @@ pub async fn read_native_attachment_file(
#[cfg(test)]
mod tests {
use super::*;
+ use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use std::fs;
use std::time::{SystemTime, UNIX_EPOCH};
@@ -909,6 +977,38 @@ mod tests {
);
}
+ #[test]
+ fn document_folder_picker_grant_is_not_a_reusable_path_token() {
+ let state = new_native_intake_state();
+ let path = temp_path("document-folder");
+ fs::create_dir(&path).unwrap();
+
+ let lease = state.sign_document_folder_path(&path).unwrap();
+ assert!(lease.token.contains('.'));
+ let payload = lease.token.split('.').next().unwrap();
+ let payload: serde_json::Value =
+ serde_json::from_slice(&URL_SAFE_NO_PAD.decode(payload).unwrap()).unwrap();
+ assert!(payload["modified_ms"].is_null());
+ assert!(payload["device_id"]
+ .as_str()
+ .is_some_and(|value| !value.is_empty()));
+ assert!(payload["file_id"]
+ .as_str()
+ .is_some_and(|value| !value.is_empty()));
+ assert_eq!(
+ lease.display_name,
+ path.file_name().unwrap().to_string_lossy()
+ );
+ let response = serde_json::to_value(&lease).unwrap();
+ assert_eq!(response["token"], lease.token);
+ assert_eq!(response["displayName"], lease.display_name);
+ assert!(response.get("path").is_none());
+ assert!(state
+ .entry_for_operation("path_token", NativePathOperation::LinkDocuments)
+ .is_err());
+ let _ = fs::remove_dir(path);
+ }
+
#[cfg(unix)]
#[test]
fn reveal_rejects_symlink_replacement() {
diff --git a/studio/src-tauri/src/native_path_policy.rs b/studio/src-tauri/src/native_path_policy.rs
index 9d1809ebad5..1d10aef1360 100644
--- a/studio/src-tauri/src/native_path_policy.rs
+++ b/studio/src-tauri/src/native_path_policy.rs
@@ -23,6 +23,8 @@ pub struct ClassifiedPath {
pub display_label: String,
pub size_bytes: Option<u64>,
pub modified_ms: Option<u64>,
+ pub device_id: String,
+ pub file_id: String,
}
pub fn classify_native_model_path(path: &Path) -> Result<ClassifiedPath, String> {
@@ -84,6 +86,20 @@ pub fn classify_native_attachment_path(path: &Path) -> Result<ClassifiedPath, St
})
}
+pub fn classify_native_document_folder(path: &Path) -> Result<ClassifiedPath, String> {
+ let classified = classify_existing_path(path)?;
+ if classified.path_type != NativePathType::Directory {
+ return Err("Only folders can be linked as document sources.".to_string());
+ }
+ reject_document_folder_root(&classified.canonical_path)?;
+ reject_sensitive_document_folder(&classified.canonical_path)?;
+ Ok(ClassifiedPath {
+ path_kind: NativePathKind::DocumentFolder,
+ allowed_operations: vec![NativePathOperation::LinkDocuments],
+ ..classified
+ })
+}
+
pub fn classify_native_dataset_path(path: &Path) -> Result<ClassifiedPath, String> {
let classified = classify_existing_path(path)?;
if classified.path_type != NativePathType::File {
@@ -152,6 +168,73 @@ pub fn refresh_path_fingerprint(
Ok((path_type, size_bytes, modified_ms))
}
+#[cfg(unix)]
+fn stable_path_identity(path: &Path) -> Result<(String, String), String> {
+ use std::os::unix::fs::MetadataExt;
+
+ let metadata = fs::metadata(path).map_err(|e| format!("Path is no longer available: {e}"))?;
+ Ok((
+ format!("{:x}", metadata.dev()),
+ format!("{:x}", metadata.ino()),
+ ))
+}
+
+#[cfg(windows)]
+fn stable_path_identity(path: &Path) -> Result<(String, String), String> {
+ use std::mem::zeroed;
+ use std::os::windows::fs::OpenOptionsExt;
+ use std::os::windows::io::AsRawHandle;
+ use windows_sys::Win32::Storage::FileSystem::{
+ FileIdInfo, GetFileInformationByHandle, GetFileInformationByHandleEx,
+ BY_HANDLE_FILE_INFORMATION, FILE_ID_INFO,
+ };
+
+ const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;
+ const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
+ const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
+ let file = fs::OpenOptions::new()
+ .read(true)
+ .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
+ .open(path)
+ .map_err(|e| format!("Path is no longer available: {e}"))?;
+ let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { zeroed() };
+ let ok = unsafe {
+ GetFileInformationByHandle(file.as_raw_handle() as _, std::ptr::addr_of_mut!(info))
+ };
+ if ok == 0 || info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
+ return Err("Path is no longer available.".to_string());
+ }
+ let legacy_device_id = info.dwVolumeSerialNumber as u64;
+ let legacy_file_id = ((info.nFileIndexHigh as u64) << 32) | info.nFileIndexLow as u64;
+ let mut identity: FILE_ID_INFO = unsafe { zeroed() };
+ let extended_ok = unsafe {
+ GetFileInformationByHandleEx(
+ file.as_raw_handle() as _,
+ FileIdInfo,
+ std::ptr::addr_of_mut!(identity).cast(),
+ std::mem::size_of::<FILE_ID_INFO>() as u32,
+ )
+ };
+ if extended_ok != 0 {
+ let file_id = u128::from_le_bytes(identity.FileId.Identifier);
+ if identity.VolumeSerialNumber == legacy_device_id && file_id == legacy_file_id as u128 {
+ return Ok((
+ format!("{legacy_device_id:x}"),
+ format!("{legacy_file_id:x}"),
+ ));
+ }
+ // Python <=3.11 exposes the legacy pair; Python >=3.12 exposes FILE_ID_INFO.
+ return Ok((
+ format!("{legacy_device_id:x}:{:x}", identity.VolumeSerialNumber),
+ format!("{legacy_file_id:x}:{file_id:x}"),
+ ));
+ }
+ Ok((
+ format!("{legacy_device_id:x}"),
+ format!("{legacy_file_id:x}"),
+ ))
+}
+
pub fn reveal_target(path: &Path) -> PathBuf {
if path.is_dir() {
path.to_path_buf()
@@ -204,6 +287,7 @@ fn classify_existing_path(path: &Path) -> Result<ClassifiedPath, String> {
return Err("Symlink paths are not supported for native intake.".to_string());
}
let (path_type, size_bytes, modified_ms) = refresh_path_fingerprint(&canonical_path)?;
+ let (device_id, file_id) = stable_path_identity(&canonical_path)?;
let display_label = sanitize_display_label(
canonical_path
.file_name()
@@ -219,6 +303,8 @@ fn classify_existing_path(path: &Path) -> Result<ClassifiedPath, String> {
display_label,
size_bytes,
modified_ms,
+ device_id,
+ file_id,
})
}
@@ -270,6 +356,156 @@ fn reject_sensitive_artifact(path: &Path) -> Result<(), String> {
Ok(())
}
+fn reject_document_folder_root(path: &Path) -> Result<(), String> {
+ if path.parent().is_none() {
+ Err("A filesystem root cannot be linked as a document folder.".to_string())
+ } else {
+ Ok(())
+ }
+}
+
+fn reject_sensitive_document_folder(path: &Path) -> Result<(), String> {
+ let has_sensitive_segment = path.components().any(|component| {
+ matches!(
+ component
+ .as_os_str()
+ .to_string_lossy()
+ .to_ascii_lowercase()
+ .as_str(),
+ ".1password"
+ | ".aws"
+ | ".azure"
+ | ".bitwarden"
+ | ".config"
+ | ".docker"
+ | ".gcloud"
+ | ".gnupg"
+ | ".huggingface"
+ | ".kaggle"
+ | ".kube"
+ | ".local"
+ | ".modelscope"
+ | ".mozilla"
+ | ".ngc"
+ | ".password-store"
+ | ".pki"
+ | ".ssh"
+ | ".thunderbird"
+ | "1password"
+ | "bitwarden"
+ | "keychains"
+ | "keyrings"
+ | "mozilla"
+ | "thunderbird"
+ )
+ });
+ if has_sensitive_segment {
+ return Err(
+ "Sensitive system or application folders cannot be linked as document sources."
+ .to_string(),
+ );
+ }
+
+ let mut sensitive_roots = Vec::new();
+ if let Some(home) = dirs::home_dir() {
+ if same_native_path(path, &home) {
+ return Err(
+ "The entire home folder cannot be linked as a document source.".to_string(),
+ );
+ }
+ for relative in [".unsloth"] {
+ sensitive_roots.push(home.join(relative));
+ }
+ }
+ if let Some(config) = dirs::config_dir() {
+ sensitive_roots.push(config);
+ }
+ if let Some(data) = dirs::data_local_dir() {
+ sensitive_roots.push(data);
+ }
+
+ #[cfg(unix)]
+ sensitive_roots.extend(
+ [
+ "/boot", "/etc", "/root", "/run", "/usr", "/var/lib", "/var/run",
+ ]
+ .into_iter()
+ .map(PathBuf::from),
+ );
+ #[cfg(target_os = "macos")]
+ sensitive_roots.extend(
+ ["/Library", "/System", "/private"]
+ .into_iter()
+ .map(PathBuf::from),
+ );
+ #[cfg(windows)]
+ for variable in ["WINDIR", "ProgramFiles", "ProgramFiles(x86)", "ProgramData"] {
+ if let Some(value) = std::env::var_os(variable) {
+ sensitive_roots.push(PathBuf::from(value));
+ }
+ }
+
+ if sensitive_roots.iter().any(|sensitive| {
+ same_path_or_descendant(path, sensitive)
+ && !(is_linux_removable_media_path(path)
+ && same_native_path(sensitive, Path::new("/run")))
+ }) {
+ Err(
+ "Sensitive system or application folders cannot be linked as document sources."
+ .to_string(),
+ )
+ } else {
+ Ok(())
+ }
+}
+
+#[cfg(target_os = "linux")]
+fn is_linux_removable_media_path(path: &Path) -> bool {
+ let media_root = Path::new("/run/media");
+ path != media_root && path.starts_with(media_root)
+}
+
+#[cfg(not(target_os = "linux"))]
+fn is_linux_removable_media_path(_path: &Path) -> bool {
+ false
+}
+
+fn same_native_path(left: &Path, right: &Path) -> bool {
+ #[cfg(windows)]
+ {
+ return left
+ .to_string_lossy()
+ .replace('/', "\\")
+ .eq_ignore_ascii_case(&right.to_string_lossy().replace('/', "\\"));
+ }
+ #[cfg(not(windows))]
+ {
+ left == right
+ }
+}
+
+fn same_path_or_descendant(path: &Path, root: &Path) -> bool {
+ #[cfg(windows)]
+ {
+ let path = path
+ .to_string_lossy()
+ .replace('/', "\\")
+ .to_ascii_lowercase();
+ let root = root
+ .to_string_lossy()
+ .replace('/', "\\")
+ .to_ascii_lowercase();
+ return path == root
+ || path
+ .strip_prefix(&root)
+ .is_some_and(|rest| rest.starts_with('\\'));
+ }
+ #[cfg(not(windows))]
+ {
+ path == root || path.starts_with(root)
+ }
+}
+
fn reject_network_or_device_path(path: &Path) -> Result<(), String> {
let text = path.to_string_lossy();
#[cfg(windows)]
@@ -403,6 +639,72 @@ mod tests {
}
}
+ #[test]
+ fn document_folder_is_directory_with_link_only_capability() {
+ let path = temp_path("documents");
+ fs::create_dir(&path).unwrap();
+ let classified = classify_native_document_folder(&path).unwrap();
+ assert_eq!(classified.path_kind, NativePathKind::DocumentFolder);
+ assert_eq!(classified.path_type, NativePathType::Directory);
+ assert_eq!(
+ classified.allowed_operations,
+ vec![NativePathOperation::LinkDocuments]
+ );
+ let _ = fs::remove_dir(path);
+ }
+
+ #[test]
+ fn document_folder_rejects_files_and_filesystem_root() {
+ let file = temp_path("documents-file");
+ fs::write(&file, b"not a folder").unwrap();
+ assert!(classify_native_document_folder(&file).is_err());
+ assert!(classify_native_document_folder(Path::new(std::path::MAIN_SEPARATOR_STR)).is_err());
+ let _ = fs::remove_file(file);
+ }
+
+ #[test]
+ fn document_folder_policy_allows_normal_home_subfolders_but_not_credentials() {
+ let Some(home) = dirs::home_dir() else { return };
+ assert!(reject_sensitive_document_folder(&home.join("Documents")).is_ok());
+ assert!(reject_sensitive_document_folder(&home.join(".ssh")).is_err());
+ assert!(reject_sensitive_document_folder(&home.join(".huggingface")).is_err());
+ assert!(reject_sensitive_document_folder(&home.join("work").join(".local")).is_err());
+ assert!(reject_sensitive_document_folder(&home.join("work").join("keyrings")).is_err());
+ assert!(reject_sensitive_document_folder(&home.join(".unsloth").join("studio")).is_err());
+ }
+
+ #[cfg(target_os = "linux")]
+ #[test]
+ fn document_folder_policy_allows_linux_removable_media_under_run() {
+ assert!(
+ reject_sensitive_document_folder(Path::new("/run/media/user/USB/Documents")).is_ok()
+ );
+ assert!(reject_sensitive_document_folder(Path::new("/run/media")).is_err());
+ assert!(reject_sensitive_document_folder(Path::new("/run/secrets")).is_err());
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn windows_unc_is_rejected_but_mapped_drive_spelling_is_allowed() {
+ assert!(reject_network_or_device_path(Path::new(r"\\server\share\documents")).is_err());
+ assert!(reject_network_or_device_path(Path::new(r"Z:\documents")).is_ok());
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn document_folder_rejects_symlinks_and_sensitive_directories() {
+ use std::os::unix::fs::symlink;
+
+ let target = temp_path("documents-target");
+ let link = temp_path("documents-link");
+ fs::create_dir(&target).unwrap();
+ symlink(&target, &link).unwrap();
+ assert!(classify_native_document_folder(&link).is_err());
+ assert!(classify_native_document_folder(Path::new("/etc")).is_err());
+ let _ = fs::remove_file(link);
+ let _ = fs::remove_dir(target);
+ }
+
#[test]
fn training_dataset_allows_import_and_reveal_only() {
let path = temp_path("dataset").with_extension("jsonl");