Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: stop a linked folder re-indexing failed files forever and let Unlink stop a running sync (#13145)
Indrajit swainc0e869b1f497
diff --git a/studio/backend/core/rag/folder_sync.py b/studio/backend/core/rag/folder_sync.pyindex f50b0d08982..da4db383569 100644--- a/studio/backend/core/rag/folder_sync.py+++ b/studio/backend/core/rag/folder_sync.py@@ -48,11 +48,17 @@ _last_job_account: str | None = None_folder_locks: weakref.WeakValueDictionary[str, threading.RLock] = weakref.WeakValueDictionary()_scope_locks: weakref.WeakValueDictionary[str, threading.RLock] = weakref.WeakValueDictionary()_named_locks_lock = threading.Lock()+# Folders being unlinked, read by the worker without rag.db: an ingest can hold the writer past the+# default 5 s busy_timeout, so the retire write alone could not stop it (#13095).+_folder_cancels: set = set()+_folder_cancels_lock = threading.Lock()+_UNLINK_BUSY_TIMEOUT_MS = 30_000_retirement_schema_lock = threading.Lock()_TERMINAL = {"completed", "failed"}_MAX_FOLDER_DEPTH = 64_MAX_NAMED_FAILURES = 3_MAX_WITHHELD_PATHS = 500+_FAILED_RETRY_S = 6 * 3600_JOB_EVENT_KEEPALIVE_S = 4.0_SQLITE_INTEGER_MAX = (1 << 63) - 1# Dependency, VCS and cache trees would flood the index with third-party source.@@ -96,6 +102,10 @@ class _SyncStopped(Exception):pass+class _SyncCancelled(Exception):+ pass++class _LeaseLost(Exception):pass@@ -120,6 +130,23 @@ class _PendingIngestion:future: Future["_IngestionResult"]+def request_cancel(folder_id: str) -> None:+ with _folder_cancels_lock:+ _folder_cancels.add(account_key(folder_id))+++def clear_cancel(folder_id: str) -> None:+ with _folder_cancels_lock:+ _folder_cancels.discard(account_key(folder_id))+++def is_cancel_requested(folder_id: str | None) -> bool:+ if folder_id is None:+ return False+ with _folder_cancels_lock:+ return account_key(folder_id) in _folder_cancels++def _folder_lock(folder_id: str) -> threading.RLock:with _named_locks_lock:return _folder_locks.setdefault(account_key(folder_id), threading.RLock())@@ -505,6 +532,7 @@ 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(f"PRAGMA busy_timeout = {_UNLINK_BUSY_TIMEOUT_MS}")conn.execute("BEGIN IMMEDIATE")folder = conn.execute("SELECT delete_remove_index FROM linked_folders "@@ -568,32 +596,40 @@ def _reconcile_retired_folder_deletions() -> None:def delete_folder(folder_id: str, *, remove_index: bool = True) -> bool:- conn = rag_db.get_connection()+ request_cancel(folder_id)try:- conn.execute("BEGIN IMMEDIATE")- if conn.execute("SELECT 1 FROM linked_folders WHERE id=?", (folder_id,)).fetchone() is None:+ conn = rag_db.get_connection()+ try:+ conn.execute(f"PRAGMA busy_timeout = {_UNLINK_BUSY_TIMEOUT_MS}")+ 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()- 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+ raise+ finally:+ conn.close()+ while _delete_retired_folder(folder_id) is False:+ time.sleep(0.05)+ return Truefinally:- conn.close()- while _delete_retired_folder(folder_id) is False:- time.sleep(0.05)- return True+ clear_cancel(folder_id)def _retirement_connection():@@ -951,6 +987,7 @@ def _request_sync(folder_id: str, *, rebuild: bool = False) -> str:or folder["delete_remove_index"] is not None):raise KeyError(folder_id)+ conn.execute("UPDATE linked_folders SET failed_files=NULL WHERE id=?", (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",@@ -1178,6 +1215,8 @@ def _check_running() -> None:stop_event = getattr(_worker_state, "stop_event", _stop)if stop_event.is_set():raise _SyncStopped+ if is_cancel_requested(getattr(_worker_state, "folder_id", None)):+ raise _SyncCancelledjob_id = getattr(_worker_state, "job_id", None)if job_id is None:return@@ -1402,6 +1441,28 @@ def _store_withheld(folder_id: str, withheld: set[str]) -> None:conn.commit()+def _failure_signature(metadata: dict) -> list:+ return [metadata["size_bytes"], metadata["mtime_ns"], *_file_identity(metadata)]+++def _load_failed(folder: dict) -> dict[str, dict]:+ """Files whose ingestion failed recently, as {relative path: {"sig": [...], "at": epoch}}."""+ try:+ stored = json.loads(folder.get("failed_files") or "{}")+ except ValueError:+ return {}+ if not isinstance(stored, dict):+ return {}+ cutoff = time.time() - _FAILED_RETRY_S+ return {+ rel: entry+ for rel, entry in stored.items()+ if isinstance(entry, dict)+ and isinstance(entry.get("at"), (int, float))+ and entry["at"] > cutoff+ }++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:@@ -1426,6 +1487,7 @@ def _ingest_folder_document("""Ingest one file in a pool thread; the coordinator owns all folder state."""# Thread-local, so copy the coordinator's lease and stop state for _check_running._worker_state.job_id = job_id+ _worker_state.folder_id = folder["id"]_worker_state.stop_event = stop_eventdocument_id = Noneingestion_job = None@@ -1454,6 +1516,9 @@ def _ingest_folder_document(_check_running()return _IngestionResult(document_id, ingestion_job)except Exception as exc: # noqa: BLE001 - the coordinator classifies it+ if is_cancel_requested(folder["id"]):+ # The unlink cut the ingest short; that is not a file failure.+ return _IngestionResult(document_id, ingestion_job, _SyncCancelled())return _IngestionResult(document_id, ingestion_job, exc)@@ -1503,7 +1568,7 @@ def _reconcile_folder(job_id: str) -> None:expected_identity = _load_identity(folder["root_device"], folder["root_inode"])current, scanned_identity = _scan(folder["path"], expected_identity)_check_running()- except (_SyncStopped, _LeaseLost):+ except (_SyncStopped, _SyncCancelled, _LeaseLost):raiseexcept Exception as exc:# A partial/unavailable scan is never authoritative for deletion.@@ -1547,6 +1612,11 @@ def _reconcile_folder(job_id: str) -> None:key = (content_hash, os.path.splitext(rel)[1].lower())missing_by_content.setdefault(key, []).append(rel)already_withheld = _load_withheld(folder)+ # An unchanged file whose ingestion failed fails again: retrying it every periodic sync kept a+ # folder of scanned PDFs indexing forever (#13095). Sync changes and Rebuild retry at once.+ known_failed = {} if rebuild else _load_failed(folder)+ ingest_failed: dict[str, dict] = {}+ cached_grace = Falsetotal = len(work) + len(missing)_set_job(job_id, stage = "ingesting", discovered = len(current), renamed = renamed)added = changed_count = 0@@ -1590,10 +1660,16 @@ def _reconcile_folder(job_id: str) -> None:result = _IngestionResult(error = exc)if result.error is not None:- if isinstance(result.error, (_SyncStopped, _LeaseLost, _FolderChanged)):+ if isinstance(+ result.error, (_SyncStopped, _SyncCancelled, _LeaseLost, _FolderChanged)+ ):_cleanup_pending_ingestion(pending, result)raise result.errorfailures.append(pending.relative_path)+ ingest_failed[pending.relative_path] = {+ "sig": _failure_signature(pending.metadata),+ "at": time.time(),+ }# A failed file may be a rename or copy of a vanished path, so grant one pass.withheld.update(missing - already_withheld)logger.warning(@@ -1613,7 +1689,7 @@ def _reconcile_folder(job_id: str) -> None:result.document_id,pending.content_hash,)- except (_SyncStopped, _LeaseLost, _FolderChanged):+ except (_SyncStopped, _SyncCancelled, _LeaseLost, _FolderChanged):_cleanup_pending_ingestion(pending, result)raiseexcept Exception as exc: # noqa: BLE001@@ -1672,6 +1748,18 @@ def _reconcile_folder(job_id: str) -> None:) as executor:try:for rel in work:+ if known_failed.get(rel, {}).get("sig") == _failure_signature(current[rel]):+ # No per-file write: a folder can hold thousands of these.+ if is_cancel_requested(folder["id"]):+ raise _SyncCancelled+ failures.append(rel)+ ingest_failed[rel] = known_failed[rel]+ if not cached_grace:+ # missing only shrinks during the pass, so once covers every later failure+ withheld.update(missing - already_withheld)+ cached_grace = True+ processed += 1+ continueif len(in_flight) >= workers:drain_one()snapshot = None@@ -1730,7 +1818,7 @@ def _reconcile_folder(job_id: str) -> None:future = future,)snapshot = None- except (_SyncStopped, _LeaseLost, _FolderChanged):+ except (_SyncStopped, _SyncCancelled, _LeaseLost, _FolderChanged):_remove_snapshot(snapshot)raiseexcept Exception:@@ -1742,6 +1830,7 @@ def _reconcile_folder(job_id: str) -> None:continueprocessed += 1update_progress()+ update_progress()while in_flight:drain_one()except Exception:@@ -1765,6 +1854,16 @@ def _reconcile_folder(job_id: str) -> None:_check_running()_store_withheld(folder["id"], withheld)+ with closing(rag_db.get_connection()) as conn:+ # Written while the job is still active, so a later Sync changes clears it in _request_sync and+ # one queued behind this run (successor_kind) finds nothing to skip.+ conn.execute(+ "UPDATE linked_folders SET failed_files=CASE WHEN EXISTS(SELECT 1 FROM "+ "linked_folder_sync_jobs WHERE id=? AND successor_kind IS NOT NULL) THEN NULL ELSE ? END "+ "WHERE id=?",+ (job_id, json.dumps(ingest_failed) if ingest_failed else None, folder["id"]),+ )+ conn.commit()error = _failure_summary(failures)_set_job(job_id,@@ -1813,6 +1912,28 @@ def _pause_job(job_id: str) -> None:conn.commit()+def _stop_job(job_id: str) -> None:+ """End a job an unlink cancelled; terminal, so the queue does not reclaim it before the unlink lands."""+ job = get_job(job_id)+ if job is None or job["status"] not in ("pending", "running"):+ return+ _set_job(+ job_id,+ status = "failed",+ stage = "error",+ error = "Indexing was stopped",+ completed_at = _now(),+ )+ with closing(rag_db.get_connection()) as conn:+ conn.execute(+ "UPDATE linked_folders SET status='ready', last_error=NULL, updated_at=? "+ "WHERE id=? AND delete_remove_index IS NULL",+ (_now(), job["folder_id"]),+ )+ conn.commit()+ _prune_terminal_jobs(conn)++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()@@ -1853,17 +1974,25 @@ def _queue_successor(job_id: str) -> None: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:+ claimed = _claim_job(job_id)+ if claimed is None:# Drop an already-activated claim 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+ _, folder_id = claimedlease_lost = False+ cancelled = False_worker_state.job_id = job_id+ _worker_state.folder_id = folder_idtry:_reconcile_folder(job_id)except _LeaseLost:lease_lost = True+ except _SyncCancelled:+ cancelled = True+ if not account_is_retired():+ _stop_job(job_id)except _SyncStopped:# A retired account's database is closed; its rows moved with the roots.if not account_is_retired():@@ -1874,10 +2003,11 @@ def reconcile_folder(job_id: str) -> None:_fail_job(job_id, exc)finally:try:- if not lease_lost and not account_is_retired():+ if not lease_lost and not cancelled and not account_is_retired():_queue_successor(job_id)finally:del _worker_state.job_id+ del _worker_state.folder_idjob_leases.release(job_leases.FOLDER_SYNC, job_id)diff --git a/studio/backend/core/rag/ingestion.py b/studio/backend/core/rag/ingestion.pyindex bc71b0ed681..67bbbce4d17 100644--- a/studio/backend/core/rag/ingestion.py+++ b/studio/backend/core/rag/ingestion.py@@ -118,6 +118,13 @@ def _set_job(def _progress(conn, job_id: str, stage: str, progress: float) -> None:if account_is_retired():raise job_leases.JobLeaseLost("Account is retired")+ # An unlink stops a linked-folder document mid-embed, not after it (folder_sync imports this module).+ from . import folder_sync++ if folder_sync.is_cancel_requested(getattr(folder_sync._worker_state, "folder_id", None)):+ # Terminal, so the folder cleanup can prune the row with the document it discards.+ _set_job(conn, job_id, status = "failed", stage = "error", error = "Linked folder was removed")+ raise job_leases.JobLeaseLost("Linked folder was removed")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)diff --git a/studio/backend/storage/rag_db.py b/studio/backend/storage/rag_db.pyindex 7c7cdb9558a..5cf14d40735 100644--- a/studio/backend/storage/rag_db.py+++ b/studio/backend/storage/rag_db.py@@ -171,6 +171,7 @@ def _ensure_schema(conn: sqlite3.Connection) -> None:last_error TEXT,last_scan_at TEXT,withheld_paths TEXT,+ failed_files TEXT,created_at TEXT NOT NULL,updated_at TEXT NOT NULL,UNIQUE(scope, path)@@ -284,6 +285,8 @@ def ensure_linked_folder_columns(conn: sqlite3.Connection) -> None: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")+ if folder_cols and "failed_files" not in folder_cols:+ conn.execute("ALTER TABLE linked_folders ADD COLUMN failed_files TEXT")def reset_schema_state_for_tests() -> None:diff --git a/studio/backend/tests/test_rag_linked_folders.py b/studio/backend/tests/test_rag_linked_folders.pyindex bf8fad6df5e..8240c2d7390 100644--- a/studio/backend/tests/test_rag_linked_folders.py+++ b/studio/backend/tests/test_rag_linked_folders.py@@ -18,7 +18,7 @@ from types import SimpleNamespaceimport pytest-from core.rag import folder_sync, store+from core.rag import embeddings, folder_sync, ingestion, storefrom storage import rag_dbfrom utils.paths import rag_db_path@@ -3243,3 +3243,96 @@ def test_a_vec_table_resized_after_the_prefetch_falls_back_to_a_normal_ingest((folder["id"],),).fetchone()["document_id"]assert _vectors(b_id)+++@requires_sqlite_vec+def test_unlink_stops_the_document_being_embedded(rag_home, stub_embeddings, monkeypatch):+ """Unlink must not wait for a long embed to finish, then die on a 5 s busy_timeout (#13095)."""+ source, folder = _folder(rag_home)+ (source / "big.txt").write_text(" ".join(f"word{i}" for i in range(200_000)), encoding = "utf-8")+ embedding = threading.Event()+ real_encode = embeddings.encode++ def slow_gpu(texts, **kwargs):+ embedding.set()+ time.sleep(0.25)+ return real_encode(texts, **kwargs)++ monkeypatch.setattr(embeddings, "encode", slow_gpu)+ monkeypatch.setattr(ingestion, "_EMBED_BATCH", 4)+ job_id = folder_sync.request_sync(folder["id"])+ worker = threading.Thread(target = folder_sync.reconcile_folder, args = (job_id,), daemon = True)+ worker.start()+ assert embedding.wait(30), "the document never reached embedding"+ started = time.monotonic()+ assert folder_sync.delete_folder(folder["id"], remove_index = False) is True+ elapsed = time.monotonic() - started+ worker.join(timeout = 60)+ assert not worker.is_alive()+ # The whole document takes ~30 s of embedding here.+ assert elapsed < 8, f"unlink waited {elapsed:.1f}s for the embed"+ assert folder_sync.get_folder(folder["id"]) is None+ assert _row("SELECT 1 FROM ingestion_jobs WHERE status NOT IN ('completed','failed')") is None+++@requires_sqlite_vec+def test_periodic_sync_does_not_retry_an_unchanged_failed_file(+ rag_home, stub_embeddings, monkeypatch+):+ """A file that cannot be indexed is retried when it changes or on Sync, not every period (#13095)."""+ source, folder = _folder(rag_home)+ (source / "good.txt").write_text("words to index", encoding = "utf-8")+ bad = source / "bad.txt"+ bad.write_text(" ", encoding = "utf-8")+ attempts = []+ real_start = ingestion.start_ingestion++ def counting(*args, **kwargs):+ attempts.append(kwargs["linked_relative_path"])+ return real_start(*args, **kwargs)++ monkeypatch.setattr(ingestion, "start_ingestion", counting)++ def periodic() -> dict:+ folder_sync._enqueue_periodic()+ job_id = _row(+ "SELECT id FROM linked_folder_sync_jobs WHERE folder_id=? AND status='pending'",+ (folder["id"],),+ )["id"]+ folder_sync.reconcile_folder(job_id)+ return folder_sync.get_job(job_id)++ first = folder_sync.request_sync(folder["id"])+ folder_sync.reconcile_folder(first)+ assert attempts.count("bad.txt") == 1+ assert "bad.txt" in folder_sync.get_job(first)["error"]++ job = periodic()+ assert attempts.count("bad.txt") == 1+ assert job["status"] == "failed" and "bad.txt" in job["error"] and job["failed"] == 1+ assert folder_sync.get_folder(folder["id"])["status"] == "error"++ bad.write_text(" \n\n", encoding = "utf-8")+ periodic()+ assert attempts.count("bad.txt") == 2++ manual = folder_sync.request_sync(folder["id"])+ folder_sync.reconcile_folder(manual)+ assert attempts.count("bad.txt") == 3++ monkeypatch.setattr(folder_sync, "_FAILED_RETRY_S", 0)+ periodic()+ assert attempts.count("bad.txt") == 4+ assert attempts.count("good.txt") == 1+++def test_an_unlink_cancel_only_reaches_its_own_account():+ from utils.account_context import AccountContext, run_as++ other = AccountContext("account-b", "b")+ folder_sync.request_cancel("shared-id")+ try:+ assert folder_sync.is_cancel_requested("shared-id")+ assert not run_as(other, folder_sync.is_cancel_requested, "shared-id")+ finally:+ folder_sync.clear_cancel("shared-id")