~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
"""
Library RAG Service
Handles indexing and searching library documents using RAG:
- Index text documents into vector database
- Chunk documents for semantic search
- Generate embeddings using local models
- Manage FAISS indices per research
- Track RAG status in library
"""
import threading
import time
import json
import re
from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime, UTC
import numpy as np
from pathlib import Path
from typing import (
Any,
Callable,
Dict,
List,
Literal,
Optional,
Set,
Tuple,
Union,
)
from concurrent.futures import ThreadPoolExecutor, as_completed, CancelledError
from langchain_core.documents import Document as LangchainDocument
from loguru import logger
from sqlalchemy import exists, func
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session
from ...config.paths import get_cache_directory
from ...constants import (
DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,
DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,
DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC,
DEFAULT_LOCAL_SEARCH_INDEX_TYPE,
DEFAULT_LOCAL_SEARCH_MODEL,
DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,
DEFAULT_LOCAL_SEARCH_PROVIDER,
DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE,
DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS,
)
from ...database.models.library import (
Document,
DocumentChunk,
DocumentCollection,
Collection,
RAGIndex,
RAGIndexStatus,
RagDocumentStatus,
EmbeddingProvider,
)
from ...database.session_context import get_user_db_session, safe_rollback
from ...database.thread_local_session import thread_session_manager
from ...utilities.type_utils import to_bool
from ..utils import ensure_in_collection
from ...embeddings.splitters import get_text_splitter
from ...web_search_engines.engines.local_embedding_manager import (
LocalEmbeddingManager,
)
from ...security.directory_creation import create_directory
from ...security.file_integrity import FileIntegrityManager, FAISSIndexVerifier
from ...security.file_integrity.integrity_manager import NO_INTEGRITY_RECORD
from ...vector_stores.base import VectorStoreIntegrityError
from ...vector_stores.facade import VectorIndex, ChunkInput, SearchResult
from .collection_rebuild import (
CollectionRebuild,
RebuildCancelled,
collection_configuration,
document_fingerprint,
)
from langchain_core.embeddings import Embeddings
import hashlib
def _claim_document_snapshot(session, document_id, text_content, document_hash):
"""Keep the validated SQLite snapshot stable until the index commit.
SELECT FOR UPDATE is ignored by SQLite. A conditional no-op write either
detects a writer that already won or holds the write lock through chunk
and status persistence. Call after vector initialization, which may commit
index setup, and never before embedding.
"""
return (
session.query(Document)
.filter(
Document.id == document_id,
Document.text_content == text_content,
Document.document_hash == document_hash,
)
.update({Document.id: document_id}, synchronize_session=False)
)
@dataclass
class _PreparedDocument:
document_id: str
collection_id: str
chunk_inputs: List[ChunkInput]
vectors: np.ndarray
source_fingerprint: str | None = None
collection_configuration: str | None = None
content_hash: Optional[str] = None
initial_indexed: Optional[bool] = None
status_exists: Optional[bool] = None
# The RAGIndex identity ``status_exists`` was measured against — the
# row selected by ``_resolve_index_for_config`` at prepare time. The
# write-side staleness re-check must measure its status-row query
# against this same identity (see ``_status_row_exists``); deriving it
# from ``self.rag_index_record`` there breaks the paired predicate.
# None means no index matching this service's configuration existed at
# prepare time.
status_index_id: Optional[int] = None
# True iff a DocumentCollection row existed at prepare time. False
# means first-time ingest: Phase 3 may create the link. Distinguishes
# that from a concurrent unlink of a row that was present then.
had_collection_link: Optional[bool] = None
# Texts per embed_documents() call while a cancellation scope is armed.
# Embeddings are per-text independent, so splitting changes nothing but
# adds cancel points between batches. Without a scope the single call
# below is kept exactly as today (zero behavior change for background /
# sequential paths that cannot be cancelled).
_EMBEDDING_CANCEL_BATCH_SIZE = 32
def _indexing_scope_error() -> Optional[Dict[str, str]]:
"""Reject borrowed scopes before indexing can commit or roll them back.
Indexing commits writes and may recover from failures with a full rollback.
A nested scope reuses the caller's Session, so it cannot own either action.
Check before entering get_user_db_session, whose exception cleanup also
rolls back that Session.
Only an open ``get_user_db_session`` block on the calling thread counts
(``thread_session_manager.in_scope``). A Session obtained some other way,
such as directly from ``get_metrics_session``, is not detected.
"""
if thread_session_manager.in_scope():
return {
"status": "error",
"error": "Indexing must run outside an existing database session",
}
return None
# Service settings a Collection stores besides embedding_model, named as
# LibraryRAGService attributes.
_COLLECTION_INDEX_SETTINGS = (
"embedding_provider",
"chunk_size",
"chunk_overlap",
"splitter_type",
"text_separators",
"distance_metric",
"normalize_vectors",
"index_type",
)
def resolve_collection_index_settings(
collection: Collection, defaults: Dict[str, Any]
) -> Dict[str, Any]:
"""Return the settings a service indexing ``collection`` uses.
A stored value wins and a NULL column takes ``defaults``. Collections
indexed before #1054 never stored the five advanced settings, and
migration 0032 adds those columns without a backfill. ``get_rag_service``
passes the user's current settings as ``defaults``.
"""
provider = collection.embedding_model_type
normalize = collection.normalize_vectors
stored = {
"embedding_provider": provider.value if provider else None,
"chunk_size": collection.chunk_size,
"chunk_overlap": collection.chunk_overlap,
"splitter_type": collection.splitter_type,
"text_separators": collection.text_separators,
"distance_metric": collection.distance_metric,
"normalize_vectors": None if normalize is None else to_bool(normalize),
"index_type": collection.index_type,
}
return {
name: defaults[name] if value is None else value
for name, value in stored.items()
}
class _LazyEmbeddings(Embeddings):
"""Embeddings proxy that defers backend construction until first use.
A ``VectorIndex`` built purely to ``delete()`` never touches ``embeddings``
(delete resolves rows by id and calls ``store.apply(remove_ids=...)``).
``LocalEmbeddingManager.embeddings`` is a lazy property that, on first
access, synchronously loads the real backend (a SentenceTransformer costs
seconds and hundreds of MB of RSS, an Ollama client opens live httpx
connections). Handing that property straight to the delete path forces that
cost once per (deleted-document x collection). This proxy pulls the real
embeddings from the manager only if ``embed_*`` is genuinely called, so the
delete path pays nothing while index/search paths still work unchanged.
"""
def __init__(self, manager) -> None:
self._manager = manager
def embed_documents(self, texts):
return self._manager.embeddings.embed_documents(texts)
def embed_query(self, text):
return self._manager.embeddings.embed_query(text)
_CollectionLockPurpose = Literal["transaction", "rebuild"]
_IndexLockKey = Tuple[str, Union[str, Tuple[_CollectionLockPurpose, str]]]
class _TrackedRLock:
"""RLock proxy that records active keys even for direct acquire() calls.
The recursion depth is tracked locally (not via ``threading.RLock._is_owned``,
which is a CPython-private API and is not part of the threading contract —
absent on PyPy/other implementations). The key set membership is mutated
atomically with respect to ``acquire`` and ``pop_faiss_locks_for_user``: the
per-(user, index_path) entry is added when ownership transitions 0 → 1 and
discarded when it transitions 1 → 0, and both transitions happen under
``_faiss_write_locks_lock``.
Without holding ``_faiss_write_locks_lock`` across release, there would be a
race window: thread A could release → thread B (blocked in ``acquire``) unblock
and add its key → thread A then observe depth 0 and discard B's key. With
``pop_faiss_locks_for_user`` evicting a "free" lock, the next writer would
create a fresh lock for the same ``(username, index_path)`` and race B on the
FAISS file. Holding ``_faiss_write_locks_lock`` across inner release + depth
check + discard ensures no concurrent acquire's key-add can interleave with
key-discard.
"""
def __init__(self, key: _IndexLockKey):
self._key = key
self._lock = threading.RLock()
# Per-wrapper recursion depth (independent of the inner RLock so we
# never need the CPython-private ``_is_owned`` accessor). ``_owner``
# records the outer holder's thread id, or ``None`` when free.
# ``_tracks_active_key`` is True only when this wrapper added
# ``self._key`` to ``_faiss_active_lock_keys`` on its outer acquire
# (canonical wrappers only) so a non-canonical release cannot erase
# another holder's active-key entry.
self._depth = 0
self._owner = None
self._tracks_active_key = False
def acquire(self, *args, **kwargs):
first_acquire = self._lock.acquire(*args, **kwargs)
if first_acquire:
# ``RLock.acquire`` returns True for the outer acquisition AND for
# inner re-acquires. We detect outer-vs-inner via the wrapper's
# tracked ``_owner``: if the current thread already holds the lock,
# this is a re-entry; otherwise it's a fresh outer acquisition.
#
# Only the *canonical* wrapper for ``self._key`` (the one currently
# stored in ``_faiss_write_locks``) may mark the key active. A
# non-canonical wrapper can still be acquired briefly during the
# pop-during-acquire TOCTOU window handled by
# ``_hold_faiss_write_lock``; if it also added the key, its matching
# ``release()`` would discard the key while the *canonical* holder
# still owned the file — reopening the concurrent-FAISS-writer race.
was_owner = self._owner == threading.get_ident()
if not was_owner:
with _faiss_write_locks_lock:
if _faiss_write_locks.get(self._key) is self:
_faiss_active_lock_keys.add(self._key)
self._tracks_active_key = True
else:
self._tracks_active_key = False
self._owner = threading.get_ident()
self._depth += 1
return first_acquire
def release(self):
# Atomic with respect to acquire's add: hold the key-set lock across
# the inner release and the depth check so a concurrent acquire's
# key-add cannot interleave with our key-discard. ``_faiss_write_locks_lock``
# is taken BEFORE the inner release (the old bug was the reverse order).
#
# Only discard the active key if *this* wrapper registered it on
# acquire. Non-canonical wrappers never register, so their release
# cannot erase a concurrent canonical holder's active-key entry.
with _faiss_write_locks_lock:
self._lock.release()
self._depth -= 1
if self._depth == 0:
if self._tracks_active_key:
_faiss_active_lock_keys.discard(self._key)
self._tracks_active_key = False
self._owner = None
def locked(self) -> bool:
"""True iff the current thread holds the wrapper at depth >= 1."""
return self._owner == threading.get_ident() and self._depth > 0
def __enter__(self):
self.acquire()
return self
def __exit__(self, *args):
self.release()
# load_or_create verify→quarantine→build sequence per (username, index_path).
# MUST be module-level: each auto-index / scheduler / search worker constructs
# its own LibraryRAGService, so an instance-scoped lock would coordinate
# nothing. Pattern is adapted from web/queue/processor_v2._user_critical_locks
# — instance-scoped→module-scoped, username-only-key→(username, path)-key.
# See #4197 for the race this guards (concurrent save_local interleaves bytes,
# producing checksum_mismatch → destructive unlink, lost data).
# Logical collection operations share tracked ownership and user cleanup,
# but use tuple identities distinct from every physical path string.
_faiss_write_locks: Dict[_IndexLockKey, _TrackedRLock] = {}
_faiss_write_locks_lock = threading.Lock()
_faiss_active_lock_keys: Set[_IndexLockKey] = set()
# Hard cap on suffix-increment retries when generating the .corrupt-<ns> path.
# Normal case is one attempt — same-ns collisions only happen if the user
# manually created such files. 32 is a safety bound that converts a deadlock
# into a loud OSError.
_QUARANTINE_SUFFIX_RETRY_CAP = 32
# After a successful quarantine, keep at most this many older .corrupt-*
# files per base path (per side: .faiss.corrupt-* and .pkl.corrupt-* are
# counted independently). Prevents unbounded disk growth on systems that
# experience recurring corruption while preserving recent diagnostic
# artefacts. Keeping 5 means the user has the last 5 corruption events
# to inspect / submit with a bug report; anything older is dropped.
_QUARANTINE_KEEP_RECENT = 5
# ``FaissVectorStore._prepare`` raises ``ValueError`` with one of these exact,
# fixed-text messages when it refuses a query vector for a reason OTHER than
# a dimension mismatch (that one varies by dimension, so it stays a regex in
# ``search()`` below): non-finite (NaN/Inf), zero/overflow magnitude under L2
# normalization, and raw magnitude too large for unnormalized float32
# distance math. ``search()`` matches these verbatim (copied from
# ``_prepare``, not derived from it) so an unrelated provider ``ValueError``
# that merely resembles one of them keeps passing through unchanged — same
# fail-open-by-default posture as the dimension regex.
_DEGENERATE_QUERY_VECTOR_MESSAGES = frozenset(
{
"vectors contain non-finite values (NaN/Inf) — bad embedding",
(
"vectors contain a zero-magnitude or overflow-magnitude row "
"that L2 normalization cannot represent — bad embedding"
),
(
"vectors contain a magnitude too large for float32 distance "
"computation (would overflow to a dropped/mis-ranked search "
"hit) — normalize the embeddings or use a bounded model"
),
}
)
def _get_faiss_write_lock(username: str, index_path: str) -> _TrackedRLock:
"""Return the lock for ``(username, index_path)``, creating it on first
access. Key is normalised via ``Path.resolve()`` to match
``FileIntegrityManager._normalize_path`` so writers/readers/quarantine
all agree on identity.
"""
key = (username, str(Path(index_path).resolve()))
with _faiss_write_locks_lock:
lock = _faiss_write_locks.get(key)
if lock is None:
lock = _TrackedRLock(key)
_faiss_write_locks[key] = lock
return lock
@contextmanager
def _hold_faiss_write_lock(username: str, index_path: str):
"""Context manager that acquires the per-(username, index_path) FAISS
write lock, retrying across a pop-during-acquire TOCTOU window.
``_get_faiss_write_lock`` returns a wrapper reference, but
``pop_faiss_locks_for_user`` may run in the gap before our
``acquire()`` adds the key to ``_faiss_active_lock_keys`` and therefore
before the key is "active" from ``pop``'s perspective. Without a re-check,
the caller would hold a non-canonical wrapper while ``pop`` discarded the
canonical entry and the next writer created a fresh lock for the same
``(username, index_path)`` — reintroducing the same-(user, path)
concurrent-FAISS-writer race this module exists to eliminate.
The window is microseconds and requires a per-user lock cleanup to fire
mid-acquire, so this is a defence-in-depth tightening rather than a
regression fix — but it is cheap to close. After ``acquire()`` returns,
we re-check under ``_faiss_write_locks_lock`` that ``self`` is still the
canonical entry; if not, we release and retry with the new canonical
lock. Re-entry on the same wrapper is impossible here because each
iteration acquires a fresh wrapper reference.
"""
key = (username, str(Path(index_path).resolve()))
while True:
lock = _get_faiss_write_lock(username, index_path)
lock.acquire()
with _faiss_write_locks_lock:
canonical = _faiss_write_locks.get(key)
is_canonical = canonical is lock
if is_canonical:
try:
yield lock
finally:
lock.release()
return
# Evicted between _get_faiss_write_lock's lookup and our acquire().
# Release our (non-canonical) wrapper — acquire only marks the key
# active for the canonical dict entry, so this release cannot erase
# a concurrent canonical holder's active-key entry — then retry
# with the canonical lock.
lock.release()
def _get_collection_lock(
username: str, collection_id: str, *, purpose: _CollectionLockPurpose
) -> _TrackedRLock:
"""Identify a collection operation without interpreting its ID as a path.
The tuple namespace cannot collide with physical FAISS path keys. Share
tracked-lock cleanup with those locks so closing a user still releases
inactive entries while preserving locks held by background workers.
"""
key = (username, (purpose, str(collection_id)))
with _faiss_write_locks_lock:
lock = _faiss_write_locks.get(key)
if lock is None:
lock = _TrackedRLock(key)
_faiss_write_locks[key] = lock
return lock
@contextmanager
def _hold_collection_lock(
username: str,
collection_id: str,
*,
purpose: _CollectionLockPurpose,
blocking: bool = True,
):
"""Hold a canonical logical lock, or yield None on nonblocking contention.
Retry eviction between lookup and acquisition just as physical FAISS
locks do. Collection IDs remain opaque and never reach filesystem APIs.
"""
key = (username, (purpose, str(collection_id)))
while True:
lock = _get_collection_lock(username, collection_id, purpose=purpose)
if not lock.acquire(blocking=blocking):
yield None
return
with _faiss_write_locks_lock:
is_canonical = _faiss_write_locks.get(key) is lock
if is_canonical:
try:
yield lock
finally:
lock.release()
return
# Evicted before acquire; a stale wrapper cannot protect this key.
lock.release()
def pop_faiss_locks_for_user(username: str) -> None:
"""Remove inactive physical and logical index locks for a user."""
with _faiss_write_locks_lock:
stale = [k for k in _faiss_write_locks if k[0] == username]
for k in stale:
if k not in _faiss_active_lock_keys:
_faiss_write_locks.pop(k, None)
class LibraryRAGService:
"""Service for managing RAG indexing of library documents."""
def __init__(
self,
username: str,
embedding_model: str = DEFAULT_LOCAL_SEARCH_MODEL,
embedding_provider: str = DEFAULT_LOCAL_SEARCH_PROVIDER,
chunk_size: int = DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,
chunk_overlap: int = DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,
splitter_type: str = DEFAULT_LOCAL_SEARCH_SPLITTER_TYPE,
text_separators: Optional[list] = None,
distance_metric: str = DEFAULT_LOCAL_SEARCH_DISTANCE_METRIC,
normalize_vectors: bool = DEFAULT_LOCAL_SEARCH_NORMALIZE_VECTORS,
index_type: str = DEFAULT_LOCAL_SEARCH_INDEX_TYPE,
embedding_manager: Optional["LocalEmbeddingManager"] = None,
db_password: Optional[str] = None,
):
"""
Initialize library RAG service for a user.
Args:
username: Username for database access
embedding_model: Name of the embedding model to use
embedding_provider: Provider type ('sentence_transformers' or 'ollama')
chunk_size: Size of text chunks for splitting
chunk_overlap: Overlap between consecutive chunks
splitter_type: Type of splitter ('recursive', 'token', 'sentence', 'semantic')
text_separators: List of text separators for chunking (default: ["\n\n", "\n", ". ", " ", ""])
distance_metric: Distance metric ('cosine', 'l2', or 'dot_product')
normalize_vectors: Whether to normalize vectors with L2
index_type: FAISS index type ('flat', 'hnsw', or 'ivf')
embedding_manager: Optional pre-constructed LocalEmbeddingManager for testing/flexibility
db_password: Optional database password for background thread access
"""
self.username = username
self._db_password = db_password # Can be used for thread access
# Initialize optional attributes to None before they're set below
# This allows the db_password setter to check them without hasattr
self.embedding_manager = None
self.integrity_manager = None
self.embedding_model = embedding_model
self.embedding_provider = embedding_provider
self.chunk_size = chunk_size
self.chunk_overlap = chunk_overlap
self.splitter_type = splitter_type
self.text_separators = (
text_separators
if text_separators is not None
else list(DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS)
)
self.distance_metric = distance_metric
# Ensure normalize_vectors is always a proper boolean
self.normalize_vectors = to_bool(normalize_vectors, default=True)
self.index_type = index_type
# Emit the active configuration so users can confirm their
# UI-configured embedding settings are being honored (regression
# signal for #3453).
logger.info(
f"RAG service initialized for user={username}: "
f"provider={embedding_provider} model={embedding_model} "
f"chunk_size={chunk_size} chunk_overlap={chunk_overlap} "
f"splitter={splitter_type} index_type={index_type}"
)
# Use provided embedding manager or create a new one
# (Must be created before text splitter for semantic chunking)
# Track ownership so close() only tears down the manager when we
# constructed it — a caller-supplied manager stays under caller
# control (test fixtures, multi-service callers reusing one manager).
self._owns_embedding_manager = embedding_manager is None
if embedding_manager is not None:
self.embedding_manager = embedding_manager
else:
# Load the complete user settings snapshot from database using the
# proper method.
#
# STRICT snapshot is mandatory at this seam: a non-strict read
# silently falls back to the JSON defaults when the underlying
# settings query fails (SQLAlchemyError / stale enum row). Those
# defaults can lack an operator-selected cloud embedding
# provider's classification inputs and admit a cloud embedder
# under a local-only posture. We refuse before any
# LocalEmbeddingManager construction instead.
from ...settings.manager import SettingsManager
from ...security.egress.policy import (
Decision,
PolicyDeniedError,
)
# Use proper database session for SettingsManager
# Note: using _db_password (backing field) directly here because the
# db_password property setter propagates to embedding_manager/integrity_manager,
# which are still None at this point in __init__.
try:
with get_user_db_session(
username, self._db_password
) as session:
settings_manager = SettingsManager(session)
settings_snapshot = settings_manager.get_settings_snapshot(
strict=True
)
except PolicyDeniedError:
raise
except Exception as exc:
raise PolicyDeniedError(
Decision(False, "settings_unavailable"),
target=embedding_provider,
) from exc
# Add the specific settings needed for this RAG service
settings_snapshot.update(
{
"_username": username,
"embeddings.provider": embedding_provider,
f"embeddings.{embedding_provider}.model": embedding_model,
"local_search_chunk_size": chunk_size,
"local_search_chunk_overlap": chunk_overlap,
}
)
# Egress policy pre-flight at the constructor boundary so
# every direct ``LibraryRAGService(...)`` construction site
# is covered, not just the factory. Skipped when an
# ``embedding_manager`` is injected (tests / advanced flows)
# — those callers vouch for the manager themselves.
#
# Build the context from the ACTUAL scope (not a hardcoded
# BOTH) so PRIVATE_ONLY forces local embeddings even when the
# raw embeddings.require_local flag is at its default False —
# context_from_snapshot applies that coupling. Resolve the
# primary via the shared helper (single source of truth)
# instead of the old search.tool + searxng fallback, which
# was a fail-OPEN: a missing primary defaulted to the public
# searxng so the scope relaxed and a cloud embedder could be
# admitted. A missing primary now raises -> fail closed via
# the ValueError handler below.
from ...security.egress.policy import (
context_from_snapshot,
evaluate_embeddings,
resolve_run_primary_engine,
)
try:
primary = resolve_run_primary_engine(settings_snapshot)
policy_ctx = context_from_snapshot(
settings_snapshot, primary, username=username
)
except PolicyDeniedError:
raise
except ValueError as exc:
raise PolicyDeniedError(
Decision(False, "invalid_policy_config"),
target=embedding_provider,
) from exc
if policy_ctx.require_local_embeddings:
decision = evaluate_embeddings(
embedding_provider,
policy_ctx,
settings_snapshot=settings_snapshot,
)
if not decision.allowed:
logger.bind(policy_audit=True).warning(
"LibraryRAGService refused by egress policy",
provider=embedding_provider,
reason=decision.reason,
)
raise PolicyDeniedError(decision, target=embedding_provider)
self.embedding_manager = LocalEmbeddingManager(
embedding_model=embedding_model,
embedding_model_type=embedding_provider,
settings_snapshot=settings_snapshot,
)
# Initialize text splitter based on type
# (Must be created AFTER embedding_manager for semantic chunking)
self.text_splitter = get_text_splitter(
splitter_type=self.splitter_type,
chunk_size=self.chunk_size,
chunk_overlap=self.chunk_overlap,
text_separators=self.text_separators,
embeddings=self.embedding_manager.embeddings
if self.splitter_type == "semantic"
else None,
)
self.rag_index_record = None
# Initialize file integrity manager for FAISS indexes
self.integrity_manager = FileIntegrityManager(
username, password=self._db_password
)
self.integrity_manager.register_verifier(FAISSIndexVerifier())
self._closed = False
def close(self):
"""Release embedding model and index resources."""
if self._closed:
return
self._closed = True
# Release embedding manager (which in turn closes the underlying
# OllamaEmbeddings httpx clients — see LocalEmbeddingManager.close).
# Only when we own it; caller-supplied managers stay under caller
# control to avoid double-close / use-after-close.
if self.embedding_manager is not None:
if self._owns_embedding_manager:
self.embedding_manager.close()
self.embedding_manager = None
# Clear other resources
self.rag_index_record = None
self.integrity_manager = None
self.text_splitter = None
def __enter__(self):
"""Enter context manager."""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Exit context manager, ensuring cleanup."""
self.close()
return False
@property
def db_password(self):
"""Get database password."""
return self._db_password
@db_password.setter
def db_password(self, value):
"""Set database password and propagate to embedding manager and integrity manager."""
self._db_password = value
if self.embedding_manager:
self.embedding_manager.db_password = value
if self.integrity_manager:
self.integrity_manager.password = value
def _get_index_hash(
self,
collection_name: str,
embedding_model: str,
embedding_model_type: str,
) -> str:
"""Generate hash for index identification."""
identity = {
"chunk_overlap": self.chunk_overlap,
"chunk_size": self.chunk_size,
"collection_name": collection_name,
"distance_metric": self.distance_metric,
"embedding_model": embedding_model,
"embedding_provider": embedding_model_type,
"index_type": self.index_type,
"normalize_vectors": self.normalize_vectors,
"splitter_type": self.splitter_type,
"text_separators": self.text_separators,
}
hash_input = json.dumps(
identity, ensure_ascii=False, separators=(",", ":"), sort_keys=True
)
return hashlib.sha256(hash_input.encode()).hexdigest()
def _matches_collection_configuration(self, collection: Collection) -> bool:
"""Whether ``collection`` still stores this service's configuration.
NULL columns resolve as in ``get_rag_service``, which filled them from
the user's settings when it built this service, so they resolve to
this service's own values. Only a stored value can differ, such as one
a complete rebuild published.
"""
own = {name: getattr(self, name) for name in _COLLECTION_INDEX_SETTINGS}
return (
collection.embedding_model == self.embedding_model
and resolve_collection_index_settings(collection, own) == own
)
def _matches_current_index_configuration(self, rag_index: RAGIndex) -> bool:
stored_provider = rag_index.embedding_model_type
if isinstance(stored_provider, EmbeddingProvider):
stored_provider = stored_provider.value
stored_separators = rag_index.text_separators
if stored_separators is None:
stored_separators = DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS
if not isinstance(stored_separators, list) or not all(
isinstance(separator, str) for separator in stored_separators
):
return False
return (
rag_index.embedding_model == self.embedding_model
and stored_provider == self.embedding_provider
and rag_index.chunk_size == self.chunk_size
and rag_index.chunk_overlap == self.chunk_overlap
and (rag_index.splitter_type or "recursive") == self.splitter_type
and stored_separators == self.text_separators
and (rag_index.distance_metric or "cosine") == self.distance_metric
and (
rag_index.normalize_vectors
if rag_index.normalize_vectors is not None
else True
)
== self.normalize_vectors
and (rag_index.index_type or "flat") == self.index_type
)
def _find_matching_rag_index(
self, db_session: Session, collection_name: str, index_hash: str
) -> RAGIndex | None:
rag_index = (
db_session.query(RAGIndex).filter_by(index_hash=index_hash).first()
)
if rag_index is not None:
return rag_index
candidates = (
db_session.query(RAGIndex)
.filter_by(
collection_name=collection_name,
embedding_model=self.embedding_model,
embedding_model_type=EmbeddingProvider(self.embedding_provider),
)
.all()
)
for candidate in candidates:
if self._matches_current_index_configuration(candidate):
return candidate
return None
def _resolve_index_for_config(
self, db_session: Session, collection_id: str
) -> RAGIndex | None:
"""The collection's index for this service's configuration, or None.
Read-only: unlike ``_get_or_create_rag_index`` it never creates a
row or probes the embedding provider.
"""
collection_name = f"collection_{collection_id}"
return self._find_matching_rag_index(
db_session,
collection_name,
self._get_index_hash(
collection_name, self.embedding_model, self.embedding_provider
),
)
def _status_row_exists(
self,
session,
document_id: str,
collection_id: str,
rag_index_id: Optional[int],
) -> bool:
"""Whether the document's status row exists for one index identity.
Both sides of the prepare/write staleness comparison must measure
through this function AND against the same ``rag_index_id``: the
identity :meth:`_resolve_index_for_config` selected when the
prepared document was snapshotted
(``_PreparedDocument.status_index_id``). Deriving the write side's
identity from ``self.rag_index_record`` breaks the pairing whenever
that attribute lags the resolution: on a fresh per-request/per-sweep
service it is still ``None`` when the staleness gate runs
(``_get_vector_index`` only sets it afterwards), so every document
whose status row survived a chunk purge compares True against
False, aborts a healthy write as "stale", and
``_flag_document_for_reindex`` deletes the surviving row. A ``None``
identity means no index existed at prepare time; the NOT NULL
column can hold no row for it, so the predicate is False — the same
value preparation snapshotted.
"""
return (
session.query(RagDocumentStatus)
.filter_by(
document_id=document_id,
collection_id=collection_id,
rag_index_id=rag_index_id,
)
.first()
is not None
)
def _get_index_path(self, index_hash: str) -> Path:
"""Get path for FAISS index file.
Files are scoped to a per-user subdirectory derived from a hash
of the username so two users with identical collection name +
embedding model don't share the same .faiss/.pkl files on disk.
The previous layout used a shared `cache/rag_indices/` for all
users, which would let one user's vectors land in another
user's load path in any deployment running more than one
account against the same data dir.
Raises:
ValueError: If self.username is empty/None. sha256("") is a
known constant, so silently hashing an empty username would
let two different "no username" service instances collide
into one shared cache directory instead of failing loudly.
Defense-in-depth -- see #5481.
"""
if not self.username:
raise ValueError(
"Cannot compute a RAG index path for an empty username"
)
# Store in centralized cache directory (respects LDR_DATA_DIR)
user_scope = hashlib.sha256(self.username.encode("utf-8")).hexdigest()[
:16
]
rag_root = get_cache_directory() / "rag_indices"
cache_dir = rag_root / user_scope
create_directory(
cache_dir, context="per-user RAG index cache directory"
)
# 0o700: filesystem-level defense-in-depth so other local OS accounts
# can't browse another LDR user's vector caches. mkdir(parents=True)
# silently creates the intermediate rag_indices/ root under the process
# umask (typically 0o755, world-traversable), so harden the ROOT too —
# chmod'ing only the per-user leaf leaves a 0o755 rag_indices/ that lets
# another OS user traverse in and stat/enumerate every account's caches.
for d in (rag_root, cache_dir):
try:
d.chmod(0o700)
except OSError:
# Best-effort: some filesystems (e.g. Windows shares) don't
# honor chmod; the per-user path scope is still applied.
pass
return cache_dir / f"{index_hash}.faiss"
def _migrate_legacy_index_files(
self, legacy_path: Path, index_path: Path, rag_index: RAGIndex
) -> None:
"""Relocate a pre-per-user-scoping index into the per-user directory.
Before the per-user path scoping, indexes lived directly in the
shared ``cache/rag_indices/`` directory. ``_preflight_index_path``
recomputes the path and ignores the stored one, so without this
one-time migration an upgrading user's existing index is never
found again: semantic search silently returns nothing while
``DocumentCollection.indexed`` still claims everything is indexed,
so a non-force re-index no-ops too. Only files directly inside the
known legacy shared directory with the expected hash filename are
moved — arbitrary stored paths are not followed.
"""
legacy_root = get_cache_directory() / "rag_indices"
if (
legacy_path == index_path
or legacy_path.parent != legacy_root
or legacy_path.name != index_path.name
or not legacy_path.exists()
):
return
with _hold_faiss_write_lock(self.username, str(index_path)):
if index_path.exists():
return
try:
legacy_pkl = legacy_path.with_suffix(".pkl")
# Relocate phase-1's text-free .idmap.json sidecar BEFORE the
# .faiss, then move the .faiss LAST. phase-2 rekey looks for the
# sidecar next to the .faiss (legacy_rekey._sidecar_for =
# <stem>.idmap.json); leaving it at the legacy location orphans
# it, and a not-yet-rekeyed index then has no findable sidecar →
# rekey sees "no sidecar + old format" and destructively
# quarantines a healthy index. Ordering matters for crash
# recovery: the re-entry guard keys ONLY on index_path (the
# .faiss), so moving the .faiss last makes this idempotent — a
# crash after the sidecar move but before the .faiss move leaves
# the .faiss at the legacy path (guard still False) and re-entry
# simply retries (the sidecar move no-ops, new one exists). The
# reverse order would strand index_path.exists()=True with the
# sidecar orphaned at the legacy root, which the guard never
# re-invokes this to fix.
legacy_sidecar = legacy_path.with_name(
legacy_path.stem + ".idmap.json"
)
if legacy_sidecar.exists():
new_sidecar = index_path.with_name(
index_path.stem + ".idmap.json"
)
if not new_sidecar.exists():
# nosemgrep: semgrep.rules.path-traversal-risk, reason: The legacy parent and hash filename are checked above; both fixed-suffix sidecars derive from that path and the service-generated per-user index path
legacy_sidecar.rename(new_sidecar)
from ...vector_stores.segment_files import relocate_segments
moved_segments = relocate_segments(legacy_path, index_path)
try:
legacy_path.rename(index_path)
except OSError:
if moved_segments:
relocate_segments(index_path, legacy_path)
raise
# DELETE (don't relocate) any legacy plaintext .pkl companion:
# the new store writes NO .pkl, so moving it would just carry the
# plaintext chunk text to the new location. Its text lives in the
# encrypted DB.
if legacy_pkl.exists():
try:
legacy_pkl.unlink()
except OSError:
logger.warning(
f"Could not remove legacy plaintext .pkl "
f"{legacy_pkl} — delete it manually"
)
except OSError:
logger.exception(
f"Failed to migrate legacy FAISS index "
f"{legacy_path} -> {index_path}"
)
return
# Persist the relocated path so the row stops pointing at the
# now-empty legacy location.
with get_user_db_session(self.username, self.db_password) as session:
idx = session.query(RAGIndex).filter_by(id=rag_index.id).first()
if idx:
idx.index_path = str(index_path)
session.commit()
try:
# Refresh the integrity record under the new path (the old
# record is keyed by the legacy path and no longer applies).
self.integrity_manager.record_file(
index_path,
related_entity_type="rag_index",
related_entity_id=rag_index.id,
)
except Exception:
# Non-fatal: verify_file() creates a record on demand for
# unknown paths, so the subsequent load still succeeds.
logger.exception(
"Failed to refresh integrity record after index migration"
)
logger.info(
f"Migrated legacy shared FAISS index to per-user location: "
f"{index_path}"
)
def _reset_index_state_for_rebuild(
self, collection_id: str, rag_index: RAGIndex
) -> None:
"""Reset per-document indexed state when the index file is gone.
Reaching the fresh-build branch with DB rows that still claim
indexed content means the on-disk index was lost (missing after an
upgrade, quarantined, or deleted on dimension mismatch). Without
this reset, ``index_document``/``index_collection`` skip every
document (``DocumentCollection.indexed`` is still True), so the
only repair is an undocumented force re-index while search
silently returns nothing. Clearing the flags makes the regular
re-index path rebuild for real and makes the UI show the honest
unindexed state. Worst case of the narrow race with an in-flight
indexer is re-submitting chunks the merge step dedups by id.
"""
with get_user_db_session(self.username, self.db_password) as session:
idx = session.query(RAGIndex).filter_by(id=rag_index.id).first()
claims_content = bool(
idx and (idx.chunk_count or idx.total_documents)
)
stale_status = (
session.query(RagDocumentStatus)
.filter_by(rag_index_id=rag_index.id)
.count()
)
stale_memberships = (
session.query(DocumentCollection)
.filter_by(collection_id=collection_id, indexed=True)
.count()
)
if not (claims_content or stale_status or stale_memberships):
# Genuinely new index — nothing to reset.
return
if idx:
idx.chunk_count = 0
idx.total_documents = 0
session.query(RagDocumentStatus).filter_by(
rag_index_id=rag_index.id
).delete()
session.query(DocumentCollection).filter_by(
collection_id=collection_id, indexed=True
).update({"indexed": False, "chunk_count": 0})
session.commit()
logger.warning(
f"FAISS index file for collection {collection_id} is "
f"missing; reset indexed state for {stale_memberships} "
f"document(s) so the next index run rebuilds the index."
)
def _get_or_create_rag_index(
self,
collection_id: str,
*,
promote_current: bool = True,
db_session: Session | None = None,
commit: bool = True,
) -> RAGIndex:
"""Get or create RAGIndex record for the current configuration.
``promote_current`` (default True) controls whether the resolved row,
reused or just created, is promoted to ``is_current`` (demoting
others). Read paths (search) pass False: a mere search under a
stale/different config must NOT silently flip which index the
collection considers current; only an actual write (index) should.
A row created on a read path is still persisted, but stays
non-current until an indexing run promotes it.
"""
if db_session is None:
with get_user_db_session(
self.username, self.db_password
) as session:
return self._get_or_create_rag_index_in_session(
session,
collection_id,
promote_current=promote_current,
commit=commit,
)
return self._get_or_create_rag_index_in_session(
db_session,
collection_id,
promote_current=promote_current,
commit=commit,
)
def _get_or_create_rag_index_in_session(
self,
db_session: Session,
collection_id: str,
*,
promote_current: bool,
commit: bool,
) -> RAGIndex:
collection_name = f"collection_{collection_id}"
index_hash = self._get_index_hash(
collection_name, self.embedding_model, self.embedding_provider
)
rag_index = self._find_matching_rag_index(
db_session, collection_name, index_hash
)
created = False
if rag_index is None:
index_path = self._get_index_path(index_hash)
embedding_manager = self.embedding_manager
if embedding_manager is None:
raise RuntimeError(
"Cannot create an index after closing the service"
)
embedding_dim = len(
embedding_manager.embeddings.embed_query("test")
)
candidate = RAGIndex(
collection_name=collection_name,
embedding_model=self.embedding_model,
embedding_model_type=EmbeddingProvider(self.embedding_provider),
embedding_dimension=embedding_dim,
index_path=str(index_path),
index_hash=index_hash,
chunk_size=self.chunk_size,
chunk_overlap=self.chunk_overlap,
splitter_type=self.splitter_type,
text_separators=self.text_separators,
distance_metric=self.distance_metric,
normalize_vectors=self.normalize_vectors,
index_type=self.index_type,
chunk_count=0,
total_documents=0,
status=RAGIndexStatus.ACTIVE,
is_current=False,
)
try:
with db_session.begin_nested():
db_session.add(candidate)
db_session.flush()
except IntegrityError:
rag_index = self._find_matching_rag_index(
db_session, collection_name, index_hash
)
if rag_index is None:
raise
logger.info(
f"Using concurrently created RAG index: {index_hash}"
)
else:
rag_index = candidate
created = True
logger.info(f"Created new RAG index: {index_hash}")
# Only a write path (promote_current=True) may move the collection's
# is_current pointer. A read path that had to create the row leaves
# it non-current: the collection's real index must keep serving every
# other caller until an actual indexing run switches over.
promoted = promote_current and not rag_index.is_current
if promoted:
# A previous model switch may have left aggregates inflated while
# the one status row per document moved to another index. Repair
# all configurations once on promotion, then use O(1) deltas for
# the documents written under the newly current configuration.
index_rows = (
db_session.query(RAGIndex)
.filter_by(collection_name=collection_name)
.all()
)
totals = {
index_id: (documents, chunks or 0)
for index_id, documents, chunks in (
db_session.query(
RagDocumentStatus.rag_index_id,
func.count(),
func.sum(RagDocumentStatus.chunk_count),
)
.filter(
RagDocumentStatus.rag_index_id.in_(
[row.id for row in index_rows]
)
)
.group_by(RagDocumentStatus.rag_index_id)
.all()
)
}
for row in index_rows:
row.total_documents, row.chunk_count = totals.get(
row.id, (0, 0)
)
db_session.query(RAGIndex).filter(
RAGIndex.collection_name == collection_name,
RAGIndex.is_current.is_(True),
RAGIndex.id != rag_index.id,
).update({"is_current": False})
rag_index.is_current = True
# Only commit when this call actually created or promoted an index.
# A pure read-through of an existing current index must stay a no-op
# so it can't consume a caller's pending write (e.g. the fault the
# index-finalize self-heal backstop guards against).
if commit and (created or promoted):
db_session.commit()
db_session.refresh(rag_index)
return rag_index
def _quarantine_corrupt_index(self, index_path: Path, reason: str) -> None:
"""Rename a corrupted FAISS index to ``<path>.corrupt-<ns>``
instead of deleting it; any legacy plaintext ``.pkl`` companion
is deleted outright rather than preserved.
Preserves user data for inspection/recovery. The
dimension-mismatch branch elsewhere in this method intentionally
*deletes* — that case rebuilds from scratch and the old bytes
are unreadable with the new model. This helper is for the two
"transient or unknown failure" branches (verify_file said no,
loading the index into a ``VectorIndex``/faiss raised) where the
on-disk bytes may still be usable by a human.
The rebuilt index is re-recorded by the caller (``_record``
through ``FileIntegrityManager.record_file``), which resets the
path's verification streaks (``consecutive_failures`` /
``consecutive_successes``) — the streak accumulated against the
quarantined bytes must not be charged to the new ones.
Raises ``OSError`` on rename failure (disk full, read-only fs,
permission denied). Re-raising prevents silent data loss: if we
swallowed the error, the next ``persist()``/``faiss.write_index``
would overwrite the corrupt bytes anyway. Caller paths log the
exception via the broader try/except around their indexer call.
"""
ns = time.time_ns()
pkl_path = index_path.with_suffix(".pkl")
# Same-nanosecond collisions essentially can't happen between
# concurrent threads (we hold the per-path lock), but a user
# could manually create such files. Loop with a hard cap so a
# weird state surfaces as a clean OSError rather than a hang.
suffix_n = 0
faiss_target = Path(f"{index_path}.corrupt-{ns}")
pkl_target = Path(f"{pkl_path}.corrupt-{ns}")
while faiss_target.exists() or pkl_target.exists():
suffix_n += 1
if suffix_n > _QUARANTINE_SUFFIX_RETRY_CAP:
raise OSError(
f"Quarantine path collisions exceeded "
f"{_QUARANTINE_SUFFIX_RETRY_CAP} retries for "
f"{index_path}"
)
faiss_target = Path(f"{index_path}.corrupt-{ns}-{suffix_n}")
pkl_target = Path(f"{pkl_path}.corrupt-{ns}-{suffix_n}")
try:
# nosemgrep: semgrep.rules.path-traversal-risk, reason: Callers supply the index path recomputed by _preflight_index_path; quarantine appends only a generated timestamp and collision counter in the same directory
index_path.rename(faiss_target)
from ...vector_stores.segment_files import relocate_segments
try:
relocate_segments(index_path, faiss_target)
except ValueError:
# Same containment as the delete sweep: the relocation guard
# (or a poisoned/colliding companion directory) must not abort
# the quarantine mid-way — the root is already quarantined and
# the plaintext .pkl removal below is not optional.
logger.warning(
f"Could not relocate vector segments for quarantined "
f"index {index_path} to {faiss_target}"
)
logger.warning(
f"Quarantined corrupted FAISS index to {faiss_target} "
f"(reason: {reason}). Searches against this collection "
f"will return empty results until the index is rebuilt. "
f"Document chunks are preserved in the database — "
f"trigger 'Re-index Collection' (or set "
f"research_library.auto_index_enabled=true and re-run "
f"indexing) to recover."
)
if pkl_path.exists():
# DELETE (not rename) any .pkl companion. The new store writes
# NO .pkl, so a .pkl next to a .faiss is a LEGACY plaintext
# docstore — its chunk text lives in the (encrypted) DB, so
# renaming it aside to .corrupt-<ns> would needlessly preserve
# plaintext chunk text on disk. Plaintext removal is not optional.
try:
pkl_path.unlink()
logger.info(f"Removed legacy plaintext PKL {pkl_path}")
except OSError:
logger.warning(
f"Could not remove legacy plaintext PKL {pkl_path} — "
"delete it manually"
)
else:
# Missing .pkl is the normal case for the new store. Not
# re-raised: the .faiss is already preserved.
logger.debug(f"No PKL companion at {pkl_path}.")
except OSError:
if not index_path.exists():
# The source is already gone — most likely another worker
# PROCESS quarantined the same corrupt index concurrently (the
# per-path lock is a threading.Lock, so it serialises only
# threads within ONE process, not across gunicorn workers /
# the scheduler process). The objective — get the corrupt bytes
# off index_path so the caller rebuilds fresh — is already met,
# so don't abort a healthy rebuild with a spurious
# FileNotFoundError. Still purge any lingering plaintext .pkl:
# the no-plaintext-at-rest invariant is not optional even here.
if pkl_path.exists():
try:
pkl_path.unlink()
except OSError:
logger.warning(
f"Could not remove legacy plaintext PKL {pkl_path} "
"— delete it manually"
)
logger.warning(
f"Corrupt index {index_path} was already quarantined by "
f"another worker (reason: {reason}); proceeding to rebuild."
)
return
# A genuine failure (disk-full, read-only fs, permission denied)
# with the corrupt bytes STILL in place. Re-raise so the caller
# surfaces a real failure instead of letting the next
# persist()/write_index overwrite the corrupt bytes.
logger.exception(
f"Failed to quarantine corrupted index at {index_path}"
)
raise
# Best-effort retention sweep. The quarantine itself succeeded
# above; failing to prune older files is not a correctness
# issue, just a disk-usage one — log and move on.
self._prune_old_quarantined_files(index_path)
@staticmethod
def _corrupt_sort_key(path: Path) -> Tuple[int, int]:
"""Extract ``(ns, suffix_n)`` from a ``.corrupt-<ns>[-<n>]``
filename so retention can sort by the monotonic nanosecond
suffix the quarantine path embeds — *not* by ``st_mtime``.
Filesystem timestamp granularity is sometimes 1s or 2s
(FAT32/ext3/SMB shares), making mtime ordering non-deterministic
when multiple quarantines happen within one tick. The
``.corrupt-<ns>`` suffix carries the original ``time.time_ns()``
from the quarantine and is reliable across all filesystems.
Returns ``(-1, -1)`` for malformed names (manually-placed
files) so they sort below any real entry under ``reverse=True``
— i.e., they get pruned first.
"""
name = path.name
marker = ".corrupt-"
idx = name.rfind(marker)
if idx == -1:
return (-1, -1)
tail = name[idx + len(marker) :]
parts = tail.split("-")
try:
ns = int(parts[0])
except ValueError:
return (-1, -1)
suffix_n = 0
if len(parts) > 1:
try:
suffix_n = int(parts[-1])
except ValueError:
# Unknown trailing component — keep the file but at the
# base ns ordering.
pass
return (ns, suffix_n)
def _prune_old_quarantined_files(self, index_path: Path) -> None:
"""Keep the newest quarantined generations and their segment payloads.
A root and its companion directory count as one generation. Remove
payloads whose roots an older retention sweep already deleted. Legacy
``.pkl`` siblings retain their independent file-based retention.
Ordering uses the embedded ``-<ns>`` from the quarantine
filename, not ``st_mtime``: file systems with 1-2s timestamp
granularity can otherwise produce non-deterministic retention
on bursts.
Best-effort: logs and swallows any error so a sweep failure
never propagates back into the indexing path.
"""
parent = index_path.parent
pkl_path = index_path.with_suffix(".pkl")
from ...vector_stores.segment_files import delete_segment_files
for base in (index_path, pkl_path):
pattern = f"{base.name}.corrupt-*"
try:
# Sort newest-first by the embedded -<ns>; everything
# past the keep window is stale.
candidates = list(parent.glob(pattern))
except OSError:
logger.warning(
f"Failed to enumerate {pattern} in {parent} for "
f"quarantine retention sweep"
)
continue
roots = []
for candidate in candidates:
try:
if candidate.is_symlink():
continue
if candidate.is_file():
roots.append(candidate)
elif (
base == index_path
and candidate.name.endswith(".segments")
and candidate.is_dir()
):
root = candidate.with_suffix("")
if (
self._corrupt_sort_key(root) != (-1, -1)
and not root.is_symlink()
and not root.exists()
):
delete_segment_files(root)
except (OSError, ValueError):
logger.warning(
f"Failed to prune quarantined payload {candidate}; continuing"
)
roots.sort(key=self._corrupt_sort_key, reverse=True)
for stale in roots[_QUARANTINE_KEEP_RECENT:]:
try:
if base == index_path:
delete_segment_files(stale)
stale.unlink()
logger.info(f"Pruned old quarantined file: {stale}")
except (OSError, ValueError):
logger.warning(
f"Failed to prune quarantined file {stale}; continuing"
)
def _preflight_index_path(
self,
collection_id: str,
rag_index: RAGIndex,
*,
reset_stale_state: bool = False,
probe_dimension: bool | None = None,
) -> Path:
"""Verify -> quarantine -> dimension-check pre-flight for ``rag_index``.
Extracted from the pre-cutover ``load_or_create_faiss_index``
(deleted — the old LangChain-FAISS path is gone) so every
index/search/delete call site shares ONE recovery path instead of
duplicating it. Mutates ``rag_index.index_path`` / ``rag_index.embedding_dimension``
in place — matching the pre-refactor behavior of stamping the
recomputed path/dimension back onto the in-memory record so callers
that read ``self.rag_index_record`` afterwards see the current
values — and returns the resolved on-disk path.
``probe_dimension`` decides whether the embedding-dimension drift
probe runs (see the ``verified and should_probe_dimension`` block
below). ``None`` (the default) keeps the original rule — probe iff
``reset_stale_state`` (a WRITE path). Pass an explicit ``True``/
``False`` to override that rule for a call site that is not itself
a write but still needs (or must skip) the probe — e.g.
``reconcile_collection_index`` passes ``True``: unlike ``search()``,
it never embeds a query, so it gets no free dimension check from
the vector store's ``_prepare`` and would otherwise miss drift
entirely.
Deliberately does NOT load or construct a vector store: that stays
the caller's job (via ``VectorIndex(...)``), so a corrupt/foreign/
dimension-mismatched file surfaces as an exception from THAT
construction, which the caller catches to quarantine + rebuild (see
``_get_vector_index``).
"""
index_path = self._get_index_path(rag_index.index_hash)
stored_path = (
Path(rag_index.index_path) if rag_index.index_path else None
)
rag_index.index_path = str(index_path)
if not index_path.exists() and stored_path is not None:
self._migrate_legacy_index_files(stored_path, index_path, rag_index)
# Hold the per-(username, index_path) write lock across the entire
# verify -> quarantine -> dimension-check sequence — see #4197 (a
# narrower scope would let a concurrent writer's save race the
# verification).
if index_path.exists():
lock = _get_faiss_write_lock(self.username, str(index_path))
with lock:
verified, reason = self.integrity_manager.verify_file(
index_path
)
if not verified:
if reason == NO_INTEGRITY_RECORD:
# A MISSING record is not proven corruption, and unlike
# checksum_mismatch it cannot be attacker-induced: the
# record lives in the per-user ENCRYPTED DB, so removing
# it needs the DB password (which also decrypts
# everything). It only arises from our own crash between
# the index write and record_file (see legacy_rekey
# Phase B) or a pre-integrity-feature index. ADOPT the
# byte-present file by recording its integrity now — on
# BOTH read and write paths. Adoption is non-destructive
# (it only records a checksum), so a read path may do it:
# refusing here instead would hard-fail EVERY search on a
# byte-healthy, missing-record index forever (a read-only
# collection is never revisited by a write op that would
# otherwise adopt it). If the bytes are actually
# unreadable/foreign/wrong-dim, the VectorIndex load below
# still raises and the caller handles it — corruption is
# caught either way. Only checksum_mismatch (genuine
# tamper) is refused/quarantined below.
logger.warning(
f"No integrity record for {index_path}; adopting the "
"existing index (recording its integrity) rather than "
"quarantining — a missing record is not corruption."
)
self.integrity_manager.record_file(
index_path,
related_entity_type="rag_index",
related_entity_id=rag_index.id,
)
# Adopted = now trusted: fall through — a WRITE
# path (reset_stale_state=True) then probes the
# embedding dimension and rebuilds on drift; a READ
# path skips the probe (the vector store's
# ``_prepare`` rejects a wrong-dimension query).
verified = True
elif not reset_stale_state:
# Read path (search): refuse to serve an index that
# failed verification for a reason OTHER than a missing
# record (a checksum_mismatch = genuine tamper, or a
# transient read failure), but do NOT destroy it —
# quarantine is a WRITE-path recovery decision. A
# subsequent index/write operation quarantines + rebuilds.
raise RuntimeError(
f"Integrity verification failed for {index_path}: "
f"{reason} — refusing on a read path (a subsequent "
"index/write operation will quarantine + rebuild)"
)
elif reason and reason.startswith(
"checksum_calculation_failed"
):
# Transient: could not READ the file to compute its
# checksum (disk hiccup, momentary lock). This says
# NOTHING about tampering — unlike checksum_mismatch — so
# quarantining would force a needless full re-embed of a
# healthy collection. Raise so the operation retries (like
# the read path) instead of destroying the index.
raise RuntimeError(
f"Integrity check could not read {index_path} "
f"({reason}) — refusing to quarantine on a transient "
"read failure; retry the operation."
)
else:
logger.error(
f"Integrity verification failed for {index_path}: "
f"{reason}. Quarantining for recovery; creating "
f"new index."
)
self._quarantine_corrupt_index(index_path, reason)
should_probe_dimension = (
reset_stale_state
if probe_dimension is None
else probe_dimension
)
if verified and should_probe_dimension:
# Probe the embedding model OUTSIDE the quarantine
# decision (WRITE paths only, by default): embed_query
# fails when the provider itself is unreachable (e.g.
# Ollama down), which says nothing about the index
# file's health, and must propagate rather than trigger
# a destructive rebuild of a healthy index. search()
# skips the probe entirely — a wrong-dimension query is
# rejected by the vector store's ``_prepare`` (see
# FaissVectorStore) so reads stay fail-closed without
# the round-trip. ``reconcile_collection_index`` is the
# one exception: it never embeds a query (it only calls
# ``live_ids()``), so it gets none of that free
# protection from ``_prepare`` — it passes
# ``probe_dimension=True`` explicitly to keep detecting
# drift despite ``reset_stale_state=False``.
current_dim = len(
self.embedding_manager.embeddings.embed_query(
"dimension_check"
)
)
stored_dim = rag_index.embedding_dimension
if stored_dim and current_dim != stored_dim:
logger.warning(
f"Embedding dimension mismatch detected! "
f"Index created with dim={stored_dim}, "
f"current model returns dim={current_dim}. "
f"Deleting old index and rebuilding."
)
try:
from ...vector_stores.segment_files import (
delete_segment_files,
)
# Remove the manifest first: if segment cleanup
# then refuses a foreign file, only unreferenced
# segments remain, never a manifest pointing at
# deleted segments.
index_path.unlink()
pkl_path = index_path.with_suffix(".pkl")
if pkl_path.exists():
pkl_path.unlink()
delete_segment_files(index_path)
logger.info(
f"Deleted old index files at {index_path}"
)
except Exception:
logger.exception("Failed to delete old index files")
with get_user_db_session(
self.username, self.db_password
) as session:
idx = (
session.query(RAGIndex)
.filter_by(id=rag_index.id)
.first()
)
if idx:
idx.embedding_dimension = current_dim
session.commit()
logger.info(
f"Updated RAGIndex dimension to {current_dim}"
)
# Reset RAGIndex counts, RagDocumentStatus, and
# DocumentCollection.indexed together — a hand-rolled
# partial reset here previously left
# DocumentCollection.indexed=True, which makes
# index_document/index_collection skip every document
# and search silently return nothing after the rebuild.
self._reset_index_state_for_rebuild(
collection_id, rag_index
)
rag_index.embedding_dimension = current_dim
if not index_path.exists():
# The new per-user path is missing — but that alone does NOT mean the
# index is gone. A one-time legacy-path relocation
# (_migrate_legacy_index_files above) can fail transiently (a rename
# hitting disk-full, an AV/backup file lock, a busy network mount),
# leaving the bytes fully intact at the stored legacy path. Treating
# that as "gone" would wipe a healthy collection's indexed bookkeeping
# — even on a mere search — and force a needless full re-embed. Only
# self-heal when the bytes are absent at BOTH the new and the legacy
# location; otherwise leave the state alone so the next write-path
# access retries the relocation.
legacy_bytes_present = bool(
stored_path is not None
and stored_path != index_path
and stored_path.exists()
)
if not legacy_bytes_present:
stale_indexed = bool(
(rag_index.chunk_count or 0) > 0
or (rag_index.total_documents or 0) > 0
)
if stale_indexed:
# DB says indexed, but the file is GONE at both locations
# (cache dir cleared, restored without the cache dir, lost
# volume, crash between quarantine and rebuild). Reset so it
# self-heals — even on a READ path: an absent file has
# nothing to preserve, and without this search silently
# returns [] forever (get_rag_stats still reports 100%
# indexed and a normal reindex short-circuits on
# indexed=True, so nothing ever recovers it).
logger.warning(
f"RAG index file for collection {collection_id} is "
f"MISSING at {index_path} while the collection is marked "
"indexed — resetting indexed state so it rebuilds "
"(search would otherwise return no results indefinitely)."
)
self._reset_index_state_for_rebuild(
collection_id, rag_index
)
elif reset_stale_state:
self._reset_index_state_for_rebuild(
collection_id, rag_index
)
return index_path
def _get_vector_index(
self,
collection_id: str,
collection_name: str,
*,
reset_stale_state: bool = False,
probe_dimension: bool | None = None,
) -> VectorIndex:
"""Build a :class:`VectorIndex` for ``collection_id``.
Single call site for the index/search/delete paths: runs the
verify/quarantine/dimension-check pre-flight, then constructs the
facade. On a ``ValueError``/``RuntimeError`` from the underlying
store's ``load()`` (corrupt bytes, a foreign/pre-migration format
that isn't an ``IndexIDMap2``, or a dimension mismatch the
pre-flight didn't already catch) the corrupt file is quarantined,
stale per-document indexed state is reset, and construction is
retried once as a fresh, empty store.
NOTE: like ``_get_or_create_rag_index``, this CREATES a RAGIndex
row if none exists for the configured (collection, embedding model)
— callers on a delete-only path that must not create an index
(e.g. ``remove_documents_from_index``) guard with their own
existence check before calling this.
``probe_dimension`` is forwarded to ``_preflight_index_path`` (see
its docstring) unchanged. Every caller but
``reconcile_collection_index`` leaves it at the default ``None``.
"""
# Only WRITE paths (reset_stale_state=True) may re-promote a reused
# index to is_current; a read-path search must not flip the pointer.
rag_index = self._get_or_create_rag_index(
collection_id, promote_current=reset_stale_state
)
self.rag_index_record = rag_index
index_path = self._preflight_index_path(
collection_id,
rag_index,
reset_stale_state=reset_stale_state,
probe_dimension=probe_dimension,
)
lock = _get_faiss_write_lock(self.username, str(index_path))
# nested=True: these run reentrantly inside VectorIndex.apply(), which
# holds just-flushed, uncommitted DocumentChunk rows on this same
# thread-local session. The integrity write must run in a SAVEPOINT and
# let apply()'s caller commit — a plain commit/rollback here would
# settle or DISCARD those pending rows (silently losing indexed text
# while the vectors persist). See FileIntegrityManager._integrity_write.
def _record(path: Path) -> None:
self.integrity_manager.record_file(
path,
related_entity_type="rag_index",
related_entity_id=rag_index.id,
nested=True,
)
def _verify(path: Path):
return self.integrity_manager.verify_file(path, nested=True)
kwargs = {
"username": self.username,
"db_password": self.db_password,
# Lazy: index()/search() resolve the real backend on first embed_*
# call (identical behaviour, one extra attribute hop), while the
# delete-only path (remove_documents_from_index) never materialises
# it at all. See _LazyEmbeddings.
"embeddings": _LazyEmbeddings(self.embedding_manager),
"embedding_model": self.embedding_model,
"embedding_model_type": EmbeddingProvider(self.embedding_provider),
"collection_name": collection_name,
"index_key": rag_index.index_hash,
"require_document_membership": True,
"dimension": rag_index.embedding_dimension,
"path": index_path,
"lock": lock,
"integrity_record": _record,
"integrity_verify": _verify,
# Use the STORED index config, not this service instance's. The
# RAGIndex row is stamped with index_type/metric/normalize at
# creation (see _get_or_create_rag_index); the constructing
# LibraryRAGService may carry different CURRENT defaults (the
# factory falls back to global settings for a collection whose
# metadata was never stored). Building against self.* would load a
# real HNSW file while labelling it "flat" (or vice-versa), and
# FaissVectorStore.supports_delete trusts the label — routing a
# removal through remove_ids on an HNSW index (unsupported → raises)
# or silently rewriting a flat file as HNSW. This mirrors the fix
# already applied to purge_document_vectors below.
"index_type": rag_index.index_type or self.index_type,
"metric": rag_index.distance_metric or self.distance_metric,
"normalize": (
rag_index.normalize_vectors
if rag_index.normalize_vectors is not None
else self.normalize_vectors
),
}
try:
return VectorIndex(**kwargs)
except (ValueError, RuntimeError):
if not reset_stale_state:
# Read paths (search) must stay side-effect-free. A transient
# load failure (OOM, a disk hiccup, a momentarily-locked file)
# on an existing, byte-healthy index must NOT quarantine the
# file or wipe the collection's indexed state — that would turn
# a retryable blip into a forced full re-embed of the whole
# collection triggered by a mere search. Surface the error;
# quarantine + rebuild is a WRITE-path (reset_stale_state=True)
# decision. (A never-indexed collection never reaches here — no
# file exists, so VectorIndex.create() succeeds above.)
raise
# A load failure here — after _preflight_index_path's verify_file
# just PASSED on the same bytes — is ambiguous: it is either a
# genuine format/dimension mismatch (deterministic — needs a rebuild)
# OR a transient OS hiccup (EMFILE under concurrent multi-user load,
# a momentary AV-scan/backup file lock; the byte-healthy file loads
# fine moments later). faiss surfaces BOTH as the same RuntimeError,
# so quarantining unconditionally destroys a provably-healthy index
# and forces a needless full re-embed on a mere transient blip.
# Distinguish by RETRYING the load once: a transient failure clears,
# a deterministic one repeats. Only quarantine when the retry also
# fails. (Mirrors _preflight_index_path's transient-vs-tamper split.)
logger.warning(
f"Failed to load vector store at {index_path}; retrying once "
"before quarantining (may be a transient OS hiccup)"
)
try:
return VectorIndex(**kwargs)
except (ValueError, RuntimeError):
pass
logger.warning(
f"Vector store at {index_path} failed to load twice; "
"quarantining and rebuilding fresh"
)
with lock:
if index_path.exists():
self._quarantine_corrupt_index(
index_path, "vector_index_load_failed"
)
self._reset_index_state_for_rebuild(collection_id, rag_index)
return VectorIndex(**kwargs)
def search(
self, query: str, collection_id: str, top_k: int
) -> List[SearchResult]:
"""Search one published generation through the metadata switch."""
with _hold_collection_lock(
self.username, collection_id, purpose="transaction"
):
return self._search_published(query, collection_id, top_k)
def _search_published(
self, query: str, collection_id: str, top_k: int
) -> List[SearchResult]:
"""Semantic search within ``collection_id`` via the vector store.
Runs the same verify/quarantine pre-flight as indexing (through
``_get_vector_index``), then delegates to ``VectorIndex.search``.
The embedding-dimension drift probe is SKIPPED on this read path:
the vector store's ``_prepare`` (see FaissVectorStore) rejects a
wrong-dimension, non-finite, zero-magnitude, or overflow-magnitude
query vector before it ever reaches the FAISS index — even on an
EMPTY store, since ``_prepare`` runs before the ``ntotal == 0``
check. Reads stay fail-closed without the probe's round-trip.
Every such rejection is translated below into a service-level
``RuntimeError`` carrying the collection id: a degenerate or
wrong-dimension query embedding is a PROVIDER fault worth surfacing
loudly, not one to silently swallow. ``reset_stale_state`` is left
at its default False: a transient integrity hiccup during a mere
search must not wipe the collection's indexed state and force a
full re-embed.
Callers are expected to have already confirmed the collection has
indexed documents (e.g. via ``has_indexed_documents``) before
calling this — for an ORDINARY query, this method will otherwise
create an empty RAGIndex/store for a never-indexed (collection,
embedding model) pair and return no results, rather than raising.
A DEGENERATE query embedding (see above) is refused even on that
never-indexed store — it is never swallowed into an empty result
either.
"""
collection_name = f"collection_{collection_id}"
vindex = self._get_vector_index(collection_id, collection_name)
try:
return vindex.search(query, top_k)
except ValueError as exc:
# _prepare() in FaissVectorStore raises ValueError when it
# refuses the query vector outright: either a dimension
# mismatch (both dimensions in the message, so it needs a
# regex — see below) or one of the fixed-text "degenerate
# embedding" messages in _DEGENERATE_QUERY_VECTOR_MESSAGES
# above (non-finite, zero/overflow magnitude). Matching the
# exact formats (not a substring/keyword check) means an
# unrelated provider ValueError that merely mentions
# "dimension" or "magnitude" still passes through unchanged.
# Translate every match to a service-level RuntimeError with
# collection context so callers that catch the legacy
# exception type, and logs that report the affected
# collection, still work.
msg = str(exc)
if re.fullmatch(
r"vector dimension [0-9]+ != index dimension [0-9]+", msg
):
raise RuntimeError(
f"Embedding dimension mismatch — the index for "
f"collection {collection_id} was built with a different "
f"embedding model. Re-index the collection to fix this. "
f"(underlying error: {exc})"
) from exc
if msg in _DEGENERATE_QUERY_VECTOR_MESSAGES:
raise RuntimeError(
f"Query embedding rejected for collection "
f"{collection_id}: the embedding provider returned a "
f"degenerate vector for this query (non-finite, "
f"zero-magnitude, or overflow-magnitude) that cannot be "
f"searched. (underlying error: {exc})"
) from exc
raise
def get_current_index_info(
self, collection_id: Optional[str] = None
) -> Optional[Dict[str, Any]]:
"""
Get information about the current RAG index for a collection.
Args:
collection_id: UUID of collection (defaults to Library if None)
"""
with get_user_db_session(self.username, self.db_password) as session:
# Get collection name in the format stored in RAGIndex (collection_<uuid>)
if collection_id:
collection = (
session.query(Collection)
.filter_by(id=collection_id)
.first()
)
collection_name = (
f"collection_{collection_id}" if collection else "unknown"
)
else:
# Default to Library collection
from ...database.library_init import get_default_library_id
collection_id = get_default_library_id(
self.username, self.db_password
)
collection_name = f"collection_{collection_id}"
rag_index = (
session.query(RAGIndex)
.filter_by(collection_name=collection_name, is_current=True)
.first()
)
if not rag_index:
# Debug: check all RAG indices for this collection
all_indices = session.query(RAGIndex).all()
logger.info(
f"No RAG index found for collection_name='{collection_name}'. All indices: {[(idx.collection_name, idx.is_current) for idx in all_indices]}"
)
return None
# Calculate actual counts from rag_document_status table
from ...database.models.library import RagDocumentStatus
actual_chunk_count = (
session.query(func.sum(RagDocumentStatus.chunk_count))
.filter_by(collection_id=collection_id)
.scalar()
or 0
)
actual_doc_count = (
session.query(RagDocumentStatus)
.filter_by(collection_id=collection_id)
.count()
)
return {
"embedding_model": rag_index.embedding_model,
"embedding_model_type": rag_index.embedding_model_type.value
if rag_index.embedding_model_type
else None,
"embedding_dimension": rag_index.embedding_dimension,
"chunk_size": rag_index.chunk_size,
"chunk_overlap": rag_index.chunk_overlap,
"chunk_count": actual_chunk_count,
"total_documents": actual_doc_count,
"created_at": rag_index.created_at.isoformat(),
"last_updated_at": rag_index.last_updated_at.isoformat(),
}
def _flag_document_for_reindex(
self, session, document_id: str, collection_id: str
) -> None:
"""Mark a document NOT indexed so the reconciler re-embeds it.
Used on index_document failure paths: ``VectorIndex.index()`` runs
``store.apply()`` — DURABLY mutating the FAISS file — BEFORE the DB
commit, so a failure/rollback after that point can leave the source's
prior chunk rows resurrected with no vectors (silently unsearchable)
while ``DocumentCollection.indexed`` is reverted to its pre-attempt
state. The background reconciler only revisits ``indexed=False`` rows,
so without this flag the document stays permanently, silently
unsearchable. Best-effort + committed in its own statement;
index_document owns per-document commits (see index_all_documents), so
this clobbers no caller. Remove the status row's contribution from its
RAGIndex counters in the same transaction; later retries add it back.
"""
try:
status = (
session.query(RagDocumentStatus)
.filter_by(document_id=document_id, collection_id=collection_id)
.first()
)
if status is not None:
rag_index = (
session.query(RAGIndex)
.filter_by(id=status.rag_index_id)
.first()
)
if rag_index is not None:
rag_index.chunk_count = max(
0, (rag_index.chunk_count or 0) - status.chunk_count
)
rag_index.total_documents = max(
0, (rag_index.total_documents or 0) - 1
)
session.query(DocumentCollection).filter_by(
document_id=document_id, collection_id=collection_id
).update(
{"indexed": False, "chunk_count": 0},
synchronize_session=False,
)
session.query(RagDocumentStatus).filter_by(
document_id=document_id, collection_id=collection_id
).delete(synchronize_session=False)
session.commit()
except Exception:
safe_rollback(
session, "library_rag_service._flag_document_for_reindex"
)
logger.warning(
f"Could not flag document {document_id} for re-index after a "
f"failed index of collection {collection_id}; a manual reindex "
"may be needed to restore its search."
)
@contextmanager
def _collection_transaction_lock(self, collection_id: str):
"""Serialize the DB+FAISS transaction for one collection.
FAISS already uses this same re-entrant lock for reload/apply/persist and
integrity recording. Acquiring it around the complete document operation
also closes the store-persist-before-SQLCipher-commit window to sibling
workers: no worker can verify/quarantine or mutate the file until the
preceding worker's database commit (or rollback/reindex flag) finishes.
"""
# This identity survives model/configuration changes and publication
# of a new generation. Acquire it before resolving the physical path.
with _hold_collection_lock(
self.username, collection_id, purpose="transaction"
):
with get_user_db_session(
self.username, self.db_password
) as session:
index = self._resolve_index_for_config(session, collection_id)
index_hash = (
index.index_hash
if index is not None
else self._get_index_hash(
f"collection_{collection_id}",
self.embedding_model,
self.embedding_provider,
)
)
index_path = self._get_index_path(index_hash)
with _hold_faiss_write_lock(self.username, str(index_path)) as lock:
yield lock
def _embed_texts_cancellable(
self,
texts: List[str],
is_cancelled: Optional[Callable[[], bool]] = None,
) -> Optional[List[List[float]]]:
"""Embed texts, honouring cancellation between batches.
Returns the full vector list, or ``None`` when ``is_cancelled()``
fired before or during embedding — the caller must abandon the
document (nothing was persisted yet at the prepare stage). The
in-flight batch finishes naturally: an HTTP round-trip or a local
forward pass cannot be safely interrupted mid-array, so batching
bounds the uncancellable tail to one batch instead of the whole
document.
"""
embeddings = self.embedding_manager.embeddings
if is_cancelled is None or len(texts) <= _EMBEDDING_CANCEL_BATCH_SIZE:
if is_cancelled is not None and is_cancelled():
return None
return embeddings.embed_documents(texts)
vectors: List[List[float]] = []
for start in range(0, len(texts), _EMBEDDING_CANCEL_BATCH_SIZE):
if is_cancelled():
return None
vectors.extend(
embeddings.embed_documents(
texts[start : start + _EMBEDDING_CANCEL_BATCH_SIZE]
)
)
if is_cancelled():
return None
return vectors
def _prepare_document(
self,
document_id: str,
collection_id: str,
force_reindex: bool,
is_cancelled: Optional[Callable[[], bool]] = None,
) -> Dict[str, Any]:
"""Load, split, and embed without mutating collection state."""
scope_error = _indexing_scope_error()
if scope_error is not None:
return scope_error
with get_user_db_session(self.username, self.db_password) as session:
document = session.query(Document).filter_by(id=document_id).first()
if not document:
return {"status": "error", "error": "Document not found"}
link = (
session.query(DocumentCollection)
.filter_by(document_id=document_id, collection_id=collection_id)
.first()
)
if link is not None and link.indexed and not force_reindex:
return {
"status": "skipped",
"message": "Document already indexed for this collection",
"chunk_count": link.chunk_count,
}
source_fingerprint = document_fingerprint(document)
collection = session.get(Collection, collection_id)
configuration = (
collection_configuration(collection) if collection else None
)
if not document.text_content:
return {
"status": "needs_serial_write",
"source_fingerprint": source_fingerprint,
}
title = document.title or document.filename or "Untitled"
metadata = {
"source": document.original_url,
"document_id": document_id,
"collection_id": collection_id,
"document_title": title,
"title": title,
"authors": document.authors,
"published_date": str(document.published_date)
if document.published_date
else None,
"doi": document.doi,
"arxiv_id": document.arxiv_id,
"pmid": document.pmid,
"pmcid": document.pmcid,
"extraction_method": document.extraction_method,
"word_count": document.word_count,
}
source_doc = LangchainDocument(
page_content=document.text_content, metadata=metadata
)
prep_content_hash = hashlib.sha256(
(document.text_content or "").encode("utf-8")
).hexdigest()
prep_initial_indexed = link.indexed if link is not None else False
prep_had_collection_link = link is not None
# The coordinator's ORM record may be expired by a commit while
# this worker prepares another document. Resolve the index through
# this worker's session so no attribute refresh shares a session
# with the coordinator or another worker, and snapshot the
# identity the status row is keyed to so the write-side re-check
# measures the same predicate (see _status_row_exists).
rag_index = self._resolve_index_for_config(session, collection_id)
prep_status_index_id = (
rag_index.id if rag_index is not None else None
)
prep_status_exists = self._status_row_exists(
session, document_id, collection_id, prep_status_index_id
)
chunks = self.text_splitter.split_documents([source_doc])
chunk_inputs = [
ChunkInput(
text=chunk.page_content,
metadata={**metadata, "chunk_index": i},
)
for i, chunk in enumerate(chunks)
]
vectors_list = self._embed_texts_cancellable(
[chunk.text for chunk in chunk_inputs], is_cancelled
)
if vectors_list is None:
logger.info(
f"Embedding cancelled for document {document_id} "
f"({len(chunk_inputs)} chunks)"
)
return {
"status": "cancelled",
"message": "Cancelled during embedding",
}
vectors = np.asarray(
vectors_list,
dtype="float32",
)
logger.info(
f"Prepared document {document_id}: {len(chunk_inputs)} chunks embedded"
)
return {
"status": "prepared",
"prepared": _PreparedDocument(
document_id=document_id,
collection_id=collection_id,
chunk_inputs=chunk_inputs,
vectors=vectors,
source_fingerprint=source_fingerprint,
collection_configuration=configuration,
content_hash=prep_content_hash,
initial_indexed=prep_initial_indexed,
status_exists=prep_status_exists,
status_index_id=prep_status_index_id,
had_collection_link=prep_had_collection_link,
),
}
def _write_prepared_document(
self, prepared: _PreparedDocument
) -> Dict[str, Any]:
"""Publish prepared work, recovering confirmed component corruption once."""
scope_error = _indexing_scope_error()
if scope_error is not None:
return scope_error
# Recovery resets indexed/status snapshots. Re-read and prepare the
# source on retry rather than publishing the now-stale prepared work.
return self._run_vector_write(
prepared.collection_id,
lambda retry: (
self._index_document_locked(
prepared.document_id, prepared.collection_id, True
)
if retry
else self._write_prepared_document_once(prepared)
),
)
def _write_prepared_document_once(
self, prepared: _PreparedDocument
) -> Dict[str, Any]:
"""Write prepared work while the caller holds the collection lock."""
scope_error = _indexing_scope_error()
if scope_error is not None:
return scope_error
document_id = prepared.document_id
collection_id = prepared.collection_id
chunks = prepared.chunk_inputs
with get_user_db_session(self.username, self.db_password) as session:
# Embedding runs outside the collection lock. A complete
# rebuild may have published a different configuration while
# this document was being prepared. Reject that stale work
# before any write or recovery flag can touch the new index.
if prepared.source_fingerprint is not None:
document = session.get(Document, document_id)
if (
document is None
or document_fingerprint(document)
!= prepared.source_fingerprint
):
return {
"status": "error",
"error": "Document changed; retry indexing",
}
if prepared.collection_configuration is not None:
collection = session.get(Collection, collection_id)
if (
collection is None
or collection_configuration(collection)
!= prepared.collection_configuration
or (
collection.embedding_model is not None
and not self._matches_collection_configuration(
collection
)
)
):
return {
"status": "error",
"error": "Collection configuration changed; retry indexing",
}
try:
# Phase 3 Revalidation Gate: verify collection link, content, and indexed status.
# The membership check runs unconditionally so legacy
# prepared objects without a content_hash snapshot still
# get first-time vs concurrent-unlink handling instead of
# skipping the gate entirely.
link = (
session.query(DocumentCollection)
.filter_by(
document_id=document_id,
collection_id=collection_id,
)
.first()
)
if link is None:
if not getattr(prepared, "had_collection_link", None):
# Reconciler case (b): research orphans have
# no membership at prepare. Create it now
# rather than treating absence as a concurrent
# unlink. A missing snapshot (None) preserves
# main's unconditional-create behavior.
link = ensure_in_collection(
session, document_id, collection_id
)
session.flush()
else:
logger.info(
f"Document {document_id} was removed from collection {collection_id} "
"during embedding; aborting Phase 3 persist."
)
self._flag_document_for_reindex(
session, document_id, collection_id
)
return {
"status": "skipped",
"message": "Document removed from collection during embedding",
}
current_doc = (
session.query(Document).filter_by(id=document_id).first()
)
if not current_doc:
logger.info(
f"Document {document_id} was deleted during embedding; "
"aborting Phase 3 persist."
)
self._flag_document_for_reindex(
session, document_id, collection_id
)
return {
"status": "error",
"error": "Document deleted during indexing",
}
if isinstance(getattr(prepared, "content_hash", None), str):
current_hash = hashlib.sha256(
(current_doc.text_content or "").encode("utf-8")
).hexdigest()
if current_hash != prepared.content_hash:
logger.info(
f"Document {document_id} content changed during embedding; "
"aborting persist and flagging for reindex."
)
self._flag_document_for_reindex(
session, document_id, collection_id
)
return {
"status": "stale",
"message": "Document modified during indexing, flagged for reindex",
}
# Same predicate AND the same index identity as
# preparation's snapshot (see _status_row_exists and
# _PreparedDocument.status_index_id). Deriving the
# identity from self.rag_index_record here would
# disagree with preparation whenever that attribute
# lags the resolution — None on a fresh service until
# _get_vector_index sets it below — aborting healthy
# writes as "stale" and deleting surviving status
# rows via _flag_document_for_reindex.
current_status_exists = self._status_row_exists(
session,
document_id,
collection_id,
prepared.status_index_id,
)
if (
isinstance(prepared.initial_indexed, bool)
and isinstance(link.indexed, bool)
and link.indexed != prepared.initial_indexed
) or (
isinstance(prepared.status_exists, bool)
and current_status_exists != prepared.status_exists
):
peer_status_exists = current_status_exists
if (
prepared.initial_indexed is False
and prepared.status_exists is False
and link.indexed is True
and not peer_status_exists
and prepared.status_index_id is None
):
# No matching index existed during preparation.
# A peer may have created its first index and
# completed this document since then; the saved
# None identity cannot observe that new row.
peer_index = self._resolve_index_for_config(
session, collection_id
)
if peer_index is not None:
peer_status_exists = self._status_row_exists(
session,
document_id,
collection_id,
peer_index.id,
)
if (
prepared.initial_indexed is False
and prepared.status_exists is False
and link.indexed is True
and peer_status_exists
):
# Another writer finished this same document while
# we embedded it. The content hash matched above;
# clearing its committed status would lose a valid
# index and make the next sweep count it twice.
return {
"status": "skipped",
"message": "Document indexed by another run during embedding",
"chunk_count": link.chunk_count,
}
logger.info(
f"Document {document_id} indexing status modified during embedding; "
"aborting persist and flagging for reindex."
)
self._flag_document_for_reindex(
session, document_id, collection_id
)
return {
"status": "stale",
"message": "Document indexed state changed during indexing, flagged for reindex",
}
collection_name = f"collection_{collection_id}"
observed_text = current_doc.text_content
observed_hash = current_doc.document_hash
vindex = self._get_vector_index(
collection_id, collection_name, reset_stale_state=True
)
if (
_claim_document_snapshot(
session, document_id, observed_text, observed_hash
)
== 0
):
self._flag_document_for_reindex(
session, document_id, collection_id
)
return {
"status": "stale",
"message": "Document modified during indexing, flagged for reindex",
}
stats = vindex.index_prepared(
source_type="document",
source_id=document_id,
chunks=chunks,
vectors=prepared.vectors,
replace=True,
session=session,
)
timestamp = datetime.now(UTC)
existing = (
session.query(RagDocumentStatus)
.filter_by(
document_id=document_id,
collection_id=collection_id,
)
.first()
)
prior_index_id = existing.rag_index_id if existing else None
prior_chunks = existing.chunk_count if existing else 0
same_index = prior_index_id == self.rag_index_record.id
old_chunks = prior_chunks if same_index else 0
session.merge(
RagDocumentStatus(
document_id=document_id,
collection_id=collection_id,
rag_index_id=self.rag_index_record.id,
chunk_count=len(chunks),
indexed_at=timestamp,
)
)
updated_rows = (
session.query(DocumentCollection)
.filter_by(
document_id=document_id,
collection_id=collection_id,
)
.update(
{
"indexed": True,
"chunk_count": len(chunks),
"last_indexed_at": timestamp,
}
)
)
if isinstance(updated_rows, int) and updated_rows == 0:
# An unlink committed between the Phase-3 gate query
# and these persist writes (the unlink DB phase does
# not hold the FAISS lock). Rolling back avoids
# re-creating status/aggregate rows for a non-member
# and leaves phantom vectors to the unlink's purge.
logger.info(
f"Document {document_id} was removed from collection {collection_id} "
"during persist; aborting Phase 3 commit."
)
safe_rollback(
session,
"library_rag_service._write_prepared_document link vanished",
)
self._flag_document_for_reindex(
session, document_id, collection_id
)
return {
"status": "skipped",
"message": "Document removed from collection during embedding",
}
rag_index = (
session.query(RAGIndex)
.filter_by(id=self.rag_index_record.id)
.first()
)
if rag_index:
rag_index.chunk_count += len(chunks) - old_chunks
if not same_index:
rag_index.total_documents += 1
rag_index.last_updated_at = timestamp
if prior_index_id is not None and not same_index:
prior_index = session.get(RAGIndex, prior_index_id)
if prior_index is not None:
prior_index.chunk_count = max(
0, (prior_index.chunk_count or 0) - prior_chunks
)
prior_index.total_documents = max(
0, (prior_index.total_documents or 0) - 1
)
prior_index.last_updated_at = timestamp
session.commit()
logger.info(
f"Persisted prepared document {document_id}: "
f"{stats.added} vectors added"
)
return {"status": "success", "chunk_count": len(chunks)}
except Exception as exc:
safe_rollback(
session,
"library_rag_service._write_prepared_document",
)
if isinstance(exc, VectorStoreIntegrityError):
raise
self._flag_document_for_reindex(
session, document_id, collection_id
)
logger.exception(
f"Error writing prepared document {document_id}"
)
return {
"status": "error",
"error": f"Operation failed: {type(exc).__name__}",
}
def index_document(
self, document_id: str, collection_id: str, force_reindex: bool = False
) -> Dict[str, Any]:
# Reject before acquiring the collection lock: a caller holding a DB
# write transaction could otherwise deadlock a writer holding this lock.
scope_error = _indexing_scope_error()
if scope_error is not None:
return scope_error
return self._run_vector_write(
collection_id,
lambda retry: self._index_document_locked(
document_id, collection_id, force_reindex or retry
),
)
def _run_vector_write(
self,
collection_id: str,
operation: Callable[[bool], Dict[str, Any]],
) -> Dict[str, Any]:
"""Retry a write after its failed transaction has completely unwound.
Component checks remain lazy: appends never load or deserialise the
complete FAISS corpus (only the segments a write touches are opened),
while the per-write membership cleanup does hash every segment id
file. Only confirmed checksum/membership failures reach recovery;
ordinary I/O and embedding errors retain their existing behavior.
The collection lock covers rollback, quarantine and the fresh retry.
"""
with self._collection_transaction_lock(collection_id):
for retry in (False, True):
try:
return operation(retry)
except VectorStoreIntegrityError:
self.rag_index_record = None
if retry:
return {
"status": "error",
"error": "Operation failed: VectorStoreIntegrityError",
}
try:
# Rollback expires ORM records and the failed scope may
# close its session. Reload instead of dereferencing
# self.rag_index_record from that failed transaction.
with get_user_db_session(
self.username, self.db_password
) as session:
rag_index = self._resolve_index_for_config(
session, collection_id
)
if rag_index is None:
return {
"status": "error",
"error": "Operation failed: VectorStoreIntegrityError",
}
index_path = self._get_index_path(
rag_index.index_hash
)
lock = _get_faiss_write_lock(
self.username, str(index_path)
)
with lock:
self._quarantine_corrupt_index(
index_path,
"vector_segment_integrity_failed",
)
self._reset_index_state_for_rebuild(
collection_id, rag_index
)
except Exception as exc:
logger.exception("Could not recover vector components")
return {
"status": "error",
"error": f"Operation failed: {type(exc).__name__}",
}
raise AssertionError("Vector write retry did not return")
def _index_one(
self, document_id: str, collection_id: str, force_reindex: bool
) -> Dict[str, Any]:
"""Single-doc dispatch seam used by :meth:`index_documents_parallel`.
Default implementation delegates to :meth:`index_document` so production
behaviour is unchanged. Tests and subclasses override this method to
short-circuit the full per-doc pipeline (which would require mocking
every internal collaborator) without losing the prepared/serialized
pipeline in production.
The previous parallel runner detected overrides via
``"index_document" in self.__dict__`` — that only honoured
instance-attribute patches and silently bypassed class-level subclass
overrides. The runner now compares the bound method against the base
class attribute so both instance patches and subclass overrides are
honoured.
"""
return self.index_document(document_id, collection_id, force_reindex)
def _index_document_locked(
self, document_id: str, collection_id: str, force_reindex: bool = False
) -> Dict[str, Any]:
"""
Index a single document into RAG for a specific collection.
Args:
document_id: UUID of the Document to index
collection_id: UUID of the Collection to index for
force_reindex: Whether to force reindexing even if already indexed
Returns:
Dict with status, chunk_count, and any errors
"""
scope_error = _indexing_scope_error()
if scope_error is not None:
return scope_error
# Phase 1: Read & chunk doc
with get_user_db_session(self.username, self.db_password) as session:
# Get the document
document = session.query(Document).filter_by(id=document_id).first()
if not document:
return {"status": "error", "error": "Document not found"}
# A service may have been constructed before a complete rebuild
# published a different model. Check under the collection lock,
# before membership changes, empty-document purges or embedding.
collection = session.get(Collection, collection_id)
if (
collection is not None
and collection.embedding_model is not None
and not self._matches_collection_configuration(collection)
):
return {
"status": "error",
"error": "Collection configuration changed; retry indexing",
}
# Get or create DocumentCollection entry
doc_collection = ensure_in_collection(
session, document_id, collection_id
)
# If doc_collection was newly created in this session, commit it so the link
# exists durably before Phase 2 without holding a write lock during embedding.
# No test-session import is needed here: `in session.new` is
# False for unittest.mock sessions (MagicMock __contains__
# defaults to False), so mocks safely skip the pre-commit.
try:
_is_new_link = (
getattr(session, "new", None) is not None
and doc_collection in session.new
)
except Exception:
_is_new_link = False
if _is_new_link:
try:
session.commit()
except Exception: # allow: silent-exception
logger.debug(
f"Could not pre-commit newly created collection link for {document_id} in {collection_id}"
)
# Check if already indexed for this collection
if doc_collection.indexed and not force_reindex:
return {
"status": "skipped",
"message": "Document already indexed for this collection",
"chunk_count": doc_collection.chunk_count,
}
# Validate text content
if not document.text_content:
# A previously-indexed document now cleared to empty text (e.g.
# a note edited down to whitespace) must have its stale
# chunks/vectors PURGED, not left searchable. The note-edit path
# already set indexed=False, so detect prior chunks directly and
# remove them via the facade's empty-replace.
collection_name = f"collection_{collection_id}"
has_prior = (
session.query(DocumentChunk.id)
.filter_by(
source_type="document",
source_id=document_id,
collection_name=collection_name,
)
.first()
is not None
)
if has_prior:
# Same store-durable-before-DB-commit hazard as the main
# reindex path below, but this branch sits OUTSIDE that
# path's try/except: the empty-replace apply() DURABLY
# removes the prior vectors before the commit here. On
# failure, roll back and flag the document for re-index so
# the reconciler re-runs the purge instead of leaving
# resurrected rows whose vectors are gone (silently
# unsearchable) marked indexed.
try:
vindex = self._get_vector_index(
collection_id,
collection_name,
reset_stale_state=True,
)
vindex.index(
source_type="document",
source_id=document_id,
chunks=[],
replace=True,
session=session,
)
doc_collection.indexed = False
doc_collection.chunk_count = 0
# Clear the canonical RagDocumentStatus row too. Row
# existence is the "indexed" marker get_rag_stats / the
# RAG status route read, so it MUST move with
# DocumentCollection.indexed — a leftover row would
# report this just-purged (now empty, unsearchable)
# document as still indexed with a stale chunk_count.
# Mirrors remove_document_from_rag and the three sibling
# not-indexed paths; the cleared branch was the lone
# exception.
session.query(RagDocumentStatus).filter_by(
document_id=document_id, collection_id=collection_id
).delete(synchronize_session=False)
session.commit()
except Exception as e:
safe_rollback(
session,
"library_rag_service.index_document cleared",
)
if isinstance(e, VectorStoreIntegrityError):
raise
self._flag_document_for_reindex(
session, document_id, collection_id
)
logger.exception(
f"Error purging cleared document {document_id} "
f"for collection {collection_id}"
)
return {
"status": "error",
"error": f"Operation failed: {type(e).__name__}",
}
return {
"status": "cleared",
"message": (
"Document has no text content; prior chunks/"
"vectors purged"
),
"chunk_count": 0,
}
return {
"status": "error",
"error": "Document has no text content",
}
# Replace-on-reindex context: a document being re-indexed (e.g.
# a note whose content changed) has prior chunks with DIFFERENT
# content hashes from the new text. Left alone they accumulate
# in both the DB and the vector store forever — unbounded
# per-edit growth plus stale duplicate search hits.
# ``VectorIndex.index(replace=True)`` below handles this: it
# looks up the source's prior DocumentChunk rows (authoritative,
# queried fresh — not from an ephemeral pre-committed snapshot),
# applies the vector-store removal durably, then deletes those
# rows in the SAME transaction this method already holds open
# (so a failure rolls back together with everything else, never
# orphaning rows or poisoning the shared session).
try:
phase1_content_hash = hashlib.sha256(
(document.text_content or "").encode("utf-8")
).hexdigest()
phase1_doc_hash = document.document_hash
phase1_indexed = doc_collection.indexed
phase1_status_exists = (
session.query(RagDocumentStatus)
.filter_by(
document_id=document_id,
collection_id=collection_id,
rag_index_id=self.rag_index_record.id,
)
.first()
is not None
if self.rag_index_record
else False
)
# Create LangChain Document from text
doc = LangchainDocument(
page_content=document.text_content,
metadata={
"source": document.original_url,
"document_id": document_id, # Add document ID for source linking
"collection_id": collection_id, # Add collection ID
"title": document.title
or document.filename
or "Untitled",
"document_title": document.title
or document.filename
or "Untitled", # Add for compatibility
"authors": document.authors,
"published_date": str(document.published_date)
if document.published_date
else None,
"doi": document.doi,
"arxiv_id": document.arxiv_id,
"pmid": document.pmid,
"pmcid": document.pmcid,
"extraction_method": document.extraction_method,
"word_count": document.word_count,
},
)
# Split into chunks
chunks = self.text_splitter.split_documents([doc])
logger.info(
f"Split document {document_id} into {len(chunks)} chunks"
)
# Get collection name for chunk storage
collection = (
session.query(Collection)
.filter_by(id=collection_id)
.first()
)
# Use collection_<uuid> format for internal storage
collection_name = (
f"collection_{collection_id}" if collection else "unknown"
)
document_title = (
document.title or document.filename or "Untitled"
)
# Mirrors the parent doc's metadata dict built above (source,
# ids, bibliographic fields) so it survives into each
# chunk's ``DocumentChunk.document_metadata`` — this goes
# ONLY to the encrypted DB (never the vector store; see the
# SECURITY INVARIANT in vector_stores/base.py) and future-
# proofs citation/UI features that read per-chunk metadata.
shared_chunk_metadata = {
"source": document.original_url,
"document_id": document_id,
"collection_id": collection_id,
"document_title": document_title,
"title": document_title,
"authors": document.authors,
"published_date": str(document.published_date)
if document.published_date
else None,
"doi": document.doi,
"arxiv_id": document.arxiv_id,
"pmid": document.pmid,
"pmcid": document.pmcid,
"extraction_method": document.extraction_method,
"word_count": document.word_count,
}
chunk_inputs = [
ChunkInput(
text=chunk.page_content,
metadata={
**shared_chunk_metadata,
"chunk_index": i,
},
)
for i, chunk in enumerate(chunks)
]
# Roll back uncommitted changes (such as ensure_in_collection staging
# and autoflush from query(Collection)) so no SQLite transaction
# or write lock is held during Phase 2 embedding.
safe_rollback(
session, "library_rag_service.index_document phase 1"
)
except Exception as e:
# The session is shared (thread-local) with the caller.
# If session.flush() or session.commit() raised, the session
# is in PendingRollbackError state until rolled back —
# leaving subsequent operations to cascade. Roll back BEFORE
# returning the error dict so the caller sees a clean
# session. (Same pattern as the #3827 fix.)
safe_rollback(session, "library_rag_service.index_document")
if isinstance(e, VectorStoreIntegrityError):
raise
# Backstop for the store-durable-before-DB-commit window: a
# REPLACE reindex ran store.apply() (DURABLY removing this
# source's prior vectors) before the DB commit, so the rollback
# above resurrects rows whose vectors are already gone while
# reverting indexed→its pre-attempt True. Flag for re-index so
# the reconciler re-embeds and store+DB reconverge.
self._flag_document_for_reindex(
session, document_id, collection_id
)
logger.exception(
f"Error indexing document {document_id} for collection {collection_id}"
)
return {
"status": "error",
"error": f"Operation failed: {type(e).__name__}",
}
# Phase 2: Embed vectors outside any DB session
try:
texts = [c.text for c in chunk_inputs]
vectors = (
np.asarray(
self.embedding_manager.embeddings.embed_documents(texts),
dtype="float32",
)
if texts
else None
)
except Exception as e:
logger.exception(
f"Error embedding document {document_id} for collection {collection_id}"
)
with get_user_db_session(
self.username, self.db_password
) as session:
self._flag_document_for_reindex(
session, document_id, collection_id
)
return {
"status": "error",
"error": f"Operation failed: {type(e).__name__}",
}
# Phase 3: Open short session to persist chunks, apply vectors, and commit
with get_user_db_session(self.username, self.db_password) as session:
try:
# Phase 3 Revalidation Gate: verify collection link, content, and indexed status
link = (
session.query(DocumentCollection)
.filter_by(
document_id=document_id,
collection_id=collection_id,
)
.first()
)
if link is None:
logger.info(
f"Document {document_id} was removed from collection {collection_id} "
"during embedding; aborting Phase 3 persist."
)
self._flag_document_for_reindex(
session, document_id, collection_id
)
return {
"status": "skipped",
"message": "Document removed from collection during embedding",
}
current_doc = (
session.query(Document).filter_by(id=document_id).first()
)
if not current_doc:
logger.info(
f"Document {document_id} was deleted during embedding; "
"aborting Phase 3 persist."
)
self._flag_document_for_reindex(
session, document_id, collection_id
)
return {
"status": "error",
"error": "Document deleted during indexing",
}
current_content_hash = hashlib.sha256(
(current_doc.text_content or "").encode("utf-8")
).hexdigest()
if (
current_content_hash != phase1_content_hash
or current_doc.document_hash != phase1_doc_hash
):
logger.info(
f"Document {document_id} content changed during embedding; "
"aborting persist and flagging for reindex."
)
self._flag_document_for_reindex(
session, document_id, collection_id
)
return {
"status": "stale",
"message": "Document modified during indexing, flagged for reindex",
}
current_status_exists = (
session.query(RagDocumentStatus)
.filter_by(
document_id=document_id,
collection_id=collection_id,
rag_index_id=self.rag_index_record.id,
)
.first()
is not None
if self.rag_index_record
else False
)
if (
isinstance(link.indexed, bool)
and isinstance(phase1_indexed, bool)
and link.indexed != phase1_indexed
) or (
isinstance(current_status_exists, bool)
and isinstance(phase1_status_exists, bool)
and current_status_exists != phase1_status_exists
):
logger.info(
f"Document {document_id} indexing status modified during embedding; "
"aborting persist and flagging for reindex."
)
self._flag_document_for_reindex(
session, document_id, collection_id
)
return {
"status": "stale",
"message": "Document indexed state changed during indexing, flagged for reindex",
}
observed_text = current_doc.text_content
observed_hash = current_doc.document_hash
vindex = self._get_vector_index(
collection_id, collection_name, reset_stale_state=True
)
if (
_claim_document_snapshot(
session, document_id, observed_text, observed_hash
)
== 0
):
self._flag_document_for_reindex(
session, document_id, collection_id
)
return {
"status": "stale",
"message": "Document modified during indexing, flagged for reindex",
}
if hasattr(vindex, "index_prepared"):
index_stats = vindex.index_prepared(
source_type="document",
source_id=document_id,
chunks=chunk_inputs,
vectors=vectors,
replace=True,
session=session,
)
else:
index_stats = vindex.index(
source_type="document",
source_id=document_id,
chunks=chunk_inputs,
replace=True,
session=session,
)
logger.info(
f"Vector index update for document {document_id}: "
f"{index_stats.added} added, {index_stats.removed} "
f"removed ({index_stats.chunks} chunks total)"
)
# Check if document was already indexed (for stats update)
existing_status = (
session.query(RagDocumentStatus)
.filter_by(
document_id=document_id,
collection_id=collection_id,
)
.first()
)
prior_index_id = (
existing_status.rag_index_id if existing_status else None
)
prior_chunk_count = (
existing_status.chunk_count if existing_status else 0
)
was_already_indexed = prior_index_id == self.rag_index_record.id
old_chunk_count = (
prior_chunk_count if was_already_indexed else 0
)
# Mark document as indexed using rag_document_status table
# Row existence = indexed, simple and clean
timestamp = datetime.now(UTC)
# Create or update RagDocumentStatus using ORM merge (atomic upsert)
rag_status = RagDocumentStatus(
document_id=document_id,
collection_id=collection_id,
rag_index_id=self.rag_index_record.id,
chunk_count=len(chunks),
indexed_at=timestamp,
)
session.merge(rag_status)
logger.info(
f"Marked document as indexed in rag_document_status: doc_id={document_id}, coll_id={collection_id}, chunks={len(chunks)}"
)
# Also update DocumentCollection table for backward compatibility
_serial_updated = (
session.query(DocumentCollection)
.filter_by(
document_id=document_id,
collection_id=collection_id,
)
.update(
{
"indexed": True,
"chunk_count": len(chunks),
"last_indexed_at": timestamp,
}
)
)
if isinstance(_serial_updated, int) and _serial_updated == 0:
# An unlink committed between the Phase-3 gate query and
# these persist writes. Roll back the staged status merge
# above so no non-member row/aggregate is resurrected.
logger.info(
f"Document {document_id} was removed from collection {collection_id} "
"during persist; aborting Phase 3 commit."
)
safe_rollback(
session,
"library_rag_service.index_document link vanished",
)
self._flag_document_for_reindex(
session, document_id, collection_id
)
return {
"status": "skipped",
"message": "Document removed from collection during embedding",
}
logger.info(
"Also updated DocumentCollection.indexed for backward compatibility"
)
# Keep the aggregate synchronized on both first index and
# replacement reindex. A replacement changes the per-document
# row above, so apply its new-old delta instead of skipping the
# aggregate update entirely.
rag_index_obj = (
session.query(RAGIndex)
.filter_by(id=self.rag_index_record.id)
.first()
)
if rag_index_obj:
chunk_delta = len(chunks) - old_chunk_count
rag_index_obj.chunk_count += chunk_delta
if not was_already_indexed:
rag_index_obj.total_documents += 1
rag_index_obj.last_updated_at = datetime.now(UTC)
logger.info(
"Updated RAGIndex stats: "
f"chunk_count {chunk_delta:+d}, "
f"total_documents {'+1' if not was_already_indexed else '+0'}"
)
if prior_index_id is not None and not was_already_indexed:
prior_index = session.get(RAGIndex, prior_index_id)
if prior_index is not None:
prior_index.chunk_count = max(
0,
(prior_index.chunk_count or 0) - prior_chunk_count,
)
prior_index.total_documents = max(
0, (prior_index.total_documents or 0) - 1
)
prior_index.last_updated_at = timestamp
# Flush ORM changes to database before commit
session.flush()
logger.info(f"Flushed ORM changes for document {document_id}")
# Commit the transaction. Durability is provided by
# synchronous=NORMAL (sqlcipher_utils.py); SQLite
# auto-checkpoints WAL at wal_autocheckpoint=250 frames.
# An explicit PRAGMA wal_checkpoint(FULL) here used to
# block other writers long enough to exhaust busy_timeout
# under bulk-download concurrency (#4197).
session.commit()
logger.info(
f"Successfully indexed document {document_id} for collection {collection_id} "
f"with {len(chunks)} chunks"
)
return {
"status": "success",
"chunk_count": len(chunks),
}
except Exception as e:
# The session is shared (thread-local) with the caller.
# If session.flush() or session.commit() raised, the session
# is in PendingRollbackError state until rolled back —
# leaving subsequent operations to cascade. Roll back BEFORE
# returning the error dict so the caller sees a clean
# session. (Same pattern as the #3827 fix.)
safe_rollback(session, "library_rag_service.index_document")
if isinstance(e, VectorStoreIntegrityError):
raise
# Backstop for the store-durable-before-DB-commit window: a
# REPLACE reindex ran store.apply() (DURABLY removing this
# source's prior vectors) before the DB commit, so the rollback
# above resurrects rows whose vectors are already gone while
# reverting indexed→its pre-attempt True. Flag for re-index so
# the reconciler re-embeds and store+DB reconverge.
self._flag_document_for_reindex(
session, document_id, collection_id
)
logger.exception(
f"Error indexing document {document_id} for collection {collection_id}"
)
return {
"status": "error",
"error": f"Operation failed: {type(e).__name__}",
}
def index_all_documents(
self,
collection_id: str,
force_reindex: bool = False,
progress_callback=None,
) -> Dict[str, Any]:
"""
Index all documents in a collection into RAG.
Args:
collection_id: UUID of the collection to index
force_reindex: Whether to force reindexing already indexed documents
progress_callback: Optional callback function called after each document with (current, total, doc_title, status)
Returns:
Dict with counts of successful, skipped, and failed documents.
Inside an existing ``get_user_db_session`` block on this thread
it indexes nothing and returns ``status`` ``"error"`` with zero
counts.
"""
scope_error = _indexing_scope_error()
if scope_error is not None:
# Reject before the read scope below: nested in the caller's
# scope, its exception cleanup would roll back the caller's
# Session.
return {
**scope_error,
"successful": 0,
"skipped": 0,
"failed": 0,
"errors": [],
}
with get_user_db_session(self.username, self.db_password) as session:
# Get all DocumentCollection entries for this collection
query = session.query(DocumentCollection).filter_by(
collection_id=collection_id
)
if not force_reindex:
# Only index documents that haven't been indexed yet
query = query.filter_by(indexed=False)
# Materialize the values needed by the loop before leaving the
# read scope. A thread-local session is reused by nested calls;
# keeping this scope open during index_document would retain its
# connection throughout splitting, embedding, and callbacks.
doc_info = []
for doc_collection in query.all():
document_id = doc_collection.document_id
document = (
session.query(Document).filter_by(id=document_id).first()
)
doc_info.append(
(document_id, document.title if document else "Unknown")
)
if not doc_info:
return {
"status": "info",
"message": "No documents to index",
"successful": 0,
"skipped": 0,
"failed": 0,
}
results = {"successful": 0, "skipped": 0, "failed": 0, "errors": []}
total = len(doc_info)
for idx, (document_id, title) in enumerate(doc_info, 1):
result = self.index_document(
document_id, collection_id, force_reindex
)
if result["status"] == "success":
results["successful"] += 1
elif result["status"] in ("skipped", "cleared"):
# "cleared" (a previously-indexed doc emptied to no text,
# its stale vectors purged) is a handled non-failure, not an
# error — counting it in "failed" would surface a blank-error
# failure for a correct purge.
results["skipped"] += 1
else:
results["failed"] += 1
results["errors"].append(
{
"doc_id": document_id,
"title": title,
"error": result.get("error"),
}
)
# Call progress callback if provided
if progress_callback:
progress_callback(idx, total, title, result["status"])
logger.info(
f"Indexed collection {collection_id}: "
f"{results['successful']} successful, "
f"{results['skipped']} skipped, "
f"{results['failed']} failed"
)
return results
def remove_document_from_rag(
self, document_id: str, collection_id: str
) -> Dict[str, Any]:
with _hold_collection_lock(
self.username, collection_id, purpose="transaction"
):
return self._remove_document_from_rag_locked(
document_id, collection_id
)
def _remove_document_from_rag_locked(
self, document_id: str, collection_id: str
) -> Dict[str, Any]:
"""
Remove a document's chunks from RAG for a specific collection.
Args:
document_id: UUID of the Document to remove
collection_id: UUID of the Collection to remove from
Returns:
Dict with status and count of removed chunks
"""
with get_user_db_session(self.username, self.db_password) as session:
# Get the DocumentCollection entry
doc_collection = (
session.query(DocumentCollection)
.filter_by(document_id=document_id, collection_id=collection_id)
.first()
)
if not doc_collection:
return {
"status": "error",
"error": "Document not found in collection",
}
try:
# Get collection name in the format collection_<uuid>
collection = (
session.query(Collection)
.filter_by(id=collection_id)
.first()
)
# Use collection_<uuid> format for internal storage
collection_name = (
f"collection_{collection_id}" if collection else "unknown"
)
# Remove the document's vectors from the FAISS index FIRST.
# ``remove_documents_from_index`` -> ``VectorIndex.delete``
# looks up the DocumentChunk rows by (source_type, source_id,
# collection_name) to learn which FAISS int ids to remove,
# and deletes those matching rows itself as part of the same
# operation. If the DB rows were deleted first, that lookup
# would find nothing and the vectors (and their persisted
# text) would be stranded in the FAISS store forever — never
# removed and never re-discoverable by a later cleanup.
# Best-effort: a FAISS hiccup must not fail the DB removal
# below.
# ``remove_documents_from_index`` deletes the matching chunk
# rows itself (one row per removed vector) and returns that
# count. Capture it so the reported ``deleted_count`` reflects
# the rows removed here, not just the backstop sweep below: in
# the normal path those rows are already gone by the time the
# backstop runs, so the backstop returns ~0 and — left
# uncounted — would under-report the removal (often as 0) to
# the caller/UI.
removed_vectors = 0
try:
removed_vectors = self.remove_documents_from_index(
[document_id], collection_id
)
except Exception:
logger.exception(
f"Could not remove document {document_id} vectors "
f"from FAISS index for collection {collection_id}"
)
# DB-only cleanup for any rows ``remove_documents_from_index``
# did not match (e.g. no current FAISS index for this
# collection). Disjoint from ``removed_vectors`` above (those
# rows are already committed-deleted), so the two sum to the
# true total removed.
deleted_count = removed_vectors + (
self.embedding_manager._delete_chunks_from_db(
collection_name=collection_name,
source_id=document_id,
)
)
# Update DocumentCollection RAG status
doc_collection.indexed = False
doc_collection.chunk_count = 0
doc_collection.last_indexed_at = None
# Clear the canonical RagDocumentStatus row too. Row-existence is
# the "indexed" marker get_rag_stats / the RAG status route read,
# so it MUST move together with DocumentCollection.indexed — a
# leftover row would report the just-removed document as still
# indexed.
session.query(RagDocumentStatus).filter_by(
document_id=document_id, collection_id=collection_id
).delete(synchronize_session=False)
session.commit()
logger.info(
f"Removed {deleted_count} chunks for document {document_id} from collection {collection_id}"
)
return {"status": "success", "deleted_count": deleted_count}
except Exception as e:
# session.commit() above can raise; without rollback the
# shared thread-local session stays poisoned for the
# caller's next operation (issue #3827 pattern).
safe_rollback(
session, "library_rag_service.remove_document_from_rag"
)
# Backstop for the store-durable-before-DB-commit window:
# remove_documents_from_index -> VectorIndex.delete ran
# store.apply() (DURABLY removing this document's vectors) BEFORE
# the DB status work above committed, so the rollback can leave
# the row still marked indexed=True with its vectors already gone
# -- indexed-but-unsearchable, and over-reported as indexed by
# get_rag_stats with no auto-recovery. Durably COMPLETE the
# removal's status change so the DB matches the removed vectors:
# mark it not-indexed and drop the canonical RagDocumentStatus
# row. This is a REMOVAL backstop, not a re-index one (contrast
# index_document's _flag_document_for_reindex) -- the vectors are
# intentionally gone, so we finish the removal rather than
# resurrect the document. Best-effort: a retry of the removal
# reconciles it if this too fails.
try:
session.query(DocumentCollection).filter_by(
document_id=document_id, collection_id=collection_id
).update(
{
"indexed": False,
"chunk_count": 0,
"last_indexed_at": None,
},
synchronize_session=False,
)
session.query(RagDocumentStatus).filter_by(
document_id=document_id, collection_id=collection_id
).delete(synchronize_session=False)
session.commit()
except Exception:
safe_rollback(
session,
"library_rag_service.remove_document_from_rag backstop",
)
logger.warning(
f"Could not finalize removal state for document "
f"{document_id} in collection {collection_id}; a retry "
"of the removal will reconcile it."
)
logger.exception(
f"Error removing document {document_id} from collection {collection_id}"
)
return {
"status": "error",
"error": f"Operation failed: {type(e).__name__}",
}
def purge_document_chunks(
self, document_id: str, collection_id: str
) -> int:
with _hold_collection_lock(
self.username, collection_id, purpose="transaction"
):
return self._purge_document_chunks_locked(
document_id, collection_id
)
def _purge_document_chunks_locked(
self, document_id: str, collection_id: str
) -> int:
"""Delete a document's chunk rows from a collection's RAG store
WITHOUT requiring the ``DocumentCollection`` join row to still exist.
``remove_document_from_rag`` short-circuits (returns "Document not
found in collection") when the join row is gone — which is exactly
the state after a ``Document`` is cascade-deleted. Callers that
delete the Document first (note deletion) must use this to actually
purge the now-orphaned ``DocumentChunk`` rows; otherwise the chunks
(and their embedding ids) linger and semantic search keeps
resolving hits to a Document row that no longer exists.
Mirrors the chunk-delete half of ``remove_document_from_rag``.
FAISS-vector pruning is NOT done here: pair this with
``purge_document_vectors`` when the document is being deleted
outright — replace-on-reindex can never fire again for a deleted
document id. Returns the number of chunk rows deleted.
"""
collection_name = f"collection_{collection_id}"
return self.embedding_manager._delete_chunks_from_db(
collection_name=collection_name,
source_id=document_id,
)
def purge_document_vectors(
self, document_id: str, collection_id: str
) -> int:
with _hold_collection_lock(
self.username, collection_id, purpose="transaction"
):
return self._purge_document_vectors_locked(
document_id, collection_id
)
def _purge_document_vectors_locked(
self, document_id: str, collection_id: str
) -> int:
"""Remove a deleted document's chunk vectors from the collection's
vector store.
Companion to ``purge_document_chunks`` for callers that delete the
``Document`` row itself (note deletion). Without this the vectors
lingered until a replace-on-reindex of the SAME document id — which
can never fire again once the document is deleted — so collection
search kept serving the deleted content indefinitely.
Routes to ``VectorIndex.delete(source_type="document",
source_id=document_id)``. Unlike the pre-cutover implementation,
no separate "shared chunk ownership" check is needed here: the new
store is one-row-per-source (see the "One row = one vector" note in
vector_stores/facade.py) — identical text in two documents gets two
independent rows/vectors, so deleting this document's rows can
never remove another document's vector.
Deliberately does NOT go through ``_get_vector_index`` /
``_get_or_create_rag_index``: a deletion path must not create an
index record (or probe the embedding provider) just to delete from
it, and does not quarantine/rebuild on a failed load — an
unreadable index has nothing purgeable right now; quarantine/
rebuild decisions stay with the indexing paths.
Returns the number of vectors removed.
"""
return self.purge_documents_vectors([document_id], collection_id)
def purge_documents_vectors(
self, document_ids: List[str], collection_id: str
) -> int:
"""Purge every historical configuration, once per physical index."""
if not document_ids:
return 0
# Verification can recover an interrupted vector checkpoint. Wait for
# an active writer's database commit before deciding recovery is needed,
# just as single-document deletion and search do.
with _hold_collection_lock(
self.username, collection_id, purpose="transaction"
):
return self._purge_documents_vectors_locked(
document_ids, collection_id
)
def _purge_documents_vectors_locked(
self, document_ids: List[str], collection_id: str
) -> int:
collection_name = f"collection_{collection_id}"
with get_user_db_session(self.username, self.db_password) as session:
indices = (
session.query(RAGIndex)
.filter_by(
collection_name=collection_name,
)
.all()
)
return sum(
self._purge_index_documents(index, document_ids)
for index in indices
)
def _purge_index_documents(
self, rag_index: RAGIndex, document_ids: List[str]
) -> int:
collection_name = rag_index.collection_name
# Resolve where the file ACTUALLY lives, the way the index/search paths
# do — but without _preflight's side effects (this deletion path must
# not relocate/record/create). rag_index.index_path is the authoritative
# DB record (the legacy shared-cache path pre-migration, the per-user
# path after _preflight relocates it); _get_index_path(index_hash) only
# recomputes the POST-migration location. Checking only the recomputed
# path silently no-ops on an un-migrated install — the file is still at
# the legacy index_path, so the deleted document's real vector survives.
recomputed_path = self._get_index_path(rag_index.index_hash)
recorded_path = (
Path(rag_index.index_path) if rag_index.index_path else None
)
if recorded_path is not None and recorded_path.exists():
index_path = recorded_path
elif recomputed_path.exists():
index_path = recomputed_path
else:
return 0
verified, reason = self.integrity_manager.verify_file(index_path)
if not verified:
# Leave quarantine/rebuild decisions to the indexing paths;
# an unreadable index has nothing purgeable right now.
logger.warning(
"Skipping document vector purge: index "
f"{index_path} fails verification ({reason})"
)
return 0
lock = _get_faiss_write_lock(self.username, str(index_path))
# nested=True: these run reentrantly inside VectorIndex.apply(), which
# holds just-flushed, uncommitted DocumentChunk rows on this same
# thread-local session. The integrity write must run in a SAVEPOINT and
# let apply()'s caller commit — a plain commit/rollback here would
# settle or DISCARD those pending rows (silently losing indexed text
# while the vectors persist). See FileIntegrityManager._integrity_write.
def _record(path: Path) -> None:
self.integrity_manager.record_file(
path,
related_entity_type="rag_index",
related_entity_id=rag_index.id,
nested=True,
)
def _verify(path: Path):
return self.integrity_manager.verify_file(path, nested=True)
try:
vindex = VectorIndex(
username=self.username,
db_password=self.db_password,
# Delete-only path: never materialise the embedding backend.
# VectorIndex.delete() resolves rows by id and never calls
# embed_*; forcing the model here would cost seconds + hundreds
# of MB of RSS per deleted document for nothing.
embeddings=_LazyEmbeddings(self.embedding_manager),
embedding_model=rag_index.embedding_model,
embedding_model_type=EmbeddingProvider(
rag_index.embedding_model_type
),
collection_name=collection_name,
index_key=rag_index.index_hash,
require_document_membership=True,
dimension=rag_index.embedding_dimension,
path=index_path,
lock=lock,
integrity_record=_record,
integrity_verify=_verify,
# Use the STORED index config, not the service instance's — a
# service built with defaults (index_type="flat") would evaluate
# supports_delete wrongly for an HNSW collection and silently
# fail the removal. NULL (legacy rows) falls back to self.*.
index_type=rag_index.index_type or self.index_type,
metric=rag_index.distance_metric or self.distance_metric,
normalize=(
rag_index.normalize_vectors
if rag_index.normalize_vectors is not None
else self.normalize_vectors
),
)
stats = vindex.delete_sources(
source_type="document", source_ids=document_ids
)
except (ValueError, RuntimeError, OSError):
# OSError too: this is a BEST-EFFORT purge whose caller goes on to
# delete the DocumentChunk rows. A disk error from the FAISS
# persist() (OSError) must not escape and abort that row deletion —
# it would strand the chunk rows while leaving the vectors, the
# opposite inconsistency. Skip the vector purge and let the caller
# proceed; the next write or reconciliation removes orphan vectors.
logger.warning(
"Skipping document vector purge: could "
f"not load or update index {index_path}"
)
return 0
return stats.removed
def index_documents_batch(
self,
doc_info: List[tuple],
collection_id: str,
force_reindex: bool = False,
) -> Dict[str, Dict[str, Any]]:
"""
Index multiple documents in a batch for a specific collection.
Args:
doc_info: List of (doc_id, title) tuples
collection_id: UUID of the collection to index for
force_reindex: Whether to force reindexing even if already indexed
Returns:
Dict mapping doc_id to individual result. Inside an existing
``get_user_db_session`` block on this thread every result is the
scope error and nothing is read or indexed.
"""
scope_error = _indexing_scope_error()
if scope_error is not None:
# Reject before the read scope below, for the same reason as
# index_all_documents.
return {doc_id: dict(scope_error) for doc_id, _title in doc_info}
results = {}
doc_ids = [doc_id for doc_id, _ in doc_info]
# Use one short read scope to collect only scalar state. Keep the
# potentially slow per-document operations outside this scope.
with get_user_db_session(self.username, self.db_password) as session:
# Pre-load all documents for this batch
documents = (
session.query(Document).filter(Document.id.in_(doc_ids)).all()
)
# Create lookup for quick access
existing_doc_ids = {doc.id for doc in documents}
# Pre-load DocumentCollection entries
doc_collections = (
session.query(DocumentCollection)
.filter(
DocumentCollection.document_id.in_(doc_ids),
DocumentCollection.collection_id == collection_id,
)
.all()
)
doc_collection_lookup = {
dc.document_id: (dc.indexed, dc.chunk_count)
for dc in doc_collections
}
# Process each document after the read scope releases its connection.
for doc_id, title in doc_info:
if doc_id not in existing_doc_ids:
results[doc_id] = {
"status": "error",
"error": "Document not found",
}
continue
# Check if already indexed via DocumentCollection
doc_collection = doc_collection_lookup.get(doc_id)
if doc_collection and doc_collection[0] and not force_reindex:
results[doc_id] = {
"status": "skipped",
"message": "Document already indexed for this collection",
"chunk_count": doc_collection[1],
}
continue
# Do NOT short-circuit empty text_content here: a document/note
# edited down to empty still has its PRIOR chunks + vectors on
# disk, and only index_document's empty-content branch purges
# them (via an empty-replace). Returning an "error" here left
# that stale (plaintext) content permanently searchable through
# the bulk "Index All" path — and self-perpetuating, since the
# doc's indexed flag never flips. Route it through index_document
# so the batch path gets the same purge-on-clear as the SSE /
# single-document paths; it returns "cleared" (purged) or the
# same "error" when there were no prior chunks.
try:
result = self.index_document(
doc_id, collection_id, force_reindex
)
results[doc_id] = result
except Exception as e:
logger.exception(f"Error indexing document {doc_id} in batch")
results[doc_id] = {
"status": "error",
"error": f"Indexing failed: {type(e).__name__}",
}
return results
def rebuild_collection(
self,
doc_info,
collection_id,
*,
max_workers=4,
progress_callback=None,
is_cancelled=None,
):
"""Replace the complete collection only after every document is ready."""
scope_error = _indexing_scope_error()
if scope_error is not None:
raise RuntimeError(scope_error["error"])
with _hold_collection_lock(
self.username, collection_id, purpose="rebuild"
):
with CollectionRebuild(
self,
collection_id,
doc_info,
session_factory=lambda: get_user_db_session(
self.username, self.db_password
),
) as rebuild:
aggregate = self.index_documents_parallel(
doc_info,
collection_id,
force_reindex=True,
max_workers=max_workers,
progress_callback=progress_callback,
is_cancelled=is_cancelled,
_rebuild=rebuild,
)
if aggregate["cancelled"]:
return aggregate
if aggregate["failed"]:
raise RuntimeError(
"Collection rebuild failed; the previous index was preserved"
)
try:
rebuild.publish(is_cancelled)
except RebuildCancelled:
aggregate["cancelled"] = True
return aggregate
def index_documents_parallel(
self,
doc_info: List[Tuple[str, str]],
collection_id: str,
force_reindex: bool = False,
max_workers: int = 4,
progress_callback: Optional[
Callable[[int, int, str, str], None]
] = None,
is_cancelled: Optional[Callable[[], bool]] = None,
*,
_rebuild: CollectionRebuild | None = None,
) -> Dict[str, Any]:
"""
Index many documents concurrently with bounded fan-out.
Each per-document task runs the prepared pipeline
(:meth:`_prepare_document` for load/split/embed, then the
coordinator's serialized durable write) unless a subclass overrides
:meth:`_index_one` or :meth:`index_document`, in which case that
per-doc path is invoked directly — the per-doc logic (split, embed,
persist chunks, FAISS-merge-under-lock, mark indexed, update stats)
is unchanged. The bounded fan-out only changes *which* sequential
loop dispatches the work: before this method, six call sites in the
RAG routes (main's ``research_library/routes/rag_routes.py``, now
:mod:`local_deep_research.web.routers.rag`) and the background
reconciler in :mod:`scheduler.background` each did this one doc at
a time. The slow embedding round-trip (outside the FAISS write
lock) is now overlapped across documents.
Concurrency invariants this method relies on (already true):
* :meth:`index_document` opens a fresh per-thread DB session via
:func:`get_user_db_session` — workers do not share sessions.
* All FAISS mutations go through ``VectorIndex.apply()`` in
:mod:`local_deep_research.vector_stores`, which is only
invoked under the per-(username, index_path) write lock
returned by :func:`_get_faiss_write_lock`. The service passes
that lock into the vector-store facade at the call sites
around L422, L879, L1097, and L2025, so concurrent
``index_document`` workers serialise their FAISS appends on
the same lock without any extra coordination here.
* ``LocalEmbeddingManager.embeddings`` uses double-checked
locking for first-load.
* ``is_cancelled`` is polled between completions AND between
submissions. The bounded-submission loop admits new work into
the pool only when ``is_cancelled()`` returns False, and
each :func:`_run_one` worker re-checks ``is_cancelled()``
immediately before delegating to ``index_document``. This
closes the false-poll-to-submit gap (the cancel signal can
be set between the main thread's poll and ``pool.submit()``)
so post-cancel starts are zero by construction. The final
``is_cancelled()`` poll in the ``finally`` block also
preserves ``cancelled=True`` in the aggregate when the
signal lands while the last in-flight worker is running.
* In-flight embedding batches cannot be interrupted (Python
has no safe way to kill an HTTP round-trip or a
SentenceTransformer forward pass mid-array) — but
``_prepare_document`` embeds in bounded batches
(``_EMBEDDING_CANCEL_BATCH_SIZE``) with an ``is_cancelled()``
check between them, so the uncancellable tail is one batch,
not the whole document. The helper returns via
``pool.shutdown(wait=True)`` after in-flight batches finish
naturally.
Args:
doc_info: List of ``(doc_id, title)`` pairs to index.
collection_id: UUID of the collection.
force_reindex: Forwarded to :meth:`index_document`.
max_workers: Bound on the size of the
``ThreadPoolExecutor`` — i.e. how many documents can be
**preparing** concurrently (load + split + embed). It does
NOT bound the prepared-but-unwritten backlog: completed
futures hold their full vector batches in memory until the
coordinator's serial write stage picks them up, so for very
large batches the resident memory footprint can exceed what
``max_workers`` alone suggests. Embedding is the slow stage
in practice, so this is acceptable for the default 4-worker
fan-out; a caller with many large documents should either
shrink ``max_workers`` or chunk the submission. ``1`` falls
back to fully sequential behaviour (still useful when a
flaky network makes concurrent httpx calls worse than
serial). Default 4.
progress_callback: Optional hook called once per completed
document with ``(completed, total, title, status)`` —
matches the legacy shape used by
:meth:`index_all_documents` so existing UI progress
paths keep working.
is_cancelled: Optional zero-arg callable polled between
completions AND between submissions. When it returns
``True``, no further work is admitted into the pool;
in-flight futures finish naturally. The executor is
always shut down with ``wait=True`` so no worker can
outlive the caller's service context.
Returns:
``{"successful": int, "skipped": int, "failed": int,
"errors": [...], "results": {doc_id: {...}},
"cancelled": bool, "total": int}``. Inside an existing
``get_user_db_session`` block on this thread nothing is loaded,
embedded or written and no callback runs: every document fails
with the scope error.
"""
scope_error = _indexing_scope_error()
if scope_error is not None:
# Pool workers run on their own threads, where this caller's
# scope is invisible to _prepare_document's guard. Without this
# check every document would be loaded and embedded before the
# coordinator rejected its write.
title_lookup = dict(doc_info)
return {
"successful": 0,
"skipped": 0,
"failed": len(title_lookup),
"errors": [
{
"doc_id": doc_id,
"title": title,
"error": scope_error["error"],
}
for doc_id, title in title_lookup.items()
],
"results": {
doc_id: dict(scope_error) for doc_id in title_lookup
},
"cancelled": False,
"total": len(doc_info),
}
if max_workers < 1:
max_workers = 1
total = len(doc_info)
if total == 0:
return {
"successful": 0,
"skipped": 0,
"failed": 0,
"errors": [],
"results": {},
"cancelled": False,
"total": 0,
}
# Title-lookup keyed by doc_id — futures return in ``as_completed``
# order, not submission order, so we cannot rely on positional
# iteration when emitting progress.
title_lookup = dict(doc_info)
results: Dict[str, Dict[str, Any]] = {}
counters = {"successful": 0, "skipped": 0, "failed": 0}
errors: List[Dict[str, Any]] = []
cancelled = False
def _run_one(doc_id: str) -> Dict[str, Any]:
"""Single-doc worker — never raises; returns a status dict."""
try:
if _rebuild is not None:
return _rebuild.prepare(doc_id, is_cancelled)
# Three seams tell us to bypass the prepared/serialized
# pipeline and call the per-doc method directly:
#
# 1. A class-level subclass override of ``_index_one`` —
# detected via
# ``type(self)._index_one is not LibraryRAGService._index_one``
# so it works regardless of whether the override
# has ``__func__`` (the old
# ``self._index_one.__func__ is not LibraryRAGService._index_one``
# check raised AttributeError on instance-attribute
# patches that don't expose ``__func__``).
# 2. A class-level subclass override of the legacy
# ``index_document`` extension point this seam
# replaced — callers that override ``index_document``
# at class level (not just instance-patch it for
# tests) still get the per-doc bypass, otherwise they
# would silently fall through to the prepared
# pipeline and lose the override.
# 3. An instance-level patch of ``_index_one`` or
# ``index_document`` — the legacy seams used by the
# existing parallel-runner tests that mock the
# per-doc method directly.
#
# If none is present, run the prepared pipeline: split
# and embed concurrently, then hand the prepared document
# off to the coordinator for serialized durable writes.
cls = type(self)
if cls._index_one is not LibraryRAGService._index_one:
return self._index_one(doc_id, collection_id, force_reindex)
if cls.index_document is not LibraryRAGService.index_document:
return self.index_document(
doc_id, collection_id, force_reindex
)
if (
"_index_one" in self.__dict__
or "index_document" in self.__dict__
):
return self._index_one(doc_id, collection_id, force_reindex)
prepared_result = self._prepare_document(
doc_id, collection_id, force_reindex, is_cancelled
)
if prepared_result.get("status") == "needs_serial_write":
return self.index_document(
doc_id, collection_id, force_reindex
)
return prepared_result
except Exception as exc:
# ``index_document`` already returns an error dict on its
# own internal failures; this catches only bugs / hook
# breaks outside that contract.
logger.exception(f"Parallel index worker for {doc_id} crashed")
return {
"status": "error",
"error": f"Indexing failed: {type(exc).__name__}",
}
# De-duplicated submission queue preserving input order. The
# underlying ``index_document`` is not idempotent at the DB level
# beyond its own checks; without this guard a buggy caller could
# double-insert chunks from the same doc.
pending_doc_ids: List[str] = []
seen: Set[str] = set()
for doc_id, _title in doc_info:
if doc_id in seen:
continue
seen.add(doc_id)
pending_doc_ids.append(doc_id)
pool = ThreadPoolExecutor(
max_workers=max_workers,
thread_name_prefix="ldr-index-doc-",
)
try:
future_to_doc: Dict[Any, str] = {}
submit_idx = 0
completed = 0
# Bounded-submission loop: poll ``is_cancelled`` BEFORE
# admitting any new work, then submit up to ``max_workers``
# futures, then wait for one completion.
#
# This closes the post-cancel submission leak in the
# previous all-upfront submission model: with the old
# loop, all futures were submitted before the first
# ``is_cancelled()`` poll, so queued futures could be
# picked up by idle workers between the caller's cancel
# signal (e.g. ``_sse_cancel.set()`` in
# ``web/routers/rag.py::index_collection``) and the helper's
# ``pool.shutdown(cancel_futures=True)``. Here, new work
# is admitted only when ``is_cancelled()`` returns False,
# so post-cancel starts are zero by construction.
while future_to_doc or submit_idx < len(pending_doc_ids):
# 1. Cancellation fence: stop submitting new work if
# cancelled. Once we observe cancellation we don't
# re-poll — the gate stays closed until the loop
# drains.
if (
not cancelled
and is_cancelled is not None
and is_cancelled()
):
cancelled = True
logger.info(
f"Parallel indexing cancelled at {completed}/{total}"
)
for f in future_to_doc:
f.cancel()
# 2. Admit new work up to ``max_workers`` in flight
# (skipped once cancelled).
if not cancelled:
while len(future_to_doc) < max_workers and submit_idx < len(
pending_doc_ids
):
if is_cancelled is not None and is_cancelled():
cancelled = True
logger.info(
f"Parallel indexing cancelled during submission at {completed}/{total}"
)
for f in future_to_doc:
f.cancel()
break
doc_id = pending_doc_ids[submit_idx]
submit_idx += 1
future_to_doc[pool.submit(_run_one, doc_id)] = doc_id
# 3. Nothing in flight and nothing left to submit → done.
if not future_to_doc:
break
# 4. Wait for the next completion, then process it.
try:
done_iter = as_completed(list(future_to_doc.keys()))
fut = next(done_iter, None)
except Exception:
logger.exception(
"as_completed failed unexpectedly during parallel indexing"
)
fut = None
if fut is None:
# Iterator short-circuited without yielding — loop
# back. The next iteration's cancel poll / submit
# check will either submit more work or exit.
continue
doc_id = future_to_doc.pop(fut)
try:
result = fut.result()
except CancelledError:
result = {
"status": "skipped",
"message": "Cancelled before submission",
}
except Exception as exc:
logger.exception(
f"Future for doc {doc_id} raised unexpectedly"
)
result = {
"status": "error",
"error": f"Worker crashed: {type(exc).__name__}",
}
status = result.get("status", "error")
prepared = result.get("prepared")
if status == "prepared" and isinstance(
prepared, _PreparedDocument
):
result = (
_rebuild.write(prepared)
if _rebuild is not None
else self._write_prepared_document(prepared)
)
status = result.get("status", "error")
results[doc_id] = result
if status == "success":
counters["successful"] += 1
elif status in ("skipped", "cleared"):
counters["skipped"] += 1
elif status == "cancelled":
# A worker observed the cancel signal mid-document
# (see _prepare_document). Count it as skipped — same
# as "Cancelled before submission" below — and flip
# the aggregate even if the main-thread polls have not
# observed the signal yet.
counters["skipped"] += 1
cancelled = True
else:
counters["failed"] += 1
errors.append(
{
"doc_id": doc_id,
"title": title_lookup.get(doc_id, "Unknown"),
"error": result.get("error"),
}
)
completed += 1
if progress_callback is not None:
try:
progress_callback(
completed,
total,
title_lookup.get(doc_id, "Unknown"),
status,
)
except Exception:
# A buggy callback must not poison the indexing
# run — log and continue.
logger.exception(
"Parallel index progress_callback raised"
)
finally:
if not cancelled and is_cancelled is not None and is_cancelled():
cancelled = True
# Always ``wait=True`` so in-flight workers finish before the
# helper returns. With bounded submission no new work is
# admitted after cancel is observed, so the only in-flight
# work at shutdown is what was already running — these finish
# naturally. ``cancel_futures=cancelled`` is a no-op here
# (no queued futures by construction) but is kept for
# symmetry with other shutdown sites in the codebase and as
# defense-in-depth if a future change relaxes the bounded-
# submission invariant.
pool.shutdown(wait=True, cancel_futures=cancelled)
if cancelled:
# Mark docs that were never submitted (still in the
# pending queue past ``submit_idx``) as skipped. Submitted
# docs all have results — either from processing in the
# loop above or from the ``wait=True`` shutdown drain —
# so we don't need to touch them here.
for doc_id in pending_doc_ids[submit_idx:]:
if doc_id not in results:
results[doc_id] = {
"status": "skipped",
"message": "Cancelled before submission",
}
counters["skipped"] += 1
logger.info(
f"Parallel indexing complete: "
f"{counters['successful']} successful, "
f"{counters['skipped']} skipped, "
f"{counters['failed']} failed"
f"{' (cancelled)' if cancelled else ''}"
)
return {
"successful": counters["successful"],
"skipped": counters["skipped"],
"failed": counters["failed"],
"errors": errors,
"results": results,
"cancelled": cancelled,
"total": total,
}
def reconcile_collection_index(self, collection_id: str) -> Dict[str, Any]:
"""Reconcile indexed flags and stats against durable FAISS membership.
A document is indexed only when it has at least one current-model chunk
row, none were invalidated by text replacement, and every such chunk
id exists in the live FAISS index. Stale status rows are removed and
compatibility flags/stats are rebuilt atomically.
Safety invariant: if the live FAISS index reports zero ids (transient
load error, missing file, on-disk corruption the verifier just
quarantined) but the DB still has DocumentChunk rows for the collection,
we REFUSE to shrink state. The function returns
``{"reconciliation_skipped": True, "reason": "..."}`` and the worker
surfaces this as a task failure rather than clearing every indexed flag
and RagDocumentStatus row. A mass-clear from a transient store fault
would orphan every search hit and require a full re-index to recover.
``RagDocumentStatus.indexed_at`` is preserved for durable docs that
already have a row — only newly durable docs get the current timestamp.
"""
collection_name = f"collection_{collection_id}"
with self._collection_transaction_lock(collection_id):
vindex = self._get_vector_index(
collection_id,
collection_name,
reset_stale_state=False,
# This call site never embeds a query — it only calls
# ``live_ids()`` below — so it gets none of the fail-closed
# dimension check a real search gets for free from
# ``FaissVectorStore._prepare``. Without explicitly opting
# back in here, an embedding-model dimension drift would go
# completely undetected: the file still loads (its stored
# ``dimension`` came from the DB row, which always matches
# ``index.d``), and a non-empty live index means the
# refuse-to-shrink guard below never fires either.
probe_dimension=True,
)
live_ids = set(vindex.live_ids())
rag_index_id = self.rag_index_record.id
with get_user_db_session(
self.username, self.db_password
) as session:
# Serialize this SQLite repair with text invalidation. The
# vector store was initialized above; no nested setup commit
# may release this write lock before flags/status are saved.
session.query(RAGIndex).filter_by(id=rag_index_id).update(
{RAGIndex.id: rag_index_id}, synchronize_session=False
)
chunk_query = (
session.query(
DocumentChunk.id,
DocumentChunk.source_id,
DocumentChunk.document_metadata,
)
.filter_by(
source_type="document",
collection_name=collection_name,
embedding_model=self.embedding_model,
embedding_model_type=EmbeddingProvider(
self.embedding_provider
),
)
# Chunk rows can outlive their document: source_id has
# no foreign key, and the purge after a delete is best
# effort. A status row for such a document would break
# the commit below on RagDocumentStatus's foreign key to
# documents (#6748), so only live documents count.
.filter(
exists().where(Document.id == DocumentChunk.source_id)
)
)
# Refuse-to-shrink guard: a transient empty live_ids while
# chunk rows exist would otherwise mass-clear every indexed
# flag and RagDocumentStatus row, silently killing search
# for every document in the collection. Treat as a
# reconciliation failure; the worker surfaces the skip.
if (
not live_ids
and chunk_query.filter(
*vindex.ownership_filter(include_legacy=True)
).first()
is not None
):
logger.warning(
"reconcile_collection_index: live_ids empty but "
"document chunk rows exist; "
"refusing to clear indexed flags"
)
return {
"reconciliation_skipped": True,
"reason": (
"live vector store reported zero ids while "
"DocumentChunk rows exist; refusing to clear "
"indexed flags"
),
"indexed_documents": 0,
"indexed_chunks": 0,
"live_vectors": 0,
"orphan_vectors": 0,
}
orphan_count = vindex.compact_orphans(session=session)
if orphan_count:
live_ids = set(vindex.live_ids())
# Cleanup adopts legacy rows using actual vector membership.
# Only then count this index's chunks: another configuration's
# still-NULL rows must not make a healthy document incomplete.
rows = chunk_query.filter(*vindex.ownership_filter()).all()
ids_by_document: Dict[str, Set[int]] = {}
invalidated_documents: Set[str] = set()
for chunk_id, source_id, metadata in rows:
if source_id is not None:
ids_by_document.setdefault(str(source_id), set()).add(
int(chunk_id)
)
if (metadata or {}).get("_ldr_text_invalidated"):
invalidated_documents.add(str(source_id))
owned_ids = {i for ids in ids_by_document.values() for i in ids}
durable = {
doc_id: chunk_ids
for doc_id, chunk_ids in ids_by_document.items()
if chunk_ids
and chunk_ids.issubset(live_ids)
and doc_id not in invalidated_documents
}
# Snapshot existing indexed_at BEFORE the bulk delete so
# durable docs that already had a status row keep their
# original timestamp. Only docs newly promoted to durable
# get ``now``.
prior_indexed_at: Dict[str, Any] = {
str(row.document_id): row.indexed_at
for row in session.query(
RagDocumentStatus.document_id,
RagDocumentStatus.indexed_at,
)
.filter(RagDocumentStatus.collection_id == collection_id)
.all()
}
links = (
session.query(DocumentCollection)
.filter_by(collection_id=collection_id)
.all()
)
now = datetime.now(UTC)
for link in links:
chunk_ids = durable.get(str(link.document_id), set())
link.indexed = bool(chunk_ids)
link.chunk_count = len(chunk_ids)
if chunk_ids:
link.last_indexed_at = link.last_indexed_at or now
session.query(RagDocumentStatus).filter_by(
collection_id=collection_id
).delete(synchronize_session=False)
for doc_id, chunk_ids in durable.items():
session.add(
RagDocumentStatus(
document_id=doc_id,
collection_id=collection_id,
rag_index_id=rag_index_id,
chunk_count=len(chunk_ids),
indexed_at=prior_indexed_at.get(doc_id, now),
)
)
rag_index = (
session.query(RAGIndex).filter_by(id=rag_index_id).first()
)
if rag_index:
rag_index.chunk_count = sum(map(len, durable.values()))
rag_index.total_documents = len(durable)
rag_index.last_updated_at = now
session.commit()
durable_ids = {i for ids in durable.values() for i in ids}
return {
"indexed_documents": len(durable),
"indexed_chunks": len(durable_ids),
"live_vectors": len(live_ids),
"orphan_vectors": len(live_ids - owned_ids),
"orphan_vectors_removed": orphan_count,
"partial_document_vectors": len(
(live_ids & owned_ids) - durable_ids
),
}
def has_indexed_documents(self, collection_id: str) -> bool:
"""Check search eligibility without collecting unrelated RAG statistics.
Use the same exact-hash and legacy-configuration resolution as search
and stats. Rows belonging to other indexes cannot make this one eligible.
Resolving an index is read-only and never probes the embedding provider.
"""
with get_user_db_session(self.username, self.db_password) as session:
rag_index = self._resolve_index_for_config(session, collection_id)
if rag_index is None:
# Ineligible path only, so the extra query here doesn't
# touch the hot (eligible) path. Mirrors the same
# foreign-rows diagnostic get_rag_stats logs, so "I indexed
# this and search returns nothing" is still explained.
foreign_rows = (
session.query(RagDocumentStatus)
.filter_by(collection_id=collection_id)
.count()
)
if foreign_rows:
logger.warning(
f"Collection {collection_id} has no index for the "
f"active embedding configuration "
f"({self.embedding_provider}/{self.embedding_model}), "
f"so it reports zero indexed documents. "
f"{foreign_rows} document(s) are indexed under other "
f"configurations and are not searchable from this one."
)
return False
return bool(
session.query(
exists().where(
RagDocumentStatus.collection_id == collection_id,
RagDocumentStatus.rag_index_id == rag_index.id,
)
).scalar()
)
def get_rag_stats(
self, collection_id: Optional[str] = None
) -> Dict[str, Any]:
"""
Get RAG statistics for a collection.
Args:
collection_id: UUID of the collection (defaults to Library)
Returns:
Dict with counts and metadata about indexed documents
"""
with get_user_db_session(self.username, self.db_password) as session:
# Get collection ID (default to Library)
if not collection_id:
from ...database.library_init import get_default_library_id
collection_id = get_default_library_id(
self.username, self.db_password
)
# Count total documents in collection
total_docs = (
session.query(DocumentCollection)
.filter_by(collection_id=collection_id)
.count()
)
# Count indexed documents from rag_document_status table
from ...database.models.library import RagDocumentStatus
# One collection can hold status rows from several indexes at
# once, so scope the counts to the index this configuration
# resolves to. No such index means nothing is indexed for it.
rag_index = self._resolve_index_for_config(session, collection_id)
if rag_index is None:
indexed_docs = 0
total_chunks = 0
foreign_rows = (
session.query(RagDocumentStatus)
.filter_by(collection_id=collection_id)
.count()
)
if foreign_rows:
logger.warning(
f"Collection {collection_id} has no index for the "
f"active embedding configuration "
f"({self.embedding_provider}/{self.embedding_model}), "
f"so it reports zero indexed documents. "
f"{foreign_rows} document(s) are indexed under other "
f"configurations and are not searchable from this one."
)
else:
indexed_docs = (
session.query(RagDocumentStatus)
.filter_by(
collection_id=collection_id,
rag_index_id=rag_index.id,
)
.count()
)
# Count total chunks from rag_document_status table
total_chunks = (
session.query(func.sum(RagDocumentStatus.chunk_count))
.filter_by(
collection_id=collection_id,
rag_index_id=rag_index.id,
)
.scalar()
or 0
)
# Describe the index the counts above came from. Sampling any
# chunk of the collection would describe whichever index wrote
# first, which is the same mismatch as the counts.
embedding_info = {}
if rag_index is not None:
stored_provider = rag_index.embedding_model_type
if isinstance(stored_provider, EmbeddingProvider):
stored_provider = stored_provider.value
embedding_info = {
"model": rag_index.embedding_model,
"model_type": stored_provider,
"dimension": rag_index.embedding_dimension,
}
return {
"total_documents": total_docs,
"indexed_documents": indexed_docs,
"unindexed_documents": total_docs - indexed_docs,
"total_chunks": total_chunks,
"embedding_info": embedding_info,
"chunk_size": self.chunk_size,
"chunk_overlap": self.chunk_overlap,
}
def remove_documents_from_index(
self,
document_ids: List[str],
collection_id: str,
*,
chunk_ids_by_document: Optional[Dict[str, List[int]]] = None,
) -> int:
with _hold_collection_lock(
self.username, collection_id, purpose="transaction"
):
return self._remove_documents_from_index_locked(
document_ids,
collection_id,
chunk_ids_by_document=chunk_ids_by_document,
)
def _remove_documents_from_index_locked(
self,
document_ids: List[str],
collection_id: str,
*,
chunk_ids_by_document: Optional[Dict[str, List[int]]] = None,
) -> int:
"""Delete given documents' vectors from a collection's vector store.
Vector-store-only: the DB chunk rows are removed separately by the
caller. This closes the gap where deleting a document's DB chunks
left its vectors (and their persisted text — now impossible, see
vector_stores/base.py's SECURITY INVARIANT) in the store, so the
document kept surfacing in semantic search until a full reindex.
For each id, calls ``VectorIndex.delete(source_type="document",
source_id=...)`` — which looks up the matching ``DocumentChunk``
rows by (source_type, source_id, collection_name) — UNLESS
``chunk_ids_by_document`` supplies that document's chunk ids
directly, in which case ``VectorIndex.delete_ids(ids)`` is used
instead. Callers whose own per-item transactions must delete the DB
rows eagerly (for their own atomicity/rollback semantics) BEFORE
this batched cleanup runs need the latter: the source_id lookup
would find nothing once the rows are already gone (see the Zotero
sync caller). Hardcodes ``source_type="document"``: both current
callers (Zotero sync cleanup, ``remove_document_from_rag``) only
ever pass library-document ids (the pre-cutover implementation
matched a mixed ``document_id``/``source_id`` metadata key
generically across "document" and "user_document" sources, but
nothing ever called it with anything but library documents).
Returns the total number of vectors removed across all ids. No-ops
(returns 0) when the collection has no current vector index — this
guard runs BEFORE building a ``VectorIndex`` so a delete call never
creates one (``_get_vector_index`` would otherwise create the
RAGIndex row via ``_get_or_create_rag_index``).
"""
from ...database.models.library import RAGIndex
from ...database.session_context import get_user_db_session
wanted = [d for d in document_ids if d]
if not wanted:
return 0
collection_name = f"collection_{collection_id}"
# Don't create an index just to delete from it — only act if one
# already exists for this collection.
with get_user_db_session(self.username, self.db_password) as session:
has_index = (
session.query(RAGIndex.id)
.filter_by(collection_name=collection_name, is_current=True)
.first()
is not None
)
if not has_index:
return 0
try:
# reset_stale_state=True is REQUIRED on this write path. If the
# pre-flight finds the index corrupt it quarantines the file
# (renames it aside); a fresh EMPTY store is then built and the
# delete loop below persists that empty store over the real path.
# Without resetting the per-document indexed state, the DB would
# still claim every other document is indexed while their vectors
# are gone — silently wiping the whole collection's search with no
# recovery but a manual full reindex. The reset only fires when the
# index was actually quarantined (guarded on the file no longer
# existing), so a healthy remove is unaffected. search() omits this
# flag safely because it never persists an empty store.
vindex = self._get_vector_index(
collection_id, collection_name, reset_stale_state=True
)
except (ValueError, RuntimeError):
logger.warning(
"Could not load vector index for "
f"{collection_name} while removing document vectors"
)
return 0
# Collect ALL removable chunk ids across every document, then remove
# them in ONE apply() (vindex.delete_ids). For an HNSW collection each
# apply() rebuilds the whole index, so a per-document loop is
# O(documents x collection_size); a single batched call rebuilds once.
# Captured ids are used directly; documents without captured ids have
# their chunk ids resolved by (source_type, source_id, collection_name)
# — those rows still exist at this point.
all_ids: List[int] = []
unresolved: List[str] = []
for document_id in wanted:
captured = (
chunk_ids_by_document.get(document_id)
if chunk_ids_by_document
else None
)
if captured:
all_ids.extend(int(i) for i in captured if i is not None)
else:
unresolved.append(document_id)
if unresolved:
in_chunk = 500 # keep below SQLITE_MAX_VARIABLE_NUMBER (999)
with get_user_db_session(
self.username, self.db_password
) as session:
for i in range(0, len(unresolved), in_chunk):
batch = unresolved[i : i + in_chunk]
all_ids.extend(
row.id
for row in session.query(DocumentChunk.id).filter(
DocumentChunk.source_type == "document",
DocumentChunk.collection_name == collection_name,
DocumentChunk.source_id.in_(batch),
)
)
removed = 0
if all_ids:
try:
stats = vindex.delete_ids(sorted(set(all_ids)))
removed = stats.removed
except Exception:
logger.warning(
f"Could not remove {len(set(all_ids))} vectors for "
f"{len(wanted)} document(s) from {collection_name}"
)
if removed:
logger.info(
f"Removed {removed} vectors for "
f"{len(wanted)} document(s) from {collection_name}"
)
return removed