~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
"""RAG indexing-pipeline contracts for ``web/routers/rag.py`` and the
services beneath it.
Everything here drives REAL production code: a real ``LibraryRAGService``
writing real FAISS files under ``LDR_DATA_DIR``, real ``DocumentChunk`` /
``RAGIndex`` / ``RagDocumentStatus`` rows against the real schema, and the
router's real ``_background_index_worker`` /
``_start_background_index_sync`` /
``cancel_indexing`` entry points. The ONLY faked boundary is the
embedding backend (a deterministic, network-free ``Embeddings``) --
mirroring the real-components harness in
``tests/research_library/services/test_multi_model_switch_revert.py``.
No embedding model or LLM is ever loaded or called.
Four claims are examined. Open defects use *strict xfail* markers, with
passing controls beside them so the harness cannot mask a failure:
1. **Failed force-reindex preserves the published generation.** Replacement
chunks and files stay under a staging identity until all documents are
ready. The previous searchable content survives failed preparation.
2. **Chunking settings reach indexing but not query time** (the mechanism
behind #5745). ``_get_index_hash`` covers ``splitter_type`` and
``text_separators``, and indexing stamps both onto the ``RAGIndex``
row -- but both search engines rebuild the query-time
``LibraryRAGService`` from that row WITHOUT them. A collection indexed
with non-default separators therefore resolves a different index hash
at query time, a brand-new EMPTY index is created, search returns
nothing, and the real index is DEMOTED out of ``is_current`` -- which
is precisely the row both engines look up, so every later search is
empty too.
3. **Embedding-backend failure detail stays out of the background indexing
status endpoint.** ``_background_index_worker`` stores fixed messages in
``TaskMetadata`` instead of scrubbed exception text (CWE-209). The status
endpoint rebuilds each message from typed data, so the worker's fixed
guidance (the remote-drop retry advice, "Collection not found") still
reaches the client unchanged.
4. **Concurrent collection indexing is mutually excluded.** The shared
admission gate checks both streaming workers and background tasks before
a second run can start preparing a replacement.
Plus a cancellation guard: ``cancel_indexing`` scans ALL in-progress tasks
(``.all()``, as ``start_background_index`` does) instead of ``.first()``, so
an unrelated collection's task cannot shadow this collection's and make
cancellation 404 while the worker keeps running.
NOT covered here (already covered elsewhere, deliberately not duplicated):
SSE framing/heartbeats, the disconnect drain-thread, the cancel-event
registry plumbing and ``is_cancelled`` dispatch-loop semantics
(``tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.py``,
``tests/research_library/services/test_index_documents_parallel.py``),
index-hash identity per config
(``tests/research_library/services/test_rag_index_identity.py``), and the
``/api/rag/test-embedding`` CWE-209 hardening
(``tests/web/routers/test_rag_embedding_error_sanitisation.py``).
"""
import ast
import hashlib
import importlib
import uuid
from contextlib import ExitStack, contextmanager
from datetime import UTC, datetime
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import MagicMock, patch
import numpy as np
import pytest
from langchain_core.embeddings import Embeddings
from sqlalchemy import create_engine, event
from sqlalchemy.orm import sessionmaker
from local_deep_research.database.models import Base
from local_deep_research.database.models.library import (
Collection,
Document,
DocumentChunk,
DocumentCollection,
DocumentStatus,
RAGIndex,
RagDocumentStatus,
SourceType,
)
from local_deep_research.database.models.queue import TaskMetadata
MODULE = "local_deep_research.web.routers.rag"
_RAG_SVC_MOD = (
"local_deep_research.research_library.services.library_rag_service"
)
_FACADE_MOD = "local_deep_research.vector_stores.facade"
_DB_CTX = "local_deep_research.database.session_context"
_COLLECTION_ENGINE = (
"local_deep_research.web_search_engines.engines.search_engine_collection"
)
_LIBRARY_ENGINE = (
"local_deep_research.web_search_engines.engines.search_engine_library"
)
USERNAME = "raguser"
DB_PASSWORD = "pw" # gitleaks:allow
#: Appears only inside the seeded document body, so finding it in a search
#: hit proves the ORIGINAL vectors/chunk rows were reached.
SECRET = "ZZZ_INDEXED_BODY_MARKER_4c1f8ab2"
#: Differs from ``DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS``
#: (``["\n\n", "\n", ". ", " ", ""]``) only by dropping ``". "`` -- an
#: ordinary tweak on the embedding-settings page, and enough to change
#: ``_get_index_hash``.
NON_DEFAULT_SEPARATORS = ["\n\n", "\n", " ", ""]
QUERY = f"body mentions {SECRET}"
# ---------------------------------------------------------------------------
# Real-components harness (the embedding backend is the only fake)
# ---------------------------------------------------------------------------
class _FakeEmbeddings(Embeddings):
"""Deterministic, network-free embeddings. Never loads a model."""
def __init__(self, name: str, dim: int = 8):
self.name = name
self.dim = dim
def _vec(self, text: str):
rng = np.random.default_rng(abs(hash((self.name, text))) % (2**32))
return rng.random(self.dim).tolist()
def embed_documents(self, texts):
return [self._vec(t) for t in texts]
def embed_query(self, text):
return self._vec(text)
@pytest.fixture
def world(tmp_path, monkeypatch, mocker):
"""One in-memory DB shared by every ``get_user_db_session`` call site,
and a real on-disk ``cache/rag_indices`` tree under ``tmp_path``."""
from local_deep_research.database.session_context import (
get_user_db_session as real_get_user_db_session,
)
monkeypatch.setenv("LDR_DATA_DIR", str(tmp_path))
engine = create_engine("sqlite:///:memory:")
# Production turns foreign keys ON for every connection
# (``sqlcipher_utils._configure_connection``), and
# RAG index deletion relies on cascading RagDocumentStatus rows. SQLite defaults the pragma OFF, so without
# this the harness would silently diverge from production on exactly
# the behaviour under test.
@event.listens_for(engine, "connect")
def _enable_sqlite_foreign_keys(dbapi_connection, _record):
dbapi_connection.execute("PRAGMA foreign_keys=ON")
Base.metadata.create_all(engine)
session = sessionmaker(bind=engine)()
@contextmanager
def _shared_session(username, *args, **kwargs):
if username == USERNAME:
yield session
else:
# A module imported while this patch is active may retain the
# wrapper after teardown. Other users must still reach their
# actual DB rather than this fixture's closed in-memory session.
with real_get_user_db_session(username, *args, **kwargs) as db:
yield db
mocker.patch(f"{_RAG_SVC_MOD}.get_user_db_session", _shared_session)
mocker.patch(f"{_FACADE_MOD}.get_user_db_session", _shared_session)
mocker.patch(f"{_DB_CTX}.get_user_db_session", _shared_session)
# Integrity-record plumbing is a separate concern with its own tests;
# stub it so these tests stay on the indexing pipeline.
fim = MagicMock()
fim.verify_file.return_value = (True, None)
fim.record_file.return_value = None
mocker.patch(f"{_RAG_SVC_MOD}.FileIntegrityManager", return_value=fim)
yield session
session.close()
engine.dispose()
@pytest.fixture
def seeded(world):
"""A Collection + Document (containing ``SECRET``) + their link row."""
session = world
collection_id = uuid.uuid4().hex
document_id = uuid.uuid4().hex
session.add(
SourceType(
id=uuid.uuid4().hex, name="document", display_name="Document"
)
)
source_type_id = (
session.query(SourceType).filter_by(name="document").one().id
)
session.add(Collection(id=collection_id, name="Indexing pipeline"))
body = (
f"The indexed body of this document mentions {SECRET} repeatedly.\n"
f"A second paragraph also mentions {SECRET} so chunking has work.\n"
) * 6
session.add(
Document(
id=document_id,
source_type_id=source_type_id,
document_hash=hashlib.sha256(body.encode()).hexdigest(),
title="Indexing pipeline document",
text_content=body,
original_url="http://example.com/indexing-pipeline",
file_size=len(body),
file_type="txt",
status=DocumentStatus.COMPLETED,
)
)
session.add(
DocumentCollection(
document_id=document_id,
collection_id=collection_id,
indexed=False,
chunk_count=0,
)
)
session.commit()
return collection_id, document_id
def _make_service(**overrides):
"""A real ``LibraryRAGService`` with only the embedding backend faked."""
from local_deep_research.research_library.services.library_rag_service import (
LibraryRAGService,
)
model = overrides.pop("embedding_model", "model-A")
emb_mgr = MagicMock()
emb_mgr.embeddings = _FakeEmbeddings(name=model)
kwargs = dict(
username=USERNAME,
db_password=DB_PASSWORD,
embedding_model=model,
embedding_provider="sentence_transformers",
embedding_manager=emb_mgr,
index_type="flat",
distance_metric="cosine",
normalize_vectors=True,
)
kwargs.update(overrides)
return LibraryRAGService(**kwargs)
def _seed_task(session, task_id, collection_id, status="processing"):
session.add(
TaskMetadata(
task_id=task_id,
status=status,
task_type="indexing",
created_at=datetime.now(UTC),
started_at=datetime.now(UTC),
progress_current=0,
progress_total=0,
progress_message="Starting indexing...",
metadata_json={"collection_id": collection_id},
)
)
session.commit()
return task_id
def _stored_index_files(session, collection_name):
return [
Path(row.index_path)
for row in session.query(RAGIndex)
.filter_by(collection_name=collection_name)
.all()
if row.index_path
]
def _fake_request():
"""Minimal ``Request`` stand-in: ``cancel_indexing`` reads ``.session``
only."""
return SimpleNamespace(session={}, query_params={})
# ---------------------------------------------------------------------------
# Harness control
# ---------------------------------------------------------------------------
def test_harness_indexes_and_searches_real_components(world, seeded):
"""Positive control for every test below.
Proves the fake-embeddings harness really indexes through the
production ``LibraryRAGService`` (chunk rows, a ``RAGIndex`` row, an
on-disk ``.faiss`` file, a ``RagDocumentStatus`` row) and that the
seeded marker is retrievable by a real vector search. Every "search
returned nothing" assertion in this file is only meaningful because
this one passes.
"""
session = world
collection_id, document_id = seeded
collection_name = f"collection_{collection_id}"
svc = _make_service()
result = svc.index_document(document_id, collection_id)
assert result["status"] == "success", result
assert result["chunk_count"] > 0
assert (
session.query(DocumentChunk)
.filter_by(collection_name=collection_name)
.count()
== result["chunk_count"]
)
assert (
session.query(RagDocumentStatus)
.filter_by(collection_id=collection_id, document_id=document_id)
.count()
== 1
)
files = _stored_index_files(session, collection_name)
assert files and all(p.exists() for p in files)
hits = svc.search(QUERY, collection_id, 5)
assert any(SECRET in h.text for h in hits)
# ---------------------------------------------------------------------------
# (1) force-reindex: destroy-then-rebuild, with a real failure in between
# ---------------------------------------------------------------------------
class TestForceReindexDurabilityOnFailure:
"""A background rebuild keeps the previous index until publication."""
@staticmethod
def _seed_index(session, collection_id, document_id):
svc = _make_service()
assert svc.index_document(document_id, collection_id)["status"] == (
"success"
)
files = _stored_index_files(session, f"collection_{collection_id}")
assert files and all(p.exists() for p in files)
return files
def test_force_reindex_preserves_published_state_during_preparation(
self, world, seeded
):
"""Inspect the real worker at the replacement preparation boundary."""
from local_deep_research.web.routers import rag as rag_mod
session = world
collection_id, document_id = seeded
collection_name = f"collection_{collection_id}"
files = self._seed_index(session, collection_id, document_id)
observed = {}
def _capture(*_a, **_k):
session.expire_all()
observed["chunks"] = (
session.query(DocumentChunk)
.filter_by(collection_name=collection_name)
.count()
)
observed["files_present"] = [p.exists() for p in files]
raise RuntimeError("embedding backend unavailable")
svc = _make_service()
svc.index_documents_parallel = MagicMock(side_effect=_capture)
task_id = _seed_task(session, uuid.uuid4().hex, collection_id)
with patch.object(
rag_mod, "_get_rag_service_for_thread", return_value=svc
):
rag_mod._background_index_worker(
task_id, collection_id, USERNAME, DB_PASSWORD, True, 2
)
assert svc.index_documents_parallel.call_count == 1
assert observed["chunks"] > 0
assert observed["files_present"] == [True for _ in files]
def test_failed_force_reindex_leaves_previous_content_searchable(
self, world, seeded
):
from local_deep_research.web.routers import rag as rag_mod
session = world
collection_id, document_id = seeded
collection_name = f"collection_{collection_id}"
self._seed_index(session, collection_id, document_id)
svc = _make_service()
svc.index_documents_parallel = MagicMock(
side_effect=RuntimeError("embedding backend unavailable")
)
task_id = _seed_task(session, uuid.uuid4().hex, collection_id)
with patch.object(
rag_mod, "_get_rag_service_for_thread", return_value=svc
):
rag_mod._background_index_worker(
task_id, collection_id, USERNAME, DB_PASSWORD, True, 2
)
session.expire_all()
assert (
session.query(TaskMetadata).filter_by(task_id=task_id).one().status
== "failed"
)
# A failed rebuild must leave the collection exactly as it was.
assert (
session.query(DocumentChunk)
.filter_by(collection_name=collection_name)
.count()
> 0
), "the previous index's chunk rows were deleted by a FAILED reindex"
hits = _make_service().search(QUERY, collection_id, 5)
assert any(SECRET in h.text for h in hits), (
"previously-indexed content must still be queryable after a "
"failed force-reindex; the collection is now silently empty"
)
# ---------------------------------------------------------------------------
# (2) #5745: chunking settings reach indexing but not query time
# ---------------------------------------------------------------------------
def _library_rag_service_call_kwargs(module_path: str) -> set:
"""Keyword names passed to ``LibraryRAGService(...)`` in a module.
Read from the production source so these tests track the real call
site rather than a paraphrase of it.
"""
module = importlib.import_module(module_path)
tree = ast.parse(Path(module.__file__).read_text(encoding="utf-8"))
found = set()
for node in ast.walk(tree):
if (
isinstance(node, ast.Call)
and isinstance(node.func, ast.Name)
and node.func.id == "LibraryRAGService"
):
found |= {kw.arg for kw in node.keywords if kw.arg}
assert found, f"no LibraryRAGService(...) call found in {module_path}"
return found
def _query_time_kwargs(rag_index) -> dict:
"""The query-time service kwargs ``CollectionSearchEngine`` actually
passes, sourced -- as it does -- from the stored ``RAGIndex`` row."""
from local_deep_research.utilities.type_utils import to_bool
available = {
"username": USERNAME,
"embedding_model": rag_index.embedding_model,
"embedding_provider": rag_index.embedding_model_type.value,
"chunk_size": rag_index.chunk_size,
"chunk_overlap": rag_index.chunk_overlap,
"normalize_vectors": to_bool(rag_index.normalize_vectors, default=True),
"distance_metric": rag_index.distance_metric or "cosine",
"index_type": rag_index.index_type or "flat",
"splitter_type": rag_index.splitter_type or "recursive",
"text_separators": rag_index.text_separators,
}
names = _library_rag_service_call_kwargs(_COLLECTION_ENGINE)
unknown = names - available.keys()
assert not unknown, (
f"the search-engine call site passes unknown kwargs {sorted(unknown)}"
" -- update this helper so the reconstruction stays faithful"
)
return {name: available[name] for name in names}
@pytest.fixture
def indexed_with_nondefault_separators(world, seeded):
"""Index the seeded document with non-default ``text_separators`` and
return ``(collection_id, document_id)``."""
collection_id, document_id = seeded
svc = _make_service(text_separators=NON_DEFAULT_SEPARATORS)
assert svc.index_document(document_id, collection_id)["status"] == "success"
return collection_id, document_id
def _sole_index_row(session, collection_id):
return (
session.query(RAGIndex)
.filter_by(collection_name=f"collection_{collection_id}")
.one()
)
class TestChunkingSettingsAtQueryTime:
"""``splitter_type``/``text_separators`` are part of the index identity
(``_get_index_hash``) and are stamped onto the ``RAGIndex`` row at
indexing time, and both search engines read them back when rebuilding
the query-time service -- issue #5745."""
@pytest.mark.parametrize(
"engine",
[_COLLECTION_ENGINE, _LIBRARY_ENGINE],
ids=["collection", "library"],
)
def test_search_engines_include_the_chunking_kwargs(self, engine):
"""The identity-affecting kwargs the engine threads through --
verifies that chunking settings are forwarded to LibraryRAGService."""
kwargs = _library_rag_service_call_kwargs(engine)
assert {
"embedding_model",
"embedding_provider",
"chunk_size",
"chunk_overlap",
"distance_metric",
"normalize_vectors",
"index_type",
"splitter_type",
"text_separators",
} <= kwargs
def test_indexing_persists_the_configured_separators(
self, world, indexed_with_nondefault_separators
):
"""Control: the *indexing* half of the threading works, so the
query-time failure below is not a settings-plumbing problem on the
write side."""
collection_id, _ = indexed_with_nondefault_separators
row = _sole_index_row(world, collection_id)
assert row.text_separators == NON_DEFAULT_SEPARATORS
assert row.splitter_type == "recursive"
assert row.is_current is True
assert row.chunk_count > 0
def test_same_configuration_search_finds_the_content(
self, world, indexed_with_nondefault_separators
):
"""Control: nothing is wrong with the index itself -- queried with
the configuration it was BUILT with, it answers."""
collection_id, _ = indexed_with_nondefault_separators
svc = _make_service(text_separators=NON_DEFAULT_SEPARATORS)
assert svc.get_rag_stats(collection_id)["indexed_documents"] > 0
hits = svc.search(QUERY, collection_id, 5)
assert any(SECRET in h.text for h in hits)
def test_query_time_reconstruction_finds_the_content(
self, world, indexed_with_nondefault_separators
):
collection_id, _ = indexed_with_nondefault_separators
row = _sole_index_row(world, collection_id)
query_svc = _make_service(**_query_time_kwargs(row))
# search_engine_collection's own guard now checks
# has_indexed_documents, not this -- this just confirms the
# document really is indexed, so an empty result below is not
# "nothing indexed yet" wearing a different explanation.
assert query_svc.get_rag_stats(collection_id)["indexed_documents"] > 0
hits = query_svc.search(QUERY, collection_id, 5)
assert any(SECRET in h.text for h in hits), (
"a collection indexed with non-default text_separators is "
"unreachable from the search engines' query-time service"
)
def test_query_time_mismatch_does_not_disturb_the_real_index(
self, world, indexed_with_nondefault_separators
):
session = world
collection_id, _ = indexed_with_nondefault_separators
collection_name = f"collection_{collection_id}"
row = _sole_index_row(session, collection_id)
original_id, original_hash = row.id, row.index_hash
_make_service(**_query_time_kwargs(row)).search(QUERY, collection_id, 5)
session.expire_all()
rows = (
session.query(RAGIndex)
.filter_by(collection_name=collection_name)
.all()
)
assert len(rows) == 1, (
"a read-path search created an extra, empty RAGIndex row: "
f"{[(r.index_hash, r.is_current, r.chunk_count) for r in rows]}"
)
surviving = rows[0]
assert surviving.id == original_id
assert surviving.index_hash == original_hash
assert surviving.is_current is True, (
"a read-path search demoted the collection's real index out of "
"is_current -- the row both search engines look up"
)
@pytest.mark.parametrize(
("promote_current", "expect_created_current"),
[(False, False), (True, True)],
ids=["read-path", "write-path"],
)
def test_a_row_created_on_a_read_path_is_not_promoted(
self,
world,
indexed_with_nondefault_separators,
promote_current,
expect_created_current,
):
"""``promote_current`` gates the promotion of a row
``_get_or_create_rag_index`` had to CREATE, not only of a reused one.
The write-path case is the control: an indexing run under a new
configuration still promotes its fresh row (demoting the old one)
exactly as before, so the gate is what keeps a read path from moving
the pointer -- the second half of #5745."""
session = world
collection_id, _ = indexed_with_nondefault_separators
collection_name = f"collection_{collection_id}"
original_id = _sole_index_row(session, collection_id).id
# Default separators: a configuration the collection was never
# indexed with, so the row must be created rather than reused.
created = _make_service()._get_or_create_rag_index(
collection_id, promote_current=promote_current
)
session.expire_all()
assert created.id != original_id
assert created.chunk_count == 0
current_ids = [
row.id
for row in session.query(RAGIndex)
.filter_by(collection_name=collection_name)
.all()
if row.is_current
]
expected_current = created.id if expect_created_current else original_id
assert current_ids == [expected_current], (
"a row created under promote_current=False was promoted to "
"is_current, demoting the collection's real index"
)
def test_mismatched_search_leaves_the_real_index_serving(
self, world, indexed_with_nondefault_separators
):
"""The end-to-end shape of the hijack in #5745: a search under a
configuration the collection was not indexed with (a stand-in for the
next identity field a caller forgets to thread) may create its own
empty index, but a correctly-configured search afterwards must still
reach the content -- the mismatch is not permanent any more."""
session = world
collection_id, _ = indexed_with_nondefault_separators
collection_name = f"collection_{collection_id}"
original_id = _sole_index_row(session, collection_id).id
mismatched_hits = _make_service().search(QUERY, collection_id, 5)
assert not any(SECRET in h.text for h in mismatched_hits)
session.expire_all()
current_ids = [
row.id
for row in session.query(RAGIndex)
.filter_by(collection_name=collection_name)
.all()
if row.is_current
]
assert current_ids == [original_id], (
"one mismatched search flipped the collection's current index "
"to the empty row it created"
)
hits = _make_service(text_separators=NON_DEFAULT_SEPARATORS).search(
QUERY, collection_id, 5
)
assert any(SECRET in h.text for h in hits), (
"after a mismatched search the correctly-configured search no "
"longer finds the indexed content"
)
# ---------------------------------------------------------------------------
# (3) CWE-209: backend failure detail reaches the index-status endpoint
# ---------------------------------------------------------------------------
#: A backend failure carrying a server path and the provider endpoint.
#: Neither is a credential shape, so credential scrubbing alone leaves both.
_LEAKY_BACKEND_ERROR = OSError(
"cannot load embedding model from "
"/srv/ldr-data/models/nomic-embed-text/pytorch_model.bin "
"(provider endpoint http://embed-internal.corp.example:11434)"
)
_LEAKY_RECONCILE_ERROR = RuntimeError(
"(sqlite3.OperationalError) no such column: rag.foo "
"[SQL: SELECT * FROM rag_indices] "
"[parameters: ('/srv/ldr-data/raguser.db',)]"
)
#: Served for any stored task error the status endpoint cannot rebuild.
_GENERIC_TASK_ERROR = "Indexing failed. Check the server logs for details."
#: What the worker stores on each terminal failure path. Every one is built
#: only from fixed phrases and counts, so the status endpoint must serve it
#: unchanged.
_WORKER_FAILURE_MESSAGES = {
"collection-not-found": "Collection not found",
"remote-drop-retryable-partial": (
"Vector store unreachable — indexing was aborted. Retry once the "
"vector store is available. 2 vector-store collection(s) had already "
"been removed before the failure; their index records were kept, so "
"search over them returns nothing until this is retried successfully "
"or the collection is force re-indexed."
),
"remote-drop-permanent": (
"The vector store could not drop the collection — indexing was "
"aborted. Retrying will not help until the vector store configuration "
"or permissions are fixed; see the server log."
),
"reconciliation-error": (
"Reconciliation skipped: Could not verify the vector store. Check the "
"server logs for details. Indexed flags preserved; verify the FAISS "
"index before retrying."
),
"reconciliation-refused": (
"Reconciliation skipped: live vector store reported zero ids while "
"DocumentChunk rows exist; refusing to clear indexed flags. Indexed "
"flags preserved; verify the FAISS index before retrying."
),
"reconciled-failures": (
"1 document(s) failed to index. The collection was reconciled to the "
"durable vector store."
),
"unexpected-exception": _GENERIC_TASK_ERROR,
}
#: Must never reach the client: the leaky errors' details, and the provider
#: and index-hash prefix in a failed drop's own message.
_CLIENT_SECRETS = (
"/srv/ldr-data",
"embed-internal.corp.example",
"[SQL:",
"qdrant",
"0123456789ab",
)
def _remote_drop_error(retryable, dropped):
"""A failed drop whose own text names the provider and an index hash."""
from local_deep_research.research_library.deletion.utils.cascade_helper import (
RemoteVectorStoreDropError,
)
return RemoteVectorStoreDropError(
"Failed to drop qdrant collection for index 0123456789ab...: "
"ConnectionError. The index record was NOT deleted.",
retryable=retryable,
dropped=dropped,
cause_type="ConnectionError",
)
def _fail_indexing(rag_mod, path, task_id, collection_id):
"""Drive ``_background_index_worker`` down one terminal failure path.
For ``collection-not-found`` the caller passes the id of a collection
that does not exist; every other path indexes the seeded collection.
"""
svc = _make_service()
svc.index_documents_parallel = MagicMock(
return_value={
"successful": 1,
"skipped": 0,
"failed": 0,
"cancelled": False,
"errors": [],
}
)
svc.reconcile_collection_index = MagicMock(
return_value={
"indexed_documents": 1,
"indexed_chunks": 4,
"live_vectors": 4,
"orphan_vectors": 0,
}
)
force_reindex = False
with ExitStack() as stack:
get_service = stack.enter_context(
patch.object(
rag_mod, "_get_rag_service_for_thread", return_value=svc
)
)
if path == "unexpected-exception":
get_service.side_effect = _LEAKY_BACKEND_ERROR
elif path.startswith("remote-drop"):
force_reindex = True
if path == "remote-drop-retryable-partial":
error = _remote_drop_error(retryable=True, dropped=2)
else:
error = _remote_drop_error(retryable=False, dropped=0)
# Exercise the typed failure boundary without depending on a
# destructive reset helper that staged rebuilds no longer use.
get_service.side_effect = error
elif path == "reconciliation-error":
svc.reconcile_collection_index.side_effect = _LEAKY_RECONCILE_ERROR
elif path == "reconciliation-refused":
svc.reconcile_collection_index.return_value = {
"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,
}
elif path == "reconciled-failures":
svc.index_documents_parallel.return_value = {
"successful": 0,
"skipped": 0,
"failed": 1,
"cancelled": False,
"errors": [
{
"doc_id": "doc-1",
"title": "report",
"error": "Document has no text content",
}
],
}
rag_mod._background_index_worker(
task_id, collection_id, USERNAME, DB_PASSWORD, force_reindex, 2
)
get_service.assert_called_once_with(
collection_id, USERNAME, DB_PASSWORD, use_defaults=force_reindex
)
class TestIndexStatusErrorDisclosure:
"""Background indexing must match the embedding route's default deny."""
def test_test_embedding_route_withholds_the_same_detail(self):
"""Control: the hardened surface, given the SAME exception, returns
a fixed message carrying nothing from it -- not even the class
name. This proves the exception text itself contains unsafe detail."""
from local_deep_research.web.routers.rag import (
_format_test_embedding_error,
)
message = _format_test_embedding_error(
_LEAKY_BACKEND_ERROR, "nomic-embed-text"
)
# Byte-exact, so this stays a positive control: it proves the
# default-deny branch really ran for this exception (an OSError is
# outside both the LDR-internal and the upstream-provider
# allowlists) rather than passing because some unrelated string
# happened not to contain the secrets.
assert message == (
"Embedding test failed for model 'nomic-embed-text' due to an "
"unexpected error. Check the provider URL and model name; the "
"full error is in the server logs."
)
assert "OSError" not in message
assert "/srv/ldr-data/models" not in message
assert "embed-internal.corp.example" not in message
def test_backend_failure_detail_does_not_reach_the_task_error(
self, world, seeded
):
from local_deep_research.web.routers import rag as rag_mod
session = world
collection_id, _ = seeded
task_id = _seed_task(session, uuid.uuid4().hex, collection_id)
with patch.object(
rag_mod,
"_get_rag_service_for_thread",
side_effect=_LEAKY_BACKEND_ERROR,
):
rag_mod._background_index_worker(
task_id, collection_id, USERNAME, DB_PASSWORD, False, 2
)
session.expire_all()
task = session.query(TaskMetadata).filter_by(task_id=task_id).one()
assert task.status == "failed"
client_visible = task.error_message or ""
assert (
client_visible
== "Indexing failed. Check the server logs for details."
)
assert "/srv/ldr-data/models" not in client_visible, (
"a server filesystem path reached the client-visible indexing "
f"task error: {client_visible!r}"
)
assert "embed-internal.corp.example" not in client_visible, (
"the embedding provider endpoint reached the client-visible "
f"indexing task error: {client_visible!r}"
)
def test_reconciliation_failure_detail_does_not_reach_the_task(
self, world, seeded
):
from local_deep_research.web.routers import rag as rag_mod
session = world
collection_id, _ = seeded
svc = _make_service()
svc.index_documents_parallel = MagicMock(
return_value={
"successful": 1,
"skipped": 0,
"failed": 0,
"cancelled": False,
"errors": [],
}
)
svc.reconcile_collection_index = MagicMock(
side_effect=_LEAKY_RECONCILE_ERROR
)
task_id = _seed_task(session, uuid.uuid4().hex, collection_id)
with patch.object(
rag_mod, "_get_rag_service_for_thread", return_value=svc
):
rag_mod._background_index_worker(
task_id, collection_id, USERNAME, DB_PASSWORD, False, 2
)
# The reconciliation branch really was taken.
assert svc.reconcile_collection_index.call_count == 1
session.expire_all()
task = session.query(TaskMetadata).filter_by(task_id=task_id).one()
client_visible = f"{task.error_message or ''}{task.metadata_json or {}}"
assert "Could not verify the vector store" in client_visible
assert "[SQL:" not in client_visible, (
"SQL text reached the client-visible indexing task state: "
f"{client_visible!r}"
)
assert "/srv/ldr-data/raguser.db" not in client_visible, (
"a server database path reached the client-visible indexing "
f"task state: {client_visible!r}"
)
def test_nested_per_document_result_does_not_bypass_error_boundary(
self, world, seeded
):
from local_deep_research.web.routers import rag as rag_mod
session = world
collection_id, _ = seeded
svc = _make_service()
svc.index_documents_parallel = MagicMock(
return_value={
"successful": 0,
"skipped": 0,
"failed": 1,
"cancelled": False,
"total": 1,
"errors": [
{
"doc_id": "doc-1",
"title": "report",
"error": _LEAKY_BACKEND_ERROR,
}
],
"results": {
"doc-1": {
"status": "error",
"error": str(_LEAKY_BACKEND_ERROR),
}
},
}
)
svc.reconcile_collection_index = MagicMock(
return_value={
"indexed_documents": 0,
"indexed_chunks": 0,
"live_vectors": 0,
"orphan_vectors": 0,
}
)
task_id = _seed_task(session, uuid.uuid4().hex, collection_id)
with patch.object(
rag_mod, "_get_rag_service_for_thread", return_value=svc
):
rag_mod._background_index_worker(
task_id, collection_id, USERNAME, DB_PASSWORD, False, 2
)
session.expire_all()
task = session.query(TaskMetadata).filter_by(task_id=task_id).one()
result = task.metadata_json["result"]
assert result["failed"] == 1
assert "results" not in result
assert result["errors"] == [
{
"doc_id": "doc-1",
"title": "report",
"error": "Indexing failed. Check the server logs for details.",
}
]
assert "/srv/ldr-data/models" not in str(result)
def test_status_filters_legacy_task_rows_written_before_the_fix(
self, world, seeded
):
from local_deep_research.web.routers import rag as rag_mod
session = world
collection_id, _ = seeded
task_id = _seed_task(session, uuid.uuid4().hex, collection_id)
task = session.query(TaskMetadata).filter_by(task_id=task_id).one()
task.status = "failed"
task.progress_message = "Failed: [SQL: SELECT * FROM secrets]"
task.error_message = "Failed at /srv/ldr-data/private.db"
task.metadata_json = {
"collection_id": collection_id,
"result": {
"successful": 0,
"failed": 1,
"results": {
"doc-1": {
"error": "http://embed-internal.corp.example:11434"
}
},
"errors": [
{
"doc_id": "doc-1",
"title": "report",
"error": "[SQL: SELECT 1]",
}
],
},
}
session.commit()
status = rag_mod.get_index_status(
SimpleNamespace(session={}), collection_id, USERNAME
)
assert status["status"] == "failed"
assert status["progress_message"] == "Indexing failed"
assert status["error_message"] == (
"1 document(s) failed to index. Check the server logs for details."
)
assert status["result"]["errors"][0]["error"] == (
"Indexing failed. Check the server logs for details."
)
assert "results" not in status["result"]
for secret in ("[SQL:", "/srv/ldr-data", "embed-internal.corp.example"):
assert secret not in str(status)
def test_status_keeps_safe_counts_and_document_guidance(
self, world, seeded
):
from local_deep_research.web.routers import rag as rag_mod
session = world
collection_id, _ = seeded
task_id = _seed_task(session, uuid.uuid4().hex, collection_id)
task = session.query(TaskMetadata).filter_by(task_id=task_id).one()
task.status = "completed"
task.metadata_json = {
"collection_id": collection_id,
"result": {
"successful": 2,
"skipped": 0,
"failed": 0,
"durable_indexed_documents": 2,
"durable_indexed_chunks": 12,
"live_vectors": 12,
"orphan_vectors": 0,
"orphan_vectors_removed": 7,
"partial_document_vectors": 3,
"errors": [
{
"doc_id": "doc-1",
"error": "Document deleted during indexing",
}
],
},
}
session.commit()
status = rag_mod.get_index_status(
SimpleNamespace(session={}), collection_id, USERNAME
)
assert status["status"] == "completed"
assert status["result"]["durable_indexed_documents"] == 2
assert status["result"]["durable_indexed_chunks"] == 12
assert status["result"]["orphan_vectors_removed"] == 7
assert status["result"]["partial_document_vectors"] == 3
assert status["result"]["errors"][0]["error"] == (
"Document deleted during indexing"
)
def test_worker_stores_and_status_serves_document_guidance(
self, world, seeded
):
"""A document deleted while it was being indexed: the worker stores
the service's fixed guidance, and the status endpoint serves it
exactly."""
from local_deep_research.web.routers import rag as rag_mod
session = world
collection_id, _ = seeded
svc = _make_service()
svc.index_documents_parallel = MagicMock(
return_value={
"successful": 0,
"skipped": 0,
"failed": 1,
"cancelled": False,
"total": 1,
"errors": [
{
"doc_id": "doc-1",
"title": "report",
"error": "Document deleted during indexing",
}
],
}
)
svc.reconcile_collection_index = MagicMock(
return_value={
"indexed_documents": 0,
"indexed_chunks": 0,
"live_vectors": 0,
"orphan_vectors": 0,
}
)
task_id = _seed_task(session, uuid.uuid4().hex, collection_id)
with patch.object(
rag_mod, "_get_rag_service_for_thread", return_value=svc
):
rag_mod._background_index_worker(
task_id, collection_id, USERNAME, DB_PASSWORD, False, 2
)
session.expire_all()
status = rag_mod.get_index_status(
SimpleNamespace(session={}), collection_id, USERNAME
)
assert status["status"] == "failed"
assert status["error_message"] == (
"1 document(s) failed to index. The collection was reconciled to "
"the durable vector store."
)
assert status["result"]["errors"] == [
{
"doc_id": "doc-1",
"title": "report",
"error": "Document deleted during indexing",
}
]
@pytest.mark.parametrize("path", sorted(_WORKER_FAILURE_MESSAGES))
def test_status_serves_each_worker_failure_message_unchanged(
self, world, seeded, path
):
"""Each terminal message the worker builds only from fixed phrases
and counts reaches the client exactly as stored. The remote-drop
text says whether a retry can help and warns that collections it
already dropped need a forced re-index."""
from local_deep_research.web.routers import rag as rag_mod
session = world
collection_id, _ = seeded
if path == "collection-not-found":
collection_id = uuid.uuid4().hex
task_id = _seed_task(session, uuid.uuid4().hex, collection_id)
_fail_indexing(rag_mod, path, task_id, collection_id)
session.expire_all()
task = session.query(TaskMetadata).filter_by(task_id=task_id).one()
assert task.status == "failed"
assert task.error_message == _WORKER_FAILURE_MESSAGES[path]
status = rag_mod.get_index_status(
SimpleNamespace(session={}), collection_id, USERNAME
)
assert status["status"] == "failed"
assert status["error_message"] == task.error_message
for secret in _CLIENT_SECRETS:
assert secret not in str(status), (path, secret)
@pytest.mark.parametrize(
("failure", "expected"),
[
pytest.param(None, _GENERIC_TASK_ERROR, id="no-record"),
pytest.param(
{"code": "unknown"}, _GENERIC_TASK_ERROR, id="unknown-code"
),
pytest.param(
"collection_not_found",
_GENERIC_TASK_ERROR,
id="record-not-a-dict",
),
pytest.param(
{
"code": "remote_vector_store_drop",
"retryable": "yes",
"dropped": 0,
},
_GENERIC_TASK_ERROR,
id="flag-not-a-bool",
),
pytest.param(
{
"code": "remote_vector_store_drop",
"retryable": True,
"dropped": "2 at /srv/ldr-data",
},
_GENERIC_TASK_ERROR,
id="count-not-an-int",
),
pytest.param(
{
"code": "remote_vector_store_drop",
"retryable": True,
"dropped": True,
},
_GENERIC_TASK_ERROR,
id="count-is-a-bool",
),
pytest.param(
{
"code": "remote_vector_store_drop",
"retryable": True,
"dropped": -1,
},
_GENERIC_TASK_ERROR,
id="count-negative",
),
pytest.param(
{
"code": "remote_vector_store_drop",
"retryable": True,
"dropped": None,
},
_GENERIC_TASK_ERROR,
id="count-missing",
),
pytest.param(
{"code": "collection_not_found"},
"Collection not found",
id="valid-record-rebuilds-its-text",
),
pytest.param(
{
"code": "remote_vector_store_drop",
"retryable": False,
"dropped": 0,
},
_WORKER_FAILURE_MESSAGES["remote-drop-permanent"],
id="valid-drop-record-rebuilds-its-text",
),
],
)
def test_status_never_serves_the_stored_error_text(
self, world, seeded, failure, expected
):
"""The client text comes from the failure record, never from the
stored message. A row with no record (such as one written before
records existed) or with a malformed record gets the generic text,
even when its message starts like the drop guidance. A valid record
rebuilds its own fixed text and drops whatever the stored message
holds."""
from local_deep_research.web.routers import rag as rag_mod
session = world
collection_id, _ = seeded
task_id = _seed_task(session, uuid.uuid4().hex, collection_id)
task = session.query(TaskMetadata).filter_by(task_id=task_id).one()
task.status = "failed"
task.error_message = (
"Vector store unreachable — indexing was aborted. "
"[SQL: SELECT * FROM rag_indices] at /srv/ldr-data/raguser.db"
)
metadata = {"collection_id": collection_id}
if failure is not None:
metadata["failure"] = failure
task.metadata_json = metadata
session.commit()
status = rag_mod.get_index_status(
SimpleNamespace(session={}), collection_id, USERNAME
)
assert status["error_message"] == expected
for secret in _CLIENT_SECRETS:
assert secret not in str(status), secret
# ---------------------------------------------------------------------------
# (4) concurrent indexing of one collection
# ---------------------------------------------------------------------------
class _SyncThread:
"""``threading.Thread`` stand-in that runs its target synchronously, so
the fire-and-forget worker cannot race the assertions."""
def __init__(
self, target=None, args=(), kwargs=None, daemon=None, name=None
):
self._target = target
self._args = args
self._kwargs = kwargs or {}
def start(self):
if self._target is not None:
self._target(*self._args, **self._kwargs)
def join(self, timeout=None):
pass
def is_alive(self):
return False
def _start_background_reindex(rag_mod, collection_id):
with (
patch(f"{MODULE}.get_settings_manager") as settings,
patch.object(rag_mod, "_background_index_worker"),
patch("threading.Thread", _SyncThread),
):
settings.return_value.get_setting.return_value = 4
return rag_mod._start_background_index_sync(
collection_id, USERNAME, DB_PASSWORD, True
)
class TestConcurrentIndexingOfOneCollection:
"""Streaming and background requests must not rebuild one collection together."""
def test_a_duplicate_background_task_is_rejected(self, world, seeded):
"""An existing background task blocks another collection rebuild."""
from local_deep_research.web.routers import rag as rag_mod
collection_id, _ = seeded
_seed_task(world, "task-existing", collection_id)
result = _start_background_reindex(rag_mod, collection_id)
assert getattr(result, "status_code", None) == 409
def test_an_active_sse_indexer_blocks_a_background_reindex(
self, world, seeded
):
import threading as _threading
from local_deep_research.web.routers import rag as rag_mod
collection_id, _ = seeded
key = (USERNAME, collection_id)
with rag_mod._active_sse_indexers_lock:
rag_mod._active_sse_indexers.setdefault(key, set()).add(
_threading.Event()
)
try:
result = _start_background_reindex(rag_mod, collection_id)
finally:
with rag_mod._active_sse_indexers_lock:
rag_mod._active_sse_indexers.pop(key, None)
assert getattr(result, "status_code", None) == 409, (
"a second force-reindex of a collection with an SSE indexer "
f"already in flight was admitted: {result!r}"
)
# ---------------------------------------------------------------------------
# (5) cancellation: the in-progress scan that start_background_index fixed
# ---------------------------------------------------------------------------
class TestCancelIndexingTaskLookup:
"""Unrelated in-progress tasks must not hide the requested collection."""
@staticmethod
def _cancel(collection_id):
from local_deep_research.web.routers.rag import cancel_indexing
return cancel_indexing(
_fake_request(), collection_id, username=USERNAME
)
def test_cancels_this_collections_task_when_it_is_the_only_one(
self, world, seeded
):
"""Control: with no competing task the identical call cancels."""
session = world
collection_id, _ = seeded
_seed_task(session, "task-mine", collection_id)
result = self._cancel(collection_id)
assert isinstance(result, dict)
assert result["success"] is True
assert result["task_id"] == "task-mine"
session.expire_all()
assert (
session.query(TaskMetadata).filter_by(task_id="task-mine").one()
).status == "cancelled"
def test_an_unrelated_task_does_not_shadow_this_collections_cancel(
self, world, seeded
):
session = world
collection_id, _ = seeded
# Inserted first, so the unordered ``.first()`` returns it.
_seed_task(session, "task-other", "some-other-collection")
_seed_task(session, "task-mine", collection_id)
result = self._cancel(collection_id)
session.expire_all()
assert isinstance(result, dict)
assert result["success"] is True
assert result["task_id"] == "task-mine"
assert (
session.query(TaskMetadata).filter_by(task_id="task-other").one()
).status == "processing"
mine = session.query(TaskMetadata).filter_by(task_id="task-mine").one()
assert getattr(result, "status_code", None) != 404, (
"cancel_indexing 404s for a collection that DOES have an active "
"indexing task, because an unrelated collection's task sorts "
"first in its .first() scan"
)
assert mine.status == "cancelled", (
"the active indexing task for this collection was left in "
f"{mine.status!r}; the worker keeps running after a 'cancel'"
)
class TestCollectionRebuildNotice:
def test_notice_survives_expired_and_new_incremental_tasks(
self, world, seeded
):
from datetime import timedelta
from local_deep_research.database.queue_service import UserQueueService
from local_deep_research.web.routers import rag as rag_mod
collection_id, document_id = seeded
with _make_service() as service:
service.index_document(document_id, collection_id)
pending = datetime(2025, 1, 1, tzinfo=UTC)
world.get(Collection, collection_id).rebuild_pending_since = pending
task_id = _seed_task(world, "old-cancelled", collection_id, "cancelled")
task = world.query(TaskMetadata).filter_by(task_id=task_id).one()
task.completed_at = datetime.now(UTC) - timedelta(days=8)
world.commit()
UserQueueService(world).cleanup_old_tasks()
assert world.query(TaskMetadata).count() == 0
status = rag_mod.get_index_status(
_fake_request(), collection_id, USERNAME
)
assert status["status"] == "idle"
assert status["rebuild_pending_since"] == pending.isoformat()
assert status["has_published_index"] is True
assert status["index_last_updated_at"] is not None
_seed_task(world, "incremental", collection_id, "completed")
status = rag_mod.get_index_status(
_fake_request(), collection_id, USERNAME
)
assert status["force_reindex"] is False
assert status["rebuild_pending_since"] == pending.isoformat()
documents = rag_mod.get_collection_documents(
_fake_request(), collection_id, USERNAME
)
assert (
documents["collection"]["rebuild_pending_since"]
== pending.isoformat()
)
def test_cancel_status_waits_for_worker_and_reports_publication(
self, world, seeded
):
from local_deep_research.web.routers import rag as rag_mod
collection_id, _ = seeded
task_id = _seed_task(world, "late-publication", collection_id)
task = world.query(TaskMetadata).filter_by(task_id=task_id).one()
task.metadata_json = {
"collection_id": collection_id,
"force_reindex": True,
}
world.commit()
key = (USERNAME, collection_id)
with rag_mod._active_sse_indexers_lock:
rag_mod._active_background_indexers[key] = task_id
try:
assert rag_mod.cancel_indexing(
_fake_request(), collection_id, USERNAME
)["success"]
status = rag_mod.get_index_status(
_fake_request(), collection_id, USERNAME
)
assert status["status"] == "cancelled"
assert status["worker_active"] is True
assert status["force_reindex"] is True
assert status["has_published_index"] is False
rag_mod._do_update_task_status(
USERNAME,
DB_PASSWORD,
task_id,
status="completed",
progress_message="Rebuild complete.",
published_rebuild=True,
)
finally:
rag_mod._unregister_background_indexer(
USERNAME, collection_id, task_id
)
status = rag_mod.get_index_status(
_fake_request(), collection_id, USERNAME
)
assert status["status"] == "completed"
assert status["worker_active"] is False
assert "new index is in use" in status["progress_message"]
# A stale cancellation must never rewrite the published outcome.
rag_mod._do_update_task_status(
USERNAME, DB_PASSWORD, task_id, status="cancelled"
)
assert (
rag_mod.get_index_status(_fake_request(), collection_id, USERNAME)[
"status"
]
== "completed"
)