Skip to content

~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.

fix(rag): serialize collection indexing admission (#6911)

LearningCircuit142bac2aa24d
diff --git a/changelog.d/+serialize-collection-indexing.bugfix.md b/changelog.d/+serialize-collection-indexing.bugfix.md
new file mode 100644
index 0000000000..9968b3a7c7
--- /dev/null
+++ b/changelog.d/+serialize-collection-indexing.bugfix.md
@@ -0,0 +1 @@
+Prevent overlapping streaming and background indexing runs for the same collection. Cancelling or disconnecting keeps new rebuilds blocked until existing indexing workers have stopped. Disconnected workers release admission and close their service on completion without needing to start another cleanup thread.
diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.py
index 676fcf3480..8773ee905b 100644
--- a/src/local_deep_research/web/routers/rag.py
+++ b/src/local_deep_research/web/routers/rag.py
@@ -35,7 +35,7 @@ import time
import contextvars
import threading
import queue
-from concurrent.futures import ThreadPoolExecutor
+from concurrent.futures import Future, ThreadPoolExecutor
from datetime import datetime, UTC
from pathlib import Path
from typing import Any, Dict, Optional, Set, Tuple, Annotated
@@ -110,11 +110,14 @@ _EMBEDDING_TEST_SENTENCE = (
# Process-local registry tracking active SSE indexing streams for cancellation.
# Keyed by (username, collection_id) -> Set[threading.Event]
-# NOTE: Process-local registry assumes single-process deployment (or sticky sessions).
-# Multi-worker deployments (e.g. uvicorn with multiple workers without sticky sessions)
-# would require cross-process signaling (e.g. DB-backed cancel flag or Redis pub/sub).
+# Process-local cancellation and admission require a single worker process.
+# Multiple workers need shared admission and cancellation coordination;
+# sticky sessions alone do not exclude two devices indexing the same collection.
_active_sse_indexers: Dict[Tuple[str, str], Set[threading.Event]] = {}
_active_sse_indexers_lock = threading.Lock()
+# A cancelled task can still have workers draining. Keep admission closed
+# until its worker exits, independently of the task's persisted status.
+_active_background_indexers: Dict[Tuple[str, str], str] = {}
# NOTE: Routes use username (not .get()) intentionally.
# Depends(require_auth) guarantees the key exists; direct access fails
@@ -160,8 +163,8 @@ def _is_protected_collection(collection) -> bool:
_auto_index_executor: ThreadPoolExecutor | None = None
_auto_index_executor_lock = threading.Lock()
-# Per-(user, collection) locks guarding the start-background-index
-# check-and-create path. Keyed by tuple so two users indexing different
+# Per-(user, collection) locks guarding admission for all collection indexers.
+# Keyed by tuple so two users indexing different
# collections don't serialize against each other.
_start_bg_index_locks: dict[tuple[str, str], threading.Lock] = {}
@@ -1303,6 +1306,11 @@ def index_all(
"""Generator function for SSE progress updates."""
_sse_cancel = threading.Event()
try:
+ if not _register_sse_indexer(
+ username, collection_id, None, _sse_cancel
+ ):
+ yield f"data: {json.dumps({'type': 'error', 'error': 'Indexing is already in progress for this collection'})}\n\n"
+ return
# Send initial status
yield f"data: {json.dumps({'type': 'start', 'message': 'Starting bulk indexing...'})}\n\n"
@@ -1470,6 +1478,7 @@ def index_all(
# the event here is for any in-progress batch loop iteration
# and any future code path that bypasses the helper.
_sse_cancel.set()
+ _unregister_sse_indexer(username, collection_id, _sse_cancel)
safe_close(rag_service, "rag_service (index-all SSE)")
return WorkerCleanupStreamingResponse(
@@ -3178,6 +3187,66 @@ def get_collection_documents(
# =============================================================================
+def _indexing_conflict(db_session, username, collection_id):
+ """Check while holding the collection's admission lock."""
+ key = (username, str(collection_id))
+ conflict = {
+ "success": False,
+ "error": "Indexing is already in progress for this collection",
+ }
+ with _active_sse_indexers_lock:
+ if _active_sse_indexers.get(key):
+ return conflict
+ task_id = _active_background_indexers.get(key)
+ if task_id is not None:
+ return {**conflict, "task_id": task_id}
+
+ in_progress = (
+ db_session.query(TaskMetadata)
+ .filter(
+ TaskMetadata.task_type == "indexing",
+ TaskMetadata.status == "processing",
+ )
+ .all()
+ )
+ for task in in_progress:
+ if (task.metadata_json or {}).get("collection_id") == collection_id:
+ return {**conflict, "task_id": task.task_id}
+ return None
+
+
+def _register_sse_indexer(username, collection_id, db_password, cancel_event):
+ """Admit an SSE worker atomically with SSE and background requests."""
+ from ...database.session_context import get_user_db_session
+
+ key = (username, str(collection_id))
+ lock = _start_bg_index_locks.setdefault(key, threading.Lock())
+ with lock, get_user_db_session(username, db_password) as db_session:
+ if _indexing_conflict(db_session, username, collection_id):
+ return False
+ with _active_sse_indexers_lock:
+ _active_sse_indexers.setdefault(key, set()).add(cancel_event)
+ return True
+
+
+def _unregister_sse_indexer(username, collection_id, cancel_event):
+ """Release admission only once every worker belonging to this stream stopped."""
+ key = (username, str(collection_id))
+ with _active_sse_indexers_lock:
+ events = _active_sse_indexers.get(key)
+ if events is not None:
+ events.discard(cancel_event)
+ if not events:
+ _active_sse_indexers.pop(key, None)
+
+
+def _unregister_background_indexer(username, collection_id, task_id):
+ key = (username, str(collection_id))
+ with _active_sse_indexers_lock:
+ if _active_background_indexers.get(key) == task_id:
+ _active_background_indexers.pop(key, None)
+
+
def _store_collection_embedding_metadata(collection, rag_service):
"""Persist the embedding/index configuration used to index a collection.
@@ -3427,12 +3496,14 @@ def index_collection(
"""Generator for SSE progress updates."""
logger.info("SSE generator started")
_sse_cancel = threading.Event()
- with _active_sse_indexers_lock:
- _active_sse_indexers.setdefault(
- (username, collection_id), set()
- ).add(_sse_cancel)
worker_thread = None
+ worker_finished: Future[None] = Future()
try:
+ if not _register_sse_indexer(
+ username, collection_id, db_password, _sse_cancel
+ ):
+ yield f"data: {json.dumps({'type': 'error', 'error': 'Indexing is already in progress for this collection'})}\n\n"
+ return
# All setup DB work happens in a SHORT-LIVED session; the per-doc
# ids/filenames are snapshotted into plain tuples so the long
# indexing loop below (which yields progress + heartbeats) holds NO
@@ -3576,6 +3647,11 @@ def index_collection(
"best-effort thread-local DB session cleanup",
exc_info=True,
)
+ finally:
+ # All indexing writes and thread-local cleanup have
+ # finished. A disconnected stream can release its
+ # admission and service here without another thread.
+ worker_finished.set_result(None)
# Copy the request's contextvars so username-dependent
# fallbacks (e.g. log attribution) inside the worker resolve
@@ -3681,21 +3757,13 @@ def index_collection(
logger.exception("Error in collection indexing")
yield f"data: {json.dumps({'type': 'error', 'error': 'An internal error occurred during indexing'})}\n\n"
finally:
- # Signal disconnect/cancellation first so any in-flight checks notice it immediately,
- # then remove this specific stream's cancel event from the registry under lock.
+ # Signal cancellation immediately, but retain admission until
+ # every in-flight writer has stopped, including deferred drains.
_sse_cancel.set()
- with _active_sse_indexers_lock:
- events = _active_sse_indexers.get((username, collection_id))
- if events is not None:
- events.discard(_sse_cancel)
- if not events:
- _active_sse_indexers.pop(
- (username, collection_id), None
- )
# On client disconnect this finally can run on the event loop
# thread (generator close), so the drain must be bounded: give
# in-flight workers a short grace period, then hand the
- # remaining join + service close to a detached daemon thread.
+ # remaining cleanup to the existing worker's completion callback.
# _sse_cancel is already set, so the parallel helper admits no
# new work and terminates once in-flight docs finish.
if worker_thread is not None and worker_thread.is_alive():
@@ -3703,23 +3771,25 @@ def index_collection(
if worker_thread is not None and worker_thread.is_alive():
logger.info(
"Indexer still draining after SSE close; deferring "
- "cleanup to background thread"
+ "cleanup until the worker finishes"
)
- _lingering_worker = worker_thread
- def _drain_and_close():
- _lingering_worker.join()
+ def _close_after_worker(_finished):
+ _unregister_sse_indexer(
+ username, collection_id, _sse_cancel
+ )
safe_close(
rag_service,
"rag_service (index-collection SSE, deferred)",
)
- threading.Thread(
- target=_drain_and_close,
- daemon=True,
- name="index-collection-drain",
- ).start()
+ # Future invokes the callback exactly once, even if the
+ # worker finished between is_alive() and registration.
+ # Starting a separate drain thread could fail and strand
+ # admission after the indexing worker has already exited.
+ worker_finished.add_done_callback(_close_after_worker)
else:
+ _unregister_sse_indexer(username, collection_id, _sse_cancel)
safe_close(rag_service, "rag_service (index-collection SSE)")
response = WorkerCleanupStreamingResponse(
@@ -4473,35 +4543,12 @@ def _start_background_index_sync(
lock_key = (username, str(collection_id))
lock = _start_bg_index_locks.setdefault(lock_key, threading.Lock())
+ task_id = None
try:
with lock, get_user_db_session(username, db_password) as db_session:
- # Scan ALL in-progress indexing tasks for one that matches this
- # collection_id. The old query did `.first()` and then checked
- # — so it missed collision when another collection's task
- # happened to sort first, and also raced when two requests for
- # the same collection arrived concurrently. Scanning all rows
- # is fine: `TaskMetadata.status == "processing"` is bounded by
- # the number of in-flight indexes (small).
- in_progress = (
- db_session.query(TaskMetadata)
- .filter(
- TaskMetadata.task_type == "indexing",
- TaskMetadata.status == "processing",
- )
- .all()
- )
-
- for existing_task in in_progress:
- metadata = existing_task.metadata_json or {}
- if metadata.get("collection_id") == collection_id:
- return JSONResponse(
- {
- "success": False,
- "error": "Indexing is already in progress for this collection",
- "task_id": existing_task.task_id,
- },
- status_code=409,
- )
+ conflict = _indexing_conflict(db_session, username, collection_id)
+ if conflict:
+ return JSONResponse(conflict, status_code=409)
# A force-reindex drops the old vector collections, which needs
# the user's settings snapshot (provider + connection config,
@@ -4542,6 +4589,8 @@ def _start_background_index_sync(
)
db_session.add(task)
db_session.commit()
+ with _active_sse_indexers_lock:
+ _active_background_indexers[lock_key] = task_id
# Resolve per-job parallel fan-out here (request-scoped
# session) and forward into the worker — the worker itself
@@ -4564,16 +4613,19 @@ def _start_background_index_sync(
_bg_ctx = contextvars.copy_context()
def _ctx_worker():
- _bg_ctx.run(
- _background_index_worker,
- task_id,
- collection_id,
- username,
- db_password,
- force_reindex,
- _bg_max_workers,
- settings_snapshot=_bg_settings_snapshot,
- )
+ try:
+ _bg_ctx.run(
+ _background_index_worker,
+ task_id,
+ collection_id,
+ username,
+ db_password,
+ force_reindex,
+ _bg_max_workers,
+ settings_snapshot=_bg_settings_snapshot,
+ )
+ finally:
+ _unregister_background_indexer(username, collection_id, task_id)
thread = threading.Thread(target=_ctx_worker, daemon=True)
thread.start()
@@ -4590,6 +4642,15 @@ def _start_background_index_sync(
except Exception:
logger.exception("Failed to start background indexing")
+ if task_id is not None:
+ _update_task_status(
+ username,
+ db_password,
+ task_id,
+ status="failed",
+ error_message="Failed to start indexing. Please try again.",
+ )
+ _unregister_background_indexer(username, collection_id, task_id)
return JSONResponse(
{
"success": False,
diff --git a/tests/research_library/routes/conftest.py b/tests/research_library/routes/conftest.py
new file mode 100644
index 0000000000..7e26ee73c4
--- /dev/null
+++ b/tests/research_library/routes/conftest.py
@@ -0,0 +1,14 @@
+"""Isolate process-local collection indexing state in route tests."""
+
+import pytest
+
+from local_deep_research.web.routers import rag
+
+
[email protected](autouse=True)
+def isolate_indexing_admission(monkeypatch):
+ # Many route tests stub Thread.start, so their admitted jobs never run
+ # the worker's finally block. They must not reserve another test's collection.
+ monkeypatch.setattr(rag, "_active_sse_indexers", {})
+ monkeypatch.setattr(rag, "_active_background_indexers", {})
+ monkeypatch.setattr(rag, "_start_bg_index_locks", {})
diff --git a/tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.py b/tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.py
index e7ccac097d..81932c8322 100644
--- a/tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.py
+++ b/tests/research_library/routes/test_rag_routes_cancel_and_worker_wiring.py
@@ -20,7 +20,7 @@ worker-count clamping). This file only covers the ROUTE-level wiring that
sits on top of it: the process-local SSE cancel registry, the
settings -> ``max_workers`` plumbing, and the disconnect-time bounded
worker drain in ``index_collection``'s SSE ``finally`` (grace ``join``
-then deferral to a daemon ``index-collection-drain`` thread), none of
+then cleanup by the existing worker on completion), none of
which the service-level tests can see.
The router's route functions are plain (non-async) callables decorated
@@ -37,6 +37,8 @@ import time
from types import SimpleNamespace
from unittest.mock import Mock, patch
+import pytest
+
MODULE = "local_deep_research.web.routers.rag"
_DB_CTX = "local_deep_research.database.session_context"
_DB_PASS = "local_deep_research.database.session_passwords"
@@ -329,6 +331,7 @@ class TestIndexCollectionSSERegistrationLifecycle:
_active_sse_indexers_lock,
)
from local_deep_research.database.models.library import Collection
+ from local_deep_research.database.models.queue import TaskMetadata
mock_coll = Mock()
mock_coll.id = "coll-1"
@@ -336,6 +339,8 @@ class TestIndexCollectionSSERegistrationLifecycle:
mock_coll.embedding_model = "existing-model"
def query_side_effect(*models):
+ if models and models[0] is TaskMetadata:
+ return _build_mock_query(all_result=[])
if models and models[0] is Collection:
return _build_mock_query(first_result=mock_coll)
# _query_documents_to_index: query(DocumentCollection, Document)
@@ -405,8 +410,7 @@ def _make_recording_thread_cls(bounded_join_cap, on_bounded_join=None):
Instances created while this class is patched in as ``threading.Thread``
are collected in the class-level ``_created`` list (fresh per factory
- call), giving each test direct handles on the route's worker thread and
- any drain thread it spawns.
+ call), giving each test direct handles on any threads the route starts.
"""
created = []
@@ -454,27 +458,27 @@ class TestIndexCollectionDisconnectWorkerDrain:
"""``index_collection``'s generator ``finally`` must never block the
event-loop thread on an unbounded worker join at client-disconnect time:
it joins the parallel-indexing worker with ``timeout=5.0`` and, if the
- worker is STILL alive after that grace period, hands the remaining
- ``join`` + ``safe_close(rag_service)`` to a detached daemon thread named
- ``index-collection-drain``; only when the worker has already exited (or
- exits within the grace join) is the service closed inline.
+ worker is STILL alive after that grace period, registers cleanup on the
+ worker's completion. When the worker has already exited (or exits within
+ the grace join), the service is closed inline.
Regressions caught: dropping the ``timeout=5.0`` (event loop blocked for
the whole embedding batch on disconnect), closing the service inline while
the worker still holds it (use-after-close), never closing it on the
- deferred path (leak), or making the drain thread non-daemon / eagerly
- joined.
+ deferred path (leak), or requiring another thread to finish cleanup.
"""
@contextlib.contextmanager
- def _open_stream_mid_indexing(self, parallel_side_effect, thread_cls):
- """Drive ``index_collection`` up to its first ``progress`` SSE event —
- i.e. suspended at a yield with the worker thread started — then hand
+ def _open_stream_mid_indexing(
+ self, parallel_side_effect, thread_cls, *, expected_event="progress"
+ ):
+ """Drive ``index_collection`` up to its first worker event, then hand
control to the test body. All route-boundary patches stay active for
- the body's duration (the deferred drain resolves ``safe_close`` from
+ the body's duration (deferred cleanup resolves ``safe_close`` from
the module namespace at call time)."""
from local_deep_research.web.routers.rag import index_collection
from local_deep_research.database.models.library import Collection
+ from local_deep_research.database.models.queue import TaskMetadata
mock_coll = Mock()
mock_coll.id = "coll-1"
@@ -482,6 +486,8 @@ class TestIndexCollectionDisconnectWorkerDrain:
mock_coll.embedding_model = "existing-model"
def query_side_effect(*models):
+ if models and models[0] is TaskMetadata:
+ return _build_mock_query(all_result=[])
if models and models[0] is Collection:
return _build_mock_query(first_result=mock_coll)
return _build_mock_query(
@@ -524,10 +530,9 @@ class TestIndexCollectionDisconnectWorkerDrain:
gen = captured["generator"]
# 1st yield: the 'start' event (worker thread not yet created).
assert '"start"' in next(gen)
- # 2nd yield: the first 'progress' event — the worker thread has
- # been started and pushed one progress item before (possibly)
- # blocking, so the generator is now suspended mid-indexing.
- assert '"progress"' in next(gen)
+ # 2nd yield: progress from the running worker, or an error if
+ # the worker could not start.
+ assert f'"{expected_event}"' in next(gen)
yield gen, mock_safe_close, mock_rag_service
@staticmethod
@@ -608,10 +613,9 @@ class TestIndexCollectionDisconnectWorkerDrain:
"index-collection-parallel"
]
- def test_stuck_worker_defers_join_and_close_to_daemon_drain_thread(self):
+ def test_stuck_worker_defers_cleanup_until_worker_completion(self):
"""Worker still alive AFTER the grace join -> close must return
- promptly (event-loop path), spawn a daemon ``index-collection-drain``
- thread, and defer ``safe_close`` until the worker actually exits."""
+ promptly and defer cleanup until its indexing writes have stopped."""
from local_deep_research.web.routers.rag import (
_active_sse_indexers,
_active_sse_indexers_lock,
@@ -639,7 +643,7 @@ class TestIndexCollectionDisconnectWorkerDrain:
# Event-loop path returned promptly despite the stuck worker.
assert elapsed < 2.0
# The grace join was bounded at 5.0s (first join call).
- (worker, drain) = thread_cls._created
+ (worker,) = thread_cls._created
assert worker.join_calls[0] == 5.0
assert worker.is_alive() is True
@@ -647,13 +651,8 @@ class TestIndexCollectionDisconnectWorkerDrain:
# nothing closed yet while the worker still holds the service.
assert mock_safe_close.call_count == 0
- # The drain thread is detached (daemon) and clearly named.
- assert drain.name == "index-collection-drain"
- assert drain.daemon is True
- assert drain._real.is_alive() is True
-
- # The finally already signalled cancellation and deregistered
- # the stream even though the drain is still pending.
+ # Cancellation is signalled immediately, but admission stays
+ # closed while the worker can still write to this collection.
is_cancelled = (
mock_rag_service.index_documents_parallel.call_args.kwargs[
"is_cancelled"
@@ -661,28 +660,151 @@ class TestIndexCollectionDisconnectWorkerDrain:
)
assert is_cancelled() is True
with _active_sse_indexers_lock:
- assert ("testuser", "coll-1") not in _active_sse_indexers
+ assert ("testuser", "coll-1") in _active_sse_indexers
+ from local_deep_research.web.routers.rag import (
+ _start_background_index_sync,
+ )
+
+ rejected = _start_background_index_sync(
+ "coll-1", "testuser", None, True
+ )
+ assert rejected.status_code == 409
- # Release the worker: the drain thread must now join it and
- # close the service with the deferred label.
+ # The existing worker performs deferred cleanup before exit.
release.set()
- deadline = time.monotonic() + 5
- while (
- mock_safe_close.call_count == 0
- and time.monotonic() < deadline
- ):
- time.sleep(0.01)
+ worker._real.join(timeout=5)
+ assert not worker.is_alive()
mock_safe_close.assert_called_once_with(
mock_rag_service,
"rag_service (index-collection SSE, deferred)",
)
- # Unbounded join happened on the drain thread, not the
- # event-loop path.
- assert worker.join_calls == [5.0, None]
- drain._real.join(timeout=5)
- assert drain._real.is_alive() is False
+ assert worker.join_calls == [5.0]
+ with _active_sse_indexers_lock:
+ assert ("testuser", "coll-1") not in _active_sse_indexers
finally:
release.set()
+ for thread in thread_cls._created:
+ if thread._real.ident is not None:
+ thread._real.join(timeout=5)
+
+ @pytest.mark.parametrize("worker_fails", [False, True])
+ def test_disconnect_cleanup_needs_no_additional_thread(
+ self, monkeypatch, worker_fails
+ ):
+ """Thread exhaustion must not strand admission after a worker exits."""
+ from local_deep_research.web.routers import rag
+
+ release = threading.Event()
+
+ def blocked_parallel(*args, **kwargs):
+ kwargs["progress_callback"](1, 1, "a.txt", "success")
+ assert release.wait(timeout=15), "test worker never released"
+ if worker_fails:
+ raise RuntimeError("indexing failed")
+ return self._aggregate()
+
+ thread_cls = _make_recording_thread_cls(bounded_join_cap=0.01)
+ ordinary_start = thread_cls.start
+
+ def refuse_additional_thread(thread):
+ if any(
+ other is not thread and other._real.ident is not None
+ for other in thread_cls._created
+ ):
+ raise RuntimeError("cannot start new thread")
+ ordinary_start(thread)
+
+ monkeypatch.setattr(thread_cls, "start", refuse_additional_thread)
+ with self._open_stream_mid_indexing(blocked_parallel, thread_cls) as (
+ gen,
+ mock_safe_close,
+ service,
+ ):
+ worker = thread_cls._created[0]
+ try:
+ gen.close()
+ assert worker.is_alive()
+ mock_safe_close.assert_not_called()
+ assert ("testuser", "coll-1") in rag._active_sse_indexers
+ finally:
+ release.set()
+ worker._real.join(timeout=5)
+
+ assert not worker.is_alive()
+ assert ("testuser", "coll-1") not in rag._active_sse_indexers
+ mock_safe_close.assert_called_once_with(
+ service, "rag_service (index-collection SSE, deferred)"
+ )
+ retry = threading.Event()
+ try:
+ assert rag._register_sse_indexer(
+ "testuser", "coll-1", None, retry
+ )
+ finally:
+ rag._unregister_sse_indexer("testuser", "coll-1", retry)
+
+ def test_worker_completing_before_callback_registration_cleans_up_once(
+ self, monkeypatch
+ ):
+ """Completion between the liveness check and registration is safe."""
+ from local_deep_research.web.routers import rag
+
+ release = threading.Event()
+ thread_cls = _make_recording_thread_cls(bounded_join_cap=0.01)
+ actual_future = rag.Future
+
+ class FinishBeforeCallback(actual_future):
+ def add_done_callback(self, callback):
+ release.set()
+ worker = thread_cls._created[0]
+ worker._real.join(timeout=5)
+ assert not worker.is_alive()
+ assert self.done()
+ super().add_done_callback(callback)
+
+ monkeypatch.setattr(rag, "Future", FinishBeforeCallback)
+
+ def blocked_parallel(*args, **kwargs):
+ kwargs["progress_callback"](1, 1, "a.txt", "success")
+ assert release.wait(timeout=15), "test worker never released"
+ return self._aggregate()
+
+ with self._open_stream_mid_indexing(blocked_parallel, thread_cls) as (
+ gen,
+ mock_safe_close,
+ service,
+ ):
+ try:
+ gen.close()
+ assert ("testuser", "coll-1") not in rag._active_sse_indexers
+ mock_safe_close.assert_called_once_with(
+ service, "rag_service (index-collection SSE, deferred)"
+ )
+ gen.close()
+ assert mock_safe_close.call_count == 1
+ finally:
+ release.set()
+ thread_cls._created[0]._real.join(timeout=5)
+
+ def test_failed_indexing_thread_start_releases_admission(self, monkeypatch):
+ """No completion callback is needed when the worker never starts."""
+ from local_deep_research.web.routers import rag
+
+ thread_cls = _make_recording_thread_cls(bounded_join_cap=0.01)
+
+ def fail_start(thread):
+ raise RuntimeError("cannot start new thread")
+
+ monkeypatch.setattr(thread_cls, "start", fail_start)
+ with self._open_stream_mid_indexing(
+ Mock(), thread_cls, expected_event="error"
+ ) as (gen, mock_safe_close, service):
+ gen.close()
+ assert ("testuser", "coll-1") not in rag._active_sse_indexers
+ service.index_documents_parallel.assert_not_called()
+ mock_safe_close.assert_called_once_with(
+ service, "rag_service (index-collection SSE)"
+ )
# ---------------------------------------------------------------------------
@@ -826,6 +948,7 @@ class TestMaxWorkersPlumbedFromSettings:
never call ``get_settings_manager`` from its worker thread."""
from local_deep_research.web.routers.rag import index_collection
from local_deep_research.database.models.library import Collection
+ from local_deep_research.database.models.queue import TaskMetadata
mock_coll = Mock()
mock_coll.id = "coll-1"
@@ -833,6 +956,8 @@ class TestMaxWorkersPlumbedFromSettings:
mock_coll.embedding_model = "existing-model"
def query_side_effect(*models):
+ if models and models[0] is TaskMetadata:
+ return _build_mock_query(all_result=[])
if models and models[0] is Collection:
return _build_mock_query(first_result=mock_coll)
return _build_mock_query(
diff --git a/tests/research_library/routes/test_rag_routes_gaps_main_port.py b/tests/research_library/routes/test_rag_routes_gaps_main_port.py
index ba7cdd0977..40b34f747c 100644
--- a/tests/research_library/routes/test_rag_routes_gaps_main_port.py
+++ b/tests/research_library/routes/test_rag_routes_gaps_main_port.py
@@ -152,10 +152,13 @@ def _collection_then_docs(collection, docs=()):
queried model is equivalent and immune to an extra lookup being added.
"""
from local_deep_research.database.models.library import Collection
+ from local_deep_research.database.models.queue import TaskMetadata
docs = list(docs)
def side_effect(*models):
+ if models and models[0] is TaskMetadata:
+ return _build_mock_query(all_result=[])
if models and models[0] is Collection:
return _build_mock_query(first_result=collection)
return _build_mock_query(all_result=docs)
diff --git a/tests/web/routers/test_rag_indexing_admission.py b/tests/web/routers/test_rag_indexing_admission.py
new file mode 100644
index 0000000000..6b2d9319ce
--- /dev/null
+++ b/tests/web/routers/test_rag_indexing_admission.py
@@ -0,0 +1,272 @@
+"""Collection indexing admission across the two streams and background jobs."""
+
+import json
+import threading
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import contextmanager
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker
+
+from local_deep_research.database.models import Base
+from local_deep_research.database.models.library import Collection
+from local_deep_research.database.models.queue import TaskMetadata
+from local_deep_research.web.routers import rag
+
+
+def admission(tmp_path, monkeypatch):
+ engine = create_engine(
+ f"sqlite:///{tmp_path / 'admission.db'}",
+ connect_args={"check_same_thread": False},
+ )
+ Base.metadata.create_all(
+ engine, tables=[Collection.__table__, TaskMetadata.__table__]
+ )
+ sessions = sessionmaker(bind=engine)
+
+ @contextmanager
+ def session_scope(*args, **kwargs):
+ with sessions() as session:
+ yield session
+
+ with sessions.begin() as session:
+ session.add(
+ Collection(
+ id="collection", name="Existing", embedding_model="model"
+ )
+ )
+ monkeypatch.setattr(
+ "local_deep_research.database.session_context.get_user_db_session",
+ session_scope,
+ )
+ monkeypatch.setattr(rag, "_active_sse_indexers", {})
+ monkeypatch.setattr(rag, "_active_background_indexers", {})
+ monkeypatch.setattr(rag, "_start_bg_index_locks", {})
+ settings = Mock()
+ settings.get_setting.return_value = 4
+ monkeypatch.setattr(rag, "get_settings_manager", lambda *a: settings)
+ monkeypatch.setattr(
+ "local_deep_research.utilities.db_utils.get_settings_manager",
+ lambda *a: settings,
+ )
+ service = Mock()
+ monkeypatch.setattr(rag, "get_rag_service", lambda *a, **k: service)
+ monkeypatch.setattr(
+ rag,
+ "_query_documents_to_index",
+ lambda *a: [
+ (
+ None,
+ SimpleNamespace(id="document", title="Doc", filename="doc.txt"),
+ )
+ ],
+ )
+ monkeypatch.setattr(
+ rag,
+ "WorkerCleanupStreamingResponse",
+ lambda content, **kwargs: SimpleNamespace(content=content, headers={}),
+ )
+ started = threading.Event()
+ release = threading.Event()
+ finished = threading.Event()
+
+ def worker(
+ task_id,
+ collection_id,
+ username,
+ password,
+ *args,
+ settings_snapshot=None,
+ ):
+ started.set()
+ try:
+ assert release.wait(10), (
+ "test did not release the background worker"
+ )
+ rag._update_task_status(
+ username, password, task_id, status="completed"
+ )
+ finally:
+ finished.set()
+
+ monkeypatch.setattr(rag, "_background_index_worker", worker)
+ threads = []
+ thread_class = threading.Thread
+
+ def track_thread(*args, **kwargs):
+ thread = thread_class(*args, **kwargs)
+ threads.append(thread)
+ return thread
+
+ monkeypatch.setattr(rag.threading, "Thread", track_thread)
+ state = SimpleNamespace(
+ sessions=sessions,
+ started=started,
+ release=release,
+ finished=finished,
+ threads=threads,
+ service=service,
+ thread_class=thread_class,
+ )
+ yield state
+ release.set()
+ for thread in threads:
+ if thread.ident is not None:
+ thread.join(timeout=10)
+ assert not thread.is_alive()
+ engine.dispose()
+
+
+def _stream(kind, *, force=False, username="user"):
+ request = SimpleNamespace(
+ session={},
+ query_params={
+ "collection_id": "collection",
+ "force_reindex": str(force).lower(),
+ },
+ )
+ if kind == "bulk":
+ return rag.index_all(request, username=username).content
+ return rag.index_collection(
+ request, "collection", username=username
+ ).content
+
+
[email protected]("first", ["single", "bulk", "background"])
[email protected]("second", ["single", "bulk", "background"])
+def test_collection_indexers_exclude_each_other(
+ admission, monkeypatch, first, second
+):
+ stream = None
+ if first == "background":
+ accepted = rag._start_background_index_sync(
+ "collection", "user", None, False
+ )
+ assert accepted["success"]
+ assert admission.started.wait(5)
+ else:
+ stream = _stream(first)
+ assert (
+ json.loads(next(stream).removeprefix("data: "))["type"] == "start"
+ )
+
+ reset = Mock(
+ side_effect=AssertionError("a competing run must not reset the index")
+ )
+ monkeypatch.setattr(rag, "_reset_collection_for_reindex", reset)
+ try:
+ if second == "background":
+ refused = rag._start_background_index_sync(
+ "collection", "user", None, True
+ )
+ assert refused.status_code == 409
+ else:
+ contender = _stream(second, force=True)
+ try:
+ event = json.loads(next(contender).removeprefix("data: "))
+ assert event == {
+ "type": "error",
+ "error": "Indexing is already in progress for this collection",
+ }
+ finally:
+ contender.close()
+ reset.assert_not_called()
+ admission.service.index_documents_parallel.assert_not_called()
+ finally:
+ if stream is not None:
+ stream.close()
+
+
+def test_cancelled_background_worker_keeps_admission_until_it_stops(admission):
+ accepted = rag._start_background_index_sync(
+ "collection", "user", None, False
+ )
+ assert admission.started.wait(5)
+ rag._do_update_task_status(
+ "user", None, accepted["task_id"], status="cancelled"
+ )
+ assert (
+ rag._start_background_index_sync(
+ "collection", "user", None, True
+ ).status_code
+ == 409
+ )
+ stream = _stream("single", force=True)
+ try:
+ assert (
+ json.loads(next(stream).removeprefix("data: "))["type"] == "error"
+ )
+ finally:
+ stream.close()
+ admission.release.set()
+ admission.threads[0].join(timeout=5)
+ assert not admission.threads[0].is_alive()
+ assert not rag._active_background_indexers
+ assert rag._start_background_index_sync("collection", "user", None, False)[
+ "success"
+ ]
+
+
+def test_failed_thread_start_releases_admission_and_fails_task(
+ admission, monkeypatch
+):
+ def fail_start(self):
+ raise RuntimeError("cannot start new thread")
+
+ # The fixture tracks real Thread instances; fail their actual start method.
+ monkeypatch.setattr(admission.thread_class, "start", fail_start)
+ refused = rag._start_background_index_sync(
+ "collection", "user", None, False
+ )
+ assert refused.status_code == 500
+ assert not rag._active_background_indexers
+ with admission.sessions() as session:
+ task = session.query(TaskMetadata).one()
+ assert task.status == "failed"
+ assert task.completed_at is not None
+
+
+def test_racing_stream_and_background_request_admit_exactly_one(admission):
+ start = threading.Barrier(2)
+ cancel = threading.Event()
+
+ def stream_request():
+ start.wait(timeout=5)
+ return rag._register_sse_indexer("user", "collection", None, cancel)
+
+ def background_request():
+ start.wait(timeout=5)
+ return rag._start_background_index_sync(
+ "collection", "user", None, False
+ )
+
+ try:
+ with ThreadPoolExecutor(max_workers=2) as pool:
+ stream = pool.submit(stream_request)
+ background = pool.submit(background_request)
+ stream_admitted = stream.result(timeout=5)
+ background_result = background.result(timeout=5)
+ if stream_admitted:
+ assert background_result.status_code == 409
+ else:
+ assert background_result["success"] is True
+ finally:
+ rag._unregister_sse_indexer("user", "collection", cancel)
+
+
+def test_other_users_and_collections_can_index(admission):
+ cancel = threading.Event()
+ assert rag._register_sse_indexer("user", "collection", None, cancel)
+ try:
+ assert rag._start_background_index_sync(
+ "other-collection", "user", None, False
+ )["success"]
+ assert rag._start_background_index_sync(
+ "collection", "other-user", None, False
+ )["success"]
+ finally:
+ rag._unregister_sse_indexer("user", "collection", cancel)
diff --git a/tests/web/routers/test_rag_indexing_pipeline.py b/tests/web/routers/test_rag_indexing_pipeline.py
index a336c4d7a5..d296a9a086 100644
--- a/tests/web/routers/test_rag_indexing_pipeline.py
+++ b/tests/web/routers/test_rag_indexing_pipeline.py
@@ -41,12 +41,9 @@ so the xfail cannot be an artifact of the harness:
(credential *shapes* only) into ``TaskMetadata.error_message``, which
``get_index_status`` returns verbatim.
-4. **Concurrent indexing of one collection is not mutually excluded.**
- The SSE indexer registers only a process-local cancel event and creates
- no ``TaskMetadata`` row, so ``_start_background_index_sync``'s
- in-progress guard cannot see it and admits a second, concurrent
- force-reindex of the same collection -- whose reset prologue then
- destroys the first run's committed work.
+4. **Concurrent collection indexing is mutually excluded.** The shared
+ admission gate checks both streaming workers and background tasks before
+ a second run can reach the destructive reset helper.
Plus a cancellation gap: ``cancel_indexing`` scans in-progress tasks with
``.first()`` (``start_background_index`` was fixed to ``.all()`` for
@@ -923,13 +920,10 @@ def _start_background_reindex(rag_mod, collection_id):
class TestConcurrentIndexingOfOneCollection:
- """The SSE indexer and the background indexer do not exclude each
- other, so both can force-reindex the SAME collection at once."""
+ """Streaming and background requests must not rebuild one collection together."""
def test_a_duplicate_background_task_is_rejected(self, world, seeded):
- """Control: the in-progress guard DOES work when the competing
- indexer left a ``TaskMetadata`` row -- so the xfail below is about
- the SSE path's invisibility, not a broken guard."""
+ """An existing background task blocks another collection rebuild."""
from local_deep_research.web.routers import rag as rag_mod
collection_id, _ = seeded
@@ -939,22 +933,6 @@ class TestConcurrentIndexingOfOneCollection:
assert getattr(result, "status_code", None) == 409
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "index_collection (the SSE indexer) records its run ONLY in the "
- "process-local _active_sse_indexers registry; it never inserts a "
- "TaskMetadata row. _start_background_index_sync's guard scans "
- "TaskMetadata alone and takes a per-(user, collection) lock the "
- "SSE path never takes, so it admits a concurrent force-reindex "
- "of a collection an SSE run is already rebuilding. Both then run "
- "_reset_collection_for_reindex, each deleting the other's "
- "committed chunks/RAGIndex rows and unlinking its .faiss file "
- "mid-run (the FAISS lock is per index_path and does not cover "
- "the reset). Fix by having the SSE path register in the same "
- "TaskMetadata/lock namespace the background path checks."
- ),
- )
def test_an_active_sse_indexer_blocks_a_background_reindex(
self, world, seeded
):
@@ -982,9 +960,7 @@ class TestConcurrentIndexingOfOneCollection:
def test_reset_prologue_destroys_committed_work_of_another_run(
self, world, seeded
):
- """The blast radius of that interleave: the second run's reset
- prologue is unconditional and wipes work the first run has already
- committed."""
+ """The raw reset helper is destructive; callers must hold admission."""
from local_deep_research.web.routers.rag import (
_reset_collection_for_reindex,
_unlink_reindex_faiss_files,
diff --git a/tests/web/routers/test_streaming_contracts.py b/tests/web/routers/test_streaming_contracts.py
index b9de3c4081..4d0a32a111 100644
--- a/tests/web/routers/test_streaming_contracts.py
+++ b/tests/web/routers/test_streaming_contracts.py
@@ -48,8 +48,8 @@ constructs one):
``index-collection-parallel`` thread so the generator's main thread
can keep yielding SSE heartbeats, and on generator ``finally`` (client
disconnect or normal completion) it joins that worker with a bounded
- 5s grace period, deferring to a daemon ``index-collection-drain``
- thread if the worker is still alive after the grace period.
+ 5s grace period, registering cleanup on worker completion if it is
+ still alive after the grace period.
Coverage map for the four requested contracts:
@@ -578,9 +578,8 @@ def find_unbounded_thread_join_in_generator_scope(func_node):
# file::L<lineno> -> justification. Seeded ONLY with verified-safe cases.
# (Currently empty: index_collection's only own-scope join is
-# `worker_thread.join(timeout=5.0)`; the unbounded
-# `_lingering_worker.join()` lives inside the nested `_drain_and_close`
-# closure, which this scanner does not search.)
+# `worker_thread.join(timeout=5.0)`; deferred cleanup uses a worker-completion
+# callback without another join.)
UNBOUNDED_JOIN_ALLOWLIST: dict[str, str] = {}
@@ -603,10 +602,8 @@ def test_no_unbounded_thread_join_in_streaming_generator_own_scope():
"own scope. On client disconnect this runs on the generator-close "
"path and blocks it for as long as the worker takes -- use "
"join(timeout=...) with a bounded grace period, and if the worker "
- "is still alive after that, defer the remaining join + cleanup to "
- "a nested (daemon) thread body, matching rag.py's index_collection "
- "('grace join, then hand off to index-collection-drain').\n"
- + "\n".join(violations)
+ "is still alive after that, defer cleanup until worker completion, "
+ "matching rag.py's index_collection.\n" + "\n".join(violations)
)