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.

feat(library): opt-in scheduled sweep to index unindexed library documents (#3939 follow-up) (#4627)

LearningCircuit4b509b82514f
diff --git a/.gitleaks.toml b/.gitleaks.toml
index 9a0030edf5..183d152b3e 100644
--- a/.gitleaks.toml
+++ b/.gitleaks.toml
@@ -148,6 +148,9 @@ paths = [
'''src/local_deep_research/research_library/services/library_rag_service\.py$''',
# RAG service factory passes db_password variable names (not actual secrets)
'''src/local_deep_research/research_library/services/rag_service_factory\.py$''',
+ # Background scheduler passes db_password variable names to DB sessions and
+ # the RAG factory (not actual secrets)
+ '''src/local_deep_research/scheduler/background\.py$''',
# Encrypted DB manager uses key derivation and password parameters (not actual secrets)
'''src/local_deep_research/database/encrypted_db\.py$''',
# Metrics search tracker uses password variable names for DB credentials (not actual secrets)
diff --git a/changelog.d/+library-index-sweep.feature.md b/changelog.d/+library-index-sweep.feature.md
new file mode 100644
index 0000000000..1d05c33904
--- /dev/null
+++ b/changelog.d/+library-index-sweep.feature.md
@@ -0,0 +1 @@
+**Unified background reconciler that indexes ANY unindexed document.** A single scheduled job now indexes every unindexed document so nothing is permanently missed: (a) library uploads that the immediate auto-index queue dropped when saturated, and (b) research downloads that were never ingested into your library. Enable the **Document Scheduler** and then **"Auto-index documents in the background"** (both off by default) to turn it on — the sweep only runs while the document scheduler itself is enabled. The reconciler is idempotent (already-indexed documents are skipped), processes a small bounded batch per run so a large backlog self-heals gradually, and honors each collection's own embedding configuration. The two cases are budgeted independently, so a backlog of documents that keep failing to index can never starve the other case (research downloads still get indexed even when many library uploads are failing). This replaces both the old library-only sweep and the separate per-research RAG-indexing pass that used to run inside the document scheduler. The legacy **"Generate RAG Embeddings"** setting is kept as a deprecated alias — it now enables this same reconciler — so existing users keep getting their research downloads indexed with no change required.
diff --git a/src/local_deep_research/defaults/settings_document_scheduler.json b/src/local_deep_research/defaults/settings_document_scheduler.json
index f15f440209..c926308ed5 100644
--- a/src/local_deep_research/defaults/settings_document_scheduler.json
+++ b/src/local_deep_research/defaults/settings_document_scheduler.json
@@ -57,11 +57,25 @@
},
"document_scheduler.generate_rag": {
"category": "document_scheduler",
- "description": "Generate RAG embeddings for semantic search",
+ "description": "Index documents in the background for semantic search. LEGACY/DEPRECATED: this is now equivalent to \"Auto-index documents in the background\" below — both enable the unified reconciler that indexes every unindexed document (library uploads AND research downloads). Kept for backward compatibility so existing users keep their research downloads indexed; prefer the auto-index setting for new configurations.",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Generate RAG Embeddings",
+ "name": "Generate RAG Embeddings (legacy)",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
+ "document_scheduler.sweep_library_collections": {
+ "category": "document_scheduler",
+ "description": "Periodically index ALL unindexed documents in the background — both library uploads that weren't indexed immediately (e.g. because the immediate auto-index queue was full) AND research downloads that haven't been ingested into your library yet. Idempotent and processed in small batches per run; already-indexed documents are skipped. Off by default. Requires \"Enable Document Scheduler\" above to be on — the background sweep only runs while the document scheduler is enabled.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Auto-index documents in the background",
"options": null,
"step": null,
"type": "APP",
diff --git a/src/local_deep_research/scheduler/background.py b/src/local_deep_research/scheduler/background.py
index defe1aa267..689b928fcd 100644
--- a/src/local_deep_research/scheduler/background.py
+++ b/src/local_deep_research/scheduler/background.py
@@ -17,14 +17,16 @@ from ..settings.manager import SnapshotSettingsContext
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.base import JobLookupError
+from sqlalchemy import func
from ..constants import ResearchStatus
from ..database.credential_store_base import CredentialStoreBase
from ..database.session_context import safe_rollback
from ..database.thread_local_session import thread_cleanup
from ..security.log_sanitizer import redact_secrets
-# RAG indexing imports
-from ..research_library.services.library_rag_service import LibraryRAGService
+# RAG indexing imports. The reconciler builds RAG services via the lazily
+# imported ``rag_service_factory`` (see _reconcile_unindexed_documents), so the
+# concrete ``LibraryRAGService`` is no longer imported at module scope.
from ..database.library_init import get_default_library_id
from ..database.models.library import Document, DocumentCollection
from ..constants import DEFAULT_SEARCH_TOOL
@@ -32,6 +34,13 @@ from ..constants import DEFAULT_SEARCH_TOOL
SCHEDULER_AVAILABLE = True # Always available since it's a required dependency
+# Per-tick cap for the opt-in library-collection index sweep. Bounds the work
+# done in a single scheduler thread tick so a large backlog of unindexed
+# documents self-heals gradually over successive ticks instead of blocking the
+# worker thread (the sweep is self-rate-limited by APScheduler max_instances=1
+# plus this batch cap).
+_LIBRARY_SWEEP_BATCH = 50
+
class SchedulerCredentialStore(CredentialStoreBase):
"""Credential store for the news scheduler.
@@ -73,6 +82,7 @@ class DocumentSchedulerSettings:
download_pdfs: bool = False
extract_text: bool = True
generate_rag: bool = False
+ sweep_library_collections: bool = False
last_run: str = ""
@classmethod
@@ -274,6 +284,9 @@ class BackgroundJobScheduler:
generate_rag=sm.get_setting(
"document_scheduler.generate_rag", False
),
+ sweep_library_collections=sm.get_setting(
+ "document_scheduler.sweep_library_collections", False
+ ),
last_run=sm.get_setting("document_scheduler.last_run", ""),
)
@@ -478,6 +491,45 @@ class BackgroundJobScheduler:
self.invalidate_user_settings_cache(username)
logger.info(f"User {username} unregistered successfully")
+ def reschedule_document_jobs(self, username: str) -> bool:
+ """(Re)schedule the document-processing + reconciler jobs for an
+ ACTIVE user against their current settings.
+
+ Call this after a ``document_scheduler.*`` setting changes so the
+ change takes effect on the next interval tick instead of only after
+ the user logs out and back in. Without it, ``_schedule_reconciler``
+ runs only via the login path (``update_user_info`` ->
+ ``_schedule_user_subscriptions`` -> ``_schedule_document_processing``):
+ the runtime gate inside ``_reconcile_unindexed_documents`` neutralises
+ a stale job after a *disable*, but an *enable* (including toggling the
+ legacy ``generate_rag`` arm, which on older builds took effect on the
+ next tick) would otherwise never create the ``{username}_library_sweep``
+ job until the next login.
+
+ Relies on the cache having already been invalidated by the caller
+ (``invalidate_settings_caches``) so ``_schedule_document_processing``
+ re-reads fresh settings. No password argument is needed: the job is
+ rebuilt from the credentials the scheduler already holds for the active
+ session. Returns ``True`` if a reschedule was performed, ``False`` for
+ a user the scheduler isn't tracking (their jobs are built from current
+ settings on their next login) or when the scheduler isn't running.
+ """
+ if not self.is_running:
+ return False
+ with self.lock:
+ if username not in self.user_sessions:
+ logger.debug(
+ f"[DOC_SCHEDULER] reschedule_document_jobs: {username} "
+ "not an active scheduler session; skipping"
+ )
+ return False
+ self.user_sessions[username]["last_activity"] = datetime.now(UTC)
+ # Re-reads fresh settings (cache invalidated by the caller) and
+ # re-adds the document-processing job + reconciler per current
+ # settings; both use replace_existing=True so this is idempotent.
+ self._schedule_document_processing(username)
+ return True
+
def _schedule_user_subscriptions(self, username: str):
"""Schedule all active subscriptions for a user."""
logger.info(f"_schedule_user_subscriptions called for {username}")
@@ -646,7 +698,8 @@ class BackgroundJobScheduler:
logger.info(
f"[DOC_SCHEDULER] User {username} document settings: enabled={settings.enabled}, "
f"interval={settings.interval_seconds}s, pdfs={settings.download_pdfs}, "
- f"text={settings.extract_text}, rag={settings.generate_rag}"
+ f"text={settings.extract_text}, "
+ f"index={settings.generate_rag or settings.sweep_library_collections}"
)
# Schedule document processing job
@@ -699,6 +752,10 @@ class BackgroundJobScheduler:
f"[DOC_SCHEDULER] Failed to verify job {job_id} exists!"
)
+ # Schedule (or tear down) the unindexed-document reconciler,
+ # mirroring the document-processing job's lifecycle.
+ self._schedule_reconciler(username, settings, session_info)
+
except Exception as e:
# No ``password`` local here, but the caller frame
# (``_schedule_user_subscriptions``) holds the SQLCipher
@@ -714,6 +771,58 @@ class BackgroundJobScheduler:
f"Error scheduling document processing for {username}: {safe_msg}"
)
+ def _schedule_reconciler(
+ self,
+ username: str,
+ settings: DocumentSchedulerSettings,
+ session_info: Dict[str, Any],
+ ) -> None:
+ """Add or remove the unindexed-document reconciler job.
+
+ Mirrors the document-processing job lifecycle in
+ ``_schedule_document_processing``: the job is (re)created only when
+ EITHER ``sweep_library_collections`` OR ``generate_rag`` is enabled, and
+ removed (and dropped from the session's tracked-jobs set) when both are
+ off — so toggling the settings off and rescheduling tears the job down
+ cleanly. The reconciler indexes every unindexed document (uploaded
+ library docs AND research downloads), so both settings gate it: the
+ ``generate_rag`` OR-arm preserves the legacy "index research downloads"
+ behaviour that used to live inline in ``_process_user_documents``.
+ """
+ job_id = f"{username}_library_sweep"
+
+ # Always remove any existing instance first so a disabled setting
+ # tears the job down and a changed interval is re-applied.
+ try:
+ self.scheduler.remove_job(job_id)
+ session_info["scheduled_jobs"].discard(job_id)
+ logger.debug(f"[RECONCILER] Removed existing job {job_id}")
+ except JobLookupError:
+ pass # Job doesn't exist, that's fine
+
+ if not (settings.sweep_library_collections or settings.generate_rag):
+ logger.debug(
+ f"[RECONCILER] Indexing disabled for {username}; not scheduling"
+ )
+ return
+
+ self.scheduler.add_job(
+ func=self._wrap_job(self._reconcile_unindexed_documents),
+ args=[username],
+ trigger="interval",
+ seconds=settings.interval_seconds,
+ id=job_id,
+ name=f"Unindexed Document Reconciler for {username}",
+ jitter=60,
+ max_instances=1, # Self-rate-limit: no overlapping runs
+ replace_existing=True,
+ )
+ session_info["scheduled_jobs"].add(job_id)
+ logger.info(
+ f"[RECONCILER] Scheduled unindexed-document reconciler job {job_id} "
+ f"for {username} with {settings.interval_seconds}s interval"
+ )
+
def _arm_egress_backstop(self, settings_manager, username: str) -> None:
"""Set the audit-hook egress context from the user's saved settings so
scheduled document downloads run under the same secondary net as an
@@ -772,18 +881,21 @@ class BackgroundJobScheduler:
logger.info(
f"[DOC_SCHEDULER] Processing settings for {username}: "
- f"pdfs={settings.download_pdfs}, text={settings.extract_text}, rag={settings.generate_rag}"
+ f"pdfs={settings.download_pdfs}, text={settings.extract_text}"
)
+ # RAG indexing has moved to ``_reconcile_unindexed_documents`` (its
+ # own scheduled job), so ``generate_rag`` no longer drives any work
+ # in this download/extract pass. Only the file-producing passes gate
+ # whether this method runs.
if not any(
[
settings.download_pdfs,
settings.extract_text,
- settings.generate_rag,
]
):
logger.info(
- f"[DOC_SCHEDULER] No processing options enabled for user {username}"
+ f"[DOC_SCHEDULER] No download/extract options enabled for user {username}"
)
return
@@ -1065,131 +1177,16 @@ class BackgroundJobScheduler:
f"[DOC_SCHEDULER] Failed to extract text for research {research.id}: {safe_msg}"
)
- if settings.generate_rag:
- logger.info(
- f"[DOC_SCHEDULER] Generating RAG embeddings for research {research.id}"
- )
- try:
- # Get embedding settings from user configuration
- embedding_model = settings_manager.get_setting(
- "local_search_embedding_model",
- "all-MiniLM-L6-v2",
- )
- embedding_provider = (
- settings_manager.get_setting(
- "local_search_embedding_provider",
- "sentence_transformers",
- )
- )
- chunk_size = int(
- settings_manager.get_setting(
- "local_search_chunk_size", 1000
- )
- )
- chunk_overlap = int(
- settings_manager.get_setting(
- "local_search_chunk_overlap", 200
- )
- )
-
- # Initialize RAG service with user's embedding configuration
- with LibraryRAGService(
- username=username,
- embedding_model=embedding_model,
- embedding_provider=embedding_provider,
- chunk_size=chunk_size,
- chunk_overlap=chunk_overlap,
- db_password=password,
- ) as rag_service:
- # Get default Library collection ID
- library_collection_id = (
- get_default_library_id(
- username, password
- )
- )
-
- # Query for unindexed documents from this research session
- documents_to_index = (
- db.query(Document.id, Document.title)
- .outerjoin(
- DocumentCollection,
- (
- DocumentCollection.document_id
- == Document.id
- )
- & (
- DocumentCollection.collection_id
- == library_collection_id
- ),
- )
- .filter(
- Document.research_id == research.id,
- Document.text_content.isnot(None),
- (
- DocumentCollection.indexed.is_(
- False
- )
- | DocumentCollection.id.is_(
- None
- )
- ),
- )
- .all()
- )
-
- if not documents_to_index:
- logger.info(
- f"[DOC_SCHEDULER] No unindexed documents found for research {research.id}"
- )
- else:
- # Index each document
- indexed_count = 0
- for (
- doc_id,
- doc_title,
- ) in documents_to_index:
- try:
- result = rag_service.index_document(
- document_id=doc_id,
- collection_id=library_collection_id,
- force_reindex=False,
- )
- if (
- result["status"]
- == "success"
- ):
- indexed_count += 1
- logger.info(
- f"[DOC_SCHEDULER] Indexed document {doc_id} ({doc_title}) "
- f"with {result.get('chunk_count', 0)} chunks"
- )
- except Exception as doc_error:
- # ``password`` is in scope
- # and was passed into
- # ``LibraryRAGService`` and
- # ``get_default_library_id``
- # above. Drop traceback +
- # redact str(e).
- safe_msg = redact_secrets(
- str(doc_error), password
- )
- logger.warning(
- f"[DOC_SCHEDULER] Failed to index document {doc_id}: {safe_msg}"
- )
-
- logger.info(
- f"[DOC_SCHEDULER] RAG indexing completed for research {research.id}: "
- f"{indexed_count}/{len(documents_to_index)} documents indexed"
- )
- except Exception as e:
- safe_rollback(db, "DOC_SCHEDULER RAG")
- # Same scope as the per-document RAG
- # handler above — ``password`` is in
- # scope via the outer function.
- safe_msg = redact_secrets(str(e), password)
- logger.warning(
- f"[DOC_SCHEDULER] Failed to generate RAG embeddings for research {research.id}: {safe_msg}"
- )
+ # NOTE: RAG indexing of research downloads used to live
+ # here (the old ``if settings.generate_rag:`` block).
+ # It has been retired — the unified
+ # ``_reconcile_unindexed_documents`` reconciler now
+ # indexes ALL unindexed documents (including research
+ # downloads that have no DocumentCollection row yet) on
+ # its own schedule, gated by ``generate_rag OR
+ # sweep_library_collections``. The download_pdfs and
+ # extract_text passes above remain here because they
+ # produce the ``text_content`` the reconciler indexes.
processed_count += 1
logger.debug(
@@ -1236,6 +1233,304 @@ class BackgroundJobScheduler:
f"[DOC_SCHEDULER] Error processing documents for user {username}: {safe_msg}"
)
+ @thread_cleanup
+ def _reconcile_unindexed_documents(self, username: str) -> None:
+ """Unified background reconciler that indexes ANY unindexed document.
+
+ Self-healing follow-up to the immediate auto-index queue (PR #3939),
+ which caps the queue and DROPS documents on saturation, AND replacement
+ for the retired research-scoped ``generate_rag`` indexing block that
+ used to live inline in ``_process_user_documents``. A single scheduled
+ job now covers every unindexed document, so library uploads and research
+ downloads can no longer be permanently missed.
+
+ Two cases are handled per tick, each with its OWN independent
+ ``_LIBRARY_SWEEP_BATCH`` budget so the work done in a single thread tick
+ stays bounded (total <= 2 x ``_LIBRARY_SWEEP_BATCH``). The budgets are
+ decoupled on purpose: case (a) only marks a row indexed on SUCCESS, so a
+ block of permanently-failing case-(a) rows must not be able to consume
+ case (b)'s budget and starve the research-orphan path:
+
+ (a) In-collection unindexed: documents that already have a
+ ``DocumentCollection`` link (e.g. manual uploads — ``upload_to_
+ collection`` always creates the row) with ``indexed`` False and
+ text content. Indexed via the per-collection RAG factory so each
+ collection's own embedding config is honored.
+ (b) Research orphans: ``Document`` rows with ``research_id`` set and
+ text content that have NO ``DocumentCollection`` link in the default
+ library collection yet (research downloads that were never
+ ingested). ``index_document(doc_id, default_library_id, ...)`` calls
+ ``ensure_in_collection`` internally, so it ingests + indexes in one
+ call.
+
+ Behaviour:
+ - Gated by EITHER ``sweep_library_collections`` OR ``generate_rag`` —
+ the ``generate_rag`` arm preserves the legacy "index research
+ downloads" behaviour. Off by default; early-returns when neither set.
+ - Idempotent: uses ``index_document(..., force_reindex=False)`` and only
+ selects rows that are not yet indexed, so already-indexed documents
+ are never touched.
+ - Self-rate-limited: each case is capped at ``_LIBRARY_SWEEP_BATCH``
+ documents per tick (so total <= 2 x ``_LIBRARY_SWEEP_BATCH``); the job
+ is scheduled with ``max_instances=1``.
+ """
+ logger.info(
+ f"[RECONCILER] Starting unindexed-document reconcile for user {username}"
+ )
+
+ # Pre-declared so the except handlers can pass it to redact_secrets
+ # even if the retrieve() call below itself raises.
+ password = None
+ try:
+ session_info = self.user_sessions.get(username)
+ if not session_info:
+ logger.warning(
+ f"[RECONCILER] No session info found for user {username}"
+ )
+ return
+
+ password = self._credential_store.retrieve(username)
+ if not password:
+ logger.warning(
+ f"[RECONCILER] Credentials expired for user {username}"
+ )
+ return
+
+ # Get user's document scheduler settings (cached).
+ settings = self._get_document_scheduler_settings(username)
+
+ # Gate at runtime too, not just at scheduling: the already-live
+ # APScheduler job keeps firing after the document scheduler is
+ # disabled until the next reschedule, and the setting description
+ # promises the sweep only runs while the scheduler is enabled.
+ # OFF by default: runs only when the scheduler is enabled AND
+ # EITHER opt-in is set. The generate_rag arm preserves the legacy
+ # research-download indexing behaviour from _process_user_documents.
+ if not settings.enabled or not (
+ settings.sweep_library_collections or settings.generate_rag
+ ):
+ logger.debug(
+ f"[RECONCILER] Indexing disabled for user {username}"
+ )
+ return
+
+ # Lazy import of the RAG factory. Imported here (not at module
+ # top) to keep the import surface of this scheduler module small
+ # and consistent with the other lazy imports in this file; the
+ # factory itself has no import dependency on the scheduler so a
+ # top-level import would also be safe.
+ from ..research_library.services.rag_service_factory import (
+ get_rag_service,
+ )
+
+ from ..database.session_context import get_user_db_session
+ from ..settings.manager import SettingsManager
+
+ with get_user_db_session(username, password) as db:
+ settings_manager = SettingsManager(db)
+
+ # Arm the PEP-578 audit-hook backstop for this scheduled run,
+ # mirroring _process_user_documents. Indexing itself doesn't
+ # download, but embedding providers may make network calls;
+ # this keeps defense-in-depth parity with an interactive run.
+ # Cleared by @thread_cleanup on exit.
+ self._arm_egress_backstop(settings_manager, username)
+
+ total_indexed = 0
+
+ # ---- Case (a): in-collection unindexed documents ----------
+ # Bounded by _LIBRARY_SWEEP_BATCH so a large backlog self-heals
+ # over successive ticks. Only rows with actual text content can
+ # be indexed. RANDOMIZED selection (not a stable id order): a
+ # row leaves this candidate set only on SUCCESS and we track no
+ # per-row failure state, so a deterministic order would let a
+ # block of permanently-failing low-id rows (e.g. empty-text /
+ # scanned PDFs that always return an indexing error yet pass the
+ # text_content IS NOT NULL filter) win the LIMIT slots every
+ # tick and starve indexable higher-id rows forever. Random
+ # sampling gives every indexable row a chance each tick, so
+ # progress is eventually made despite a permanent-failure set.
+ unindexed = (
+ db.query(
+ DocumentCollection.document_id,
+ DocumentCollection.collection_id,
+ )
+ .join(
+ Document,
+ Document.id == DocumentCollection.document_id,
+ )
+ .filter(
+ DocumentCollection.indexed.is_(False),
+ Document.text_content.isnot(None),
+ )
+ .order_by(func.random())
+ .limit(_LIBRARY_SWEEP_BATCH)
+ .all()
+ )
+
+ # Group document ids by collection so we build exactly one RAG
+ # service per collection (each collection can have its own
+ # embedding config).
+ docs_by_collection: Dict[str, List[str]] = {}
+ for doc_id, coll_id in unindexed:
+ docs_by_collection.setdefault(coll_id, []).append(doc_id)
+
+ if unindexed:
+ logger.info(
+ f"[RECONCILER] Found {len(unindexed)} in-collection "
+ f"unindexed document(s) across "
+ f"{len(docs_by_collection)} collection(s) for {username}"
+ )
+
+ for coll_id, doc_ids in docs_by_collection.items():
+ try:
+ # USE THE FACTORY so per-collection embedding settings
+ # (model/provider/chunking/etc.) stored on the
+ # collection are honored — get_rag_service loads them
+ # from the collection row when collection_id is given.
+ with get_rag_service(
+ username,
+ collection_id=coll_id,
+ db_password=password,
+ ) as rag_service:
+ for doc_id in doc_ids:
+ try:
+ result = rag_service.index_document(
+ document_id=doc_id,
+ collection_id=coll_id,
+ force_reindex=False,
+ )
+ if result.get("status") == "success":
+ total_indexed += 1
+ logger.debug(
+ f"[RECONCILER] Indexed document {doc_id} "
+ f"into collection {coll_id} with "
+ f"{result.get('chunk_count', 0)} chunks"
+ )
+ except Exception as doc_error:
+ # ``password`` is in scope and was passed
+ # into ``get_rag_service``. Drop the
+ # traceback chain + redact str(e) to avoid
+ # leaking the SQLCipher master password.
+ safe_msg = redact_secrets(
+ str(doc_error), password
+ )
+ logger.warning(
+ f"[RECONCILER] Failed to index document "
+ f"{doc_id} into collection {coll_id}: {safe_msg}"
+ )
+ except Exception as coll_error:
+ # Recover the shared thread-local session before moving
+ # on to the next collection so its queries don't run on
+ # a poisoned session.
+ safe_rollback(db, "RECONCILER collection")
+ safe_msg = redact_secrets(str(coll_error), password)
+ logger.warning(
+ f"[RECONCILER] Failed to index collection {coll_id}: {safe_msg}"
+ )
+
+ # ---- Case (b): research orphans -> default library ---------
+ # Research downloads land as Document rows (research_id set)
+ # with NO DocumentCollection link yet. index_document()
+ # ensure_in_collection's the default-library link, so this
+ # ingests + indexes in one call.
+ #
+ # Case (b) gets its OWN independent _LIBRARY_SWEEP_BATCH budget
+ # rather than the leftover of case (a). Case (a) only flips a
+ # row to indexed=True on SUCCESS, so a block of permanently
+ # failing case-(a) rows (empty text, embedding/FAISS errors,
+ # PolicyDeniedError under egress denial) would otherwise fill
+ # the LIMIT every tick, leave the leftover at 0, and starve the
+ # research-orphan path forever — regressing the no-regression
+ # promise for generate_rag-only users. Decoupling the budgets
+ # caps total work at 2 x _LIBRARY_SWEEP_BATCH per tick, which is
+ # acceptable. RANDOMIZED selection (see case (a)) so a block of
+ # permanently-failing low-id orphans can't pin the LIMIT slots
+ # every tick and starve the rest.
+ #
+ # Resolve the default library collection once.
+ default_library_id = get_default_library_id(username, password)
+
+ orphans = (
+ db.query(Document.id)
+ .outerjoin(
+ DocumentCollection,
+ (DocumentCollection.document_id == Document.id)
+ & (
+ DocumentCollection.collection_id
+ == default_library_id
+ ),
+ )
+ .filter(
+ Document.research_id.isnot(None),
+ Document.text_content.isnot(None),
+ DocumentCollection.id.is_(None),
+ )
+ .order_by(func.random())
+ .limit(_LIBRARY_SWEEP_BATCH)
+ .all()
+ )
+
+ if orphans:
+ logger.info(
+ f"[RECONCILER] Found {len(orphans)} research "
+ f"orphan document(s) to ingest into the default "
+ f"library for {username}"
+ )
+ try:
+ with get_rag_service(
+ username,
+ collection_id=default_library_id,
+ db_password=password,
+ ) as rag_service:
+ for (doc_id,) in orphans:
+ try:
+ result = rag_service.index_document(
+ document_id=doc_id,
+ collection_id=default_library_id,
+ force_reindex=False,
+ )
+ if result.get("status") == "success":
+ total_indexed += 1
+ logger.debug(
+ f"[RECONCILER] Ingested + "
+ f"indexed research orphan "
+ f"{doc_id} into the default "
+ f"library with "
+ f"{result.get('chunk_count', 0)} chunks"
+ )
+ except Exception as doc_error:
+ safe_msg = redact_secrets(
+ str(doc_error), password
+ )
+ logger.warning(
+ f"[RECONCILER] Failed to index "
+ f"research orphan {doc_id}: {safe_msg}"
+ )
+ except Exception as orphan_error:
+ safe_rollback(db, "RECONCILER orphans")
+ safe_msg = redact_secrets(str(orphan_error), password)
+ logger.warning(
+ f"[RECONCILER] Failed to index research "
+ f"orphans into the default library: {safe_msg}"
+ )
+
+ logger.info(
+ f"[RECONCILER] Completed reconcile for user {username}: "
+ f"{total_indexed} document(s) indexed "
+ f"(per-case batch cap {_LIBRARY_SWEEP_BATCH})"
+ )
+
+ except Exception as e:
+ # ``password`` is pre-declared as ``None`` at the top of the
+ # function, so it is always bound here even if the retrieve()
+ # call itself raised. ``redact_secrets`` silently skips a
+ # ``None`` secret. Drop the traceback chain.
+ safe_msg = redact_secrets(str(e), password)
+ logger.warning(
+ f"[RECONCILER] Error reconciling unindexed documents for user {username}: {safe_msg}"
+ )
+
def get_document_scheduler_status(self, username: str) -> Dict[str, Any]:
"""Get document scheduler status for a specific user."""
try:
@@ -1259,7 +1554,10 @@ class BackgroundJobScheduler:
"processing_options": {
"download_pdfs": settings.download_pdfs,
"extract_text": settings.extract_text,
+ # generate_rag and sweep_library_collections both gate the
+ # unified reconciler (_reconcile_unindexed_documents).
"generate_rag": settings.generate_rag,
+ "sweep_library_collections": settings.sweep_library_collections,
},
"last_run": settings.last_run,
"has_scheduled_job": has_job,
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index 7dd187df8d..8f38478382 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -77,6 +77,7 @@ from ...settings.manager import get_typed_setting_value, parse_boolean
from ..services.settings_service import (
create_or_update_setting,
invalidate_settings_caches,
+ reschedule_document_jobs_if_needed,
set_setting,
)
from ..utils.route_decorators import with_user_session
@@ -730,6 +731,9 @@ def save_all_settings(
)
invalidate_settings_caches(session["username"])
+ reschedule_document_jobs_if_needed(
+ session["username"], updated_settings + created_settings
+ )
return jsonify(response_data)
except Exception:
@@ -1147,6 +1151,9 @@ def api_update_setting(key, db_session: Optional[Session] = None):
)
invalidate_settings_caches(session["username"])
+ # A document_scheduler.* toggle (e.g. sweep_library_collections
+ # or generate_rag) must take effect without a re-login.
+ reschedule_document_jobs_if_needed(session["username"], [key])
return jsonify(response_data)
return jsonify({"error": f"Failed to update setting {key}"}), 500
@@ -1194,6 +1201,7 @@ def api_update_setting(key, db_session: Optional[Session] = None):
if db_setting:
invalidate_settings_caches(session["username"])
+ reschedule_document_jobs_if_needed(session["username"], [key])
return (
jsonify(
{
diff --git a/src/local_deep_research/web/services/settings_service.py b/src/local_deep_research/web/services/settings_service.py
index 723eae3508..23ae4684d2 100644
--- a/src/local_deep_research/web/services/settings_service.py
+++ b/src/local_deep_research/web/services/settings_service.py
@@ -89,6 +89,44 @@ def invalidate_settings_caches(username=None):
logger.debug("Could not invalidate scheduler cache", exc_info=True)
+def reschedule_document_jobs_if_needed(username, changed_keys):
+ """Reschedule a user's document-scheduler jobs after a settings change.
+
+ Cache invalidation alone (``invalidate_settings_caches``) only clears the
+ scheduler's cached settings — it does not (re)create or tear down the
+ per-user interval jobs. So toggling ``document_scheduler.*`` settings (e.g.
+ ``sweep_library_collections`` or the legacy ``generate_rag``) would not take
+ effect until the user logged out and back in. Call this AFTER
+ ``invalidate_settings_caches`` so the scheduler re-reads fresh settings and
+ the change applies on the next tick.
+
+ Only reschedules when a ``document_scheduler.*`` key actually changed, so an
+ unrelated settings save never churns (and resets the timer of) the document
+ jobs. Best-effort and silent when the scheduler isn't running (e.g. tests,
+ CLI), mirroring ``invalidate_settings_caches``.
+
+ Args:
+ username: The user whose jobs should be re-evaluated.
+ changed_keys: Iterable of setting keys written by the request.
+ """
+ if not username or not changed_keys:
+ return
+ if not any(
+ str(key).startswith("document_scheduler.") for key in changed_keys
+ ):
+ return
+ try:
+ from ...scheduler.background import get_background_job_scheduler
+
+ scheduler = get_background_job_scheduler()
+ scheduler.reschedule_document_jobs(username)
+ except Exception:
+ logger.debug(
+ "Could not reschedule document jobs after settings change",
+ exc_info=True,
+ )
+
+
def validate_setting(
setting: Setting, value: Any
) -> tuple[bool, Optional[str]]:
diff --git a/tests/news/subscription_manager/test_scheduler_coverage.py b/tests/news/subscription_manager/test_scheduler_coverage.py
index 110a031806..0490a98d2d 100644
--- a/tests/news/subscription_manager/test_scheduler_coverage.py
+++ b/tests/news/subscription_manager/test_scheduler_coverage.py
@@ -52,10 +52,12 @@ GET_SETTING_SNAP = (
)
DATE_STRING = "local_deep_research.news.core.utils.get_local_date_string"
-# Top-level imports in scheduler.py
+# Top-level imports in scheduler.py.
+# NOTE: RAG indexing moved out of _process_user_documents into the unified
+# _reconcile_unindexed_documents reconciler (covered in tests/news/
+# test_library_sweep.py), so this module no longer patches LibraryRAGService /
+# get_default_library_id.
SCHED_MOD = "local_deep_research.scheduler.background"
-LIB_RAG = f"{SCHED_MOD}.LibraryRAGService"
-DEFAULT_LIB = f"{SCHED_MOD}.get_default_library_id"
# ---------------------------------------------------------------------------
@@ -441,7 +443,38 @@ class TestScheduleDocumentProcessingEdgeCases:
next_run_time=datetime.now(UTC)
)
sched._schedule_document_processing("u")
- mock_bg.remove_job.assert_called_with("u_document_processing")
+ # _schedule_document_processing also tears down the opt-in library
+ # sweep job, so the document-processing removal may not be the last
+ # remove_job call — assert it happened rather than that it was last.
+ mock_bg.remove_job.assert_any_call("u_document_processing")
+
+ def test_wires_up_reconciler(self, sched, mock_bg):
+ """_schedule_document_processing must invoke _schedule_reconciler — the
+ ONLY production path that gives the library-sweep job a lifecycle.
+ Guards the integration seam: deleting the
+ self._schedule_reconciler(...) call would silently disable the whole
+ feature while every isolated reconciler test still passes.
+ """
+ _setup_user(sched, "u")
+ from local_deep_research.scheduler.background import (
+ DocumentSchedulerSettings,
+ )
+
+ settings = DocumentSchedulerSettings(
+ enabled=True, sweep_library_collections=True
+ )
+ with (
+ patch.object(
+ sched,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ patch.object(sched, "_schedule_reconciler") as mock_reconciler,
+ ):
+ sched._schedule_document_processing("u")
+
+ mock_reconciler.assert_called_once()
+ assert mock_reconciler.call_args[0][0] == "u"
def test_existing_job_not_found_ok(self, sched, mock_bg):
from apscheduler.jobstores.base import JobLookupError
@@ -677,33 +710,14 @@ class TestProcessUserDocumentsFull:
):
sched._process_user_documents("u")
- def test_generate_rag_with_documents(self, sched):
+ def test_generate_rag_alone_is_noop_in_process_user_documents(self, sched):
+ """RAG indexing of research downloads was RETIRED from
+ _process_user_documents into the reconciler. With generate_rag=True but
+ download/extract OFF, this pass short-circuits and never opens a DB
+ session — there is no inline RAG block left to run.
+ """
_setup_user(sched, "u")
- research = self._make_research()
-
mock_db = _ctx(MagicMock())
- call_count = [0]
- chain = mock_db.query.return_value
- chain.filter.return_value = chain
- chain.order_by.return_value = chain
- chain.limit.return_value = chain
- chain.outerjoin.return_value = chain
-
- def all_fn():
- call_count[0] += 1
- return [research] if call_count[0] == 1 else [(100, "Doc")]
-
- chain.all.side_effect = all_fn
-
- mock_sm = MagicMock()
- mock_sm.get_setting.side_effect = lambda k, default: default
-
- mock_rag = MagicMock()
- _ctx(mock_rag)
- mock_rag.index_document.return_value = {
- "status": "success",
- "chunk_count": 5,
- }
with (
patch.object(
@@ -711,108 +725,13 @@ class TestProcessUserDocumentsFull:
"_get_document_scheduler_settings",
return_value=self._dss(generate_rag=True),
),
- patch(DB_SESSION, return_value=mock_db),
- patch(SETTINGS_MGR, return_value=mock_sm),
- patch(LIB_RAG, return_value=mock_rag),
- patch(DEFAULT_LIB, return_value=1),
- ):
- sched._process_user_documents("u")
- mock_rag.index_document.assert_called_once()
-
- def test_generate_rag_no_documents(self, sched):
- _setup_user(sched, "u")
- research = self._make_research()
-
- mock_db = _ctx(MagicMock())
- call_count = [0]
- chain = mock_db.query.return_value
- chain.filter.return_value = chain
- chain.order_by.return_value = chain
- chain.limit.return_value = chain
- chain.outerjoin.return_value = chain
-
- def all_fn():
- call_count[0] += 1
- return [research] if call_count[0] == 1 else []
-
- chain.all.side_effect = all_fn
-
- mock_sm = MagicMock()
- mock_sm.get_setting.side_effect = lambda k, default: default
- mock_rag = MagicMock()
- _ctx(mock_rag)
-
- with (
- patch.object(
- sched,
- "_get_document_scheduler_settings",
- return_value=self._dss(generate_rag=True),
- ),
- patch(DB_SESSION, return_value=mock_db),
- patch(SETTINGS_MGR, return_value=mock_sm),
- patch(LIB_RAG, return_value=mock_rag),
- patch(DEFAULT_LIB, return_value=1),
- ):
- sched._process_user_documents("u")
- mock_rag.index_document.assert_not_called()
-
- def test_generate_rag_index_exception(self, sched):
- _setup_user(sched, "u")
- research = self._make_research()
-
- mock_db = _ctx(MagicMock())
- call_count = [0]
- chain = mock_db.query.return_value
- chain.filter.return_value = chain
- chain.order_by.return_value = chain
- chain.limit.return_value = chain
- chain.outerjoin.return_value = chain
-
- def all_fn():
- call_count[0] += 1
- return [research] if call_count[0] == 1 else [(100, "Doc")]
-
- chain.all.side_effect = all_fn
-
- mock_sm = MagicMock()
- mock_sm.get_setting.side_effect = lambda k, default: default
- mock_rag = MagicMock()
- _ctx(mock_rag)
- mock_rag.index_document.side_effect = RuntimeError("fail")
-
- with (
- patch.object(
- sched,
- "_get_document_scheduler_settings",
- return_value=self._dss(generate_rag=True),
- ),
- patch(DB_SESSION, return_value=mock_db),
- patch(SETTINGS_MGR, return_value=mock_sm),
- patch(LIB_RAG, return_value=mock_rag),
- patch(DEFAULT_LIB, return_value=1),
+ patch(DB_SESSION, return_value=mock_db) as mock_session,
+ patch(SETTINGS_MGR, return_value=MagicMock()),
):
sched._process_user_documents("u")
- def test_generate_rag_outer_exception(self, sched):
- _setup_user(sched, "u")
- research = self._make_research()
- mock_db = _ctx(MagicMock())
- self._setup_db_chain(mock_db, [research])
-
- mock_sm = MagicMock()
- mock_sm.get_setting.side_effect = lambda k, default: default
-
- with (
- patch.object(
- sched,
- "_get_document_scheduler_settings",
- return_value=self._dss(generate_rag=True),
- ),
- patch(DB_SESSION, return_value=mock_db),
- patch(SETTINGS_MGR, return_value=mock_sm),
- patch(LIB_RAG, side_effect=RuntimeError("rag fail")),
- ):
- sched._process_user_documents("u")
+ # generate_rag alone no longer enables the download/extract pass.
+ mock_session.assert_not_called()
def test_completed_at_string_parsing(self, sched):
_setup_user(sched, "u")
diff --git a/tests/news/test_document_scheduler_settings.py b/tests/news/test_document_scheduler_settings.py
index 8e37060595..0a02f49229 100644
--- a/tests/news/test_document_scheduler_settings.py
+++ b/tests/news/test_document_scheduler_settings.py
@@ -25,6 +25,7 @@ class TestDocumentSchedulerSettings:
assert settings.download_pdfs is False
assert settings.extract_text is True
assert settings.generate_rag is False
+ assert settings.sweep_library_collections is False
assert settings.last_run == ""
def test_custom_values(self):
@@ -35,6 +36,7 @@ class TestDocumentSchedulerSettings:
download_pdfs=True,
extract_text=False,
generate_rag=True,
+ sweep_library_collections=True,
last_run="2025-01-01T00:00:00+00:00",
)
@@ -43,6 +45,7 @@ class TestDocumentSchedulerSettings:
assert settings.download_pdfs is True
assert settings.extract_text is False
assert settings.generate_rag is True
+ assert settings.sweep_library_collections is True
assert settings.last_run == "2025-01-01T00:00:00+00:00"
def test_partial_values(self):
@@ -75,4 +78,5 @@ class TestDocumentSchedulerSettings:
assert defaults.download_pdfs is False
assert defaults.extract_text is True
assert defaults.generate_rag is False
+ assert defaults.sweep_library_collections is False
assert defaults.last_run == ""
diff --git a/tests/news/test_library_sweep.py b/tests/news/test_library_sweep.py
new file mode 100644
index 0000000000..fda8d64f3d
--- /dev/null
+++ b/tests/news/test_library_sweep.py
@@ -0,0 +1,1230 @@
+"""Tests for the unified unindexed-document reconciler.
+
+These drive ``BackgroundJobScheduler._reconcile_unindexed_documents`` (the
+self-healing reconciler that indexes EVERY unindexed document — both in-
+collection library uploads missed by PR #3939's drop-on-saturation auto-index
+queue AND research downloads that were never ingested) and
+``_schedule_reconciler`` (the job lifecycle) with focused mocks, mirroring the
+mocking style of ``test_download_service_3827_fix.py``.
+
+The reconciler handles two cases per tick under one batch cap:
+ (a) in-collection unindexed docs (DocumentCollection.indexed == False)
+ (b) research orphans (Document.research_id set, no default-library link)
+and is gated by ``sweep_library_collections OR generate_rag`` (the generate_rag
+arm preserves the legacy research-download indexing behaviour).
+"""
+
+from contextlib import contextmanager
+from datetime import datetime, UTC
+from unittest.mock import MagicMock, patch
+
+from local_deep_research.scheduler.background import (
+ _LIBRARY_SWEEP_BATCH,
+ BackgroundJobScheduler,
+ DocumentSchedulerSettings,
+)
+
+MODULE = "local_deep_research.scheduler.background"
+# get_default_library_id is imported at module scope in background.py, so patch
+# the name bound there (not its definition module).
+DEFAULT_LIB = f"{MODULE}.get_default_library_id"
+# get_rag_service is imported lazily inside the reconciler, so patch it at its
+# definition module.
+FACTORY = (
+ "local_deep_research.research_library.services.rag_service_factory"
+ ".get_rag_service"
+)
+
+
+def _fresh_scheduler():
+ """Return a fresh scheduler singleton with a registered test user."""
+ BackgroundJobScheduler._instance = None
+ with patch(f"{MODULE}.BackgroundScheduler"):
+ scheduler = BackgroundJobScheduler()
+ scheduler.user_sessions["testuser"] = {
+ "scheduled_jobs": set(),
+ "last_activity": datetime.now(UTC),
+ }
+ scheduler._credential_store.store("testuser", "testpass")
+ return scheduler
+
+
+def _db_returning(case_a_rows, case_b_rows=None):
+ """Build a MagicMock db whose query chain returns ``case_a_rows`` on the
+ first ``.all()`` (case-a in-collection query) and ``case_b_rows`` on the
+ second (case-b research-orphan query).
+
+ case_a_rows: list of (document_id, collection_id) tuples.
+ case_b_rows: list of (document_id,) tuples; defaults to empty.
+ """
+ if case_b_rows is None:
+ case_b_rows = []
+ db = MagicMock()
+ query = MagicMock()
+ query.join.return_value = query
+ query.outerjoin.return_value = query
+ query.filter.return_value = query
+ query.order_by.return_value = query
+ query.limit.return_value = query
+ # First .all() => case (a) rows, second .all() => case (b) rows.
+ query.all.side_effect = [case_a_rows, case_b_rows]
+ db.query.return_value = query
+ return db, query
+
+
+def _rag_service():
+ """Return a MagicMock RAG service usable as a context manager that reports
+ successful indexing.
+ """
+ rag = MagicMock()
+ rag.__enter__ = MagicMock(return_value=rag)
+ rag.__exit__ = MagicMock(return_value=False)
+ rag.index_document.return_value = {"status": "success", "chunk_count": 3}
+ return rag
+
+
+@contextmanager
+def _patched_session(db):
+ """Patch the lazily-imported get_user_db_session to yield ``db`` and stub
+ SettingsManager + the egress backstop arming + the default-library lookup.
+ """
+
+ @contextmanager
+ def fake_get_user_db_session(*a, **kw):
+ yield db
+
+ with (
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ side_effect=fake_get_user_db_session,
+ ),
+ patch(
+ "local_deep_research.settings.manager.SettingsManager",
+ return_value=MagicMock(),
+ ),
+ patch.object(
+ BackgroundJobScheduler,
+ "_arm_egress_backstop",
+ lambda *a, **kw: None,
+ ),
+ patch(DEFAULT_LIB, return_value="default-lib"),
+ ):
+ yield
+
+
+def test_reconciler_indexes_in_collection_unindexed_when_enabled():
+ """Case (a): with sweep ON, every in-collection unindexed doc is indexed via
+ the per-collection RAG service with force_reindex=False; one service per
+ distinct collection.
+ """
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings(sweep_library_collections=True)
+
+ db, _ = _db_returning(
+ [("doc-1", "coll-A"), ("doc-2", "coll-A"), ("doc-3", "coll-B")],
+ case_b_rows=[],
+ )
+
+ rag_service = _rag_service()
+
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ _patched_session(db),
+ patch(FACTORY, return_value=rag_service) as mock_factory,
+ ):
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ # Each in-collection unindexed doc indexed exactly once, never reindexed.
+ assert rag_service.index_document.call_count == 3
+ for call in rag_service.index_document.call_args_list:
+ assert call.kwargs["force_reindex"] is False
+
+ # One RAG service built per distinct collection (A, B). No orphans here so
+ # the default-library service is not built.
+ built_collections = {
+ c.kwargs.get("collection_id") for c in mock_factory.call_args_list
+ }
+ assert built_collections == {"coll-A", "coll-B"}
+
+
+def test_reconciler_ingests_and_indexes_research_orphan():
+ """Case (b): a research orphan (research_id set, no default-library link) is
+ ingested into the default library AND indexed via index_document into the
+ default-library collection. index_document's ensure_in_collection does the
+ ingest, so a single call ingests + indexes.
+ """
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings(sweep_library_collections=True)
+
+ # No in-collection work (case a empty), one research orphan (case b).
+ db, _ = _db_returning([], case_b_rows=[("orphan-doc",)])
+
+ rag_service = _rag_service()
+
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ _patched_session(db),
+ patch(FACTORY, return_value=rag_service) as mock_factory,
+ ):
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ # The orphan was indexed into the DEFAULT library collection.
+ rag_service.index_document.assert_called_once()
+ call = rag_service.index_document.call_args
+ assert call.kwargs["document_id"] == "orphan-doc"
+ assert call.kwargs["collection_id"] == "default-lib"
+ assert call.kwargs["force_reindex"] is False
+
+ # The RAG service for the orphan path was built for the default library.
+ assert any(
+ c.kwargs.get("collection_id") == "default-lib"
+ for c in mock_factory.call_args_list
+ )
+
+
+def test_reconciler_runs_for_generate_rag_only_no_regression():
+ """No-regression path: with sweep_library_collections OFF but the legacy
+ generate_rag ON, the reconciler still runs and indexes research orphans —
+ preserving the behaviour of the retired _process_user_documents RAG block.
+ """
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings(
+ sweep_library_collections=False, generate_rag=True
+ )
+ assert settings.sweep_library_collections is False
+
+ db, _ = _db_returning([], case_b_rows=[("orphan-doc",)])
+ rag_service = _rag_service()
+
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ _patched_session(db),
+ patch(FACTORY, return_value=rag_service),
+ ):
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ # generate_rag alone is enough to drive the reconciler.
+ rag_service.index_document.assert_called_once()
+ assert (
+ rag_service.index_document.call_args.kwargs["collection_id"]
+ == "default-lib"
+ )
+
+
+def test_reconciler_is_noop_when_both_disabled():
+ """With BOTH gating settings OFF (default), the reconciler returns before
+ opening a DB session or building any RAG service.
+ """
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings() # both False
+ assert settings.sweep_library_collections is False
+ assert settings.generate_rag is False
+
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ ) as mock_session,
+ patch(FACTORY) as mock_factory,
+ ):
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ mock_session.assert_not_called()
+ mock_factory.assert_not_called()
+
+
+def test_reconciler_is_noop_when_scheduler_disabled():
+ """When the document scheduler is disabled (enabled=False) the reconciler
+ must no-op even if sweep_library_collections is on — the already-live job
+ can keep firing after a runtime disable until the next reschedule, and the
+ setting promises it only runs while the scheduler is enabled.
+ """
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings(
+ enabled=False, sweep_library_collections=True
+ )
+
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ ) as mock_session,
+ patch(FACTORY) as mock_factory,
+ ):
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ mock_session.assert_not_called()
+ mock_factory.assert_not_called()
+
+
+def test_reconciler_filters_to_unindexed_only_no_work():
+ """The case-(a) query filters on DocumentCollection.indexed == False so an
+ already-indexed document is never selected. With both queries empty, no RAG
+ service is built (idempotency: already-indexed docs are never touched).
+ """
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings(sweep_library_collections=True)
+
+ db, query = _db_returning([], case_b_rows=[]) # nothing to do
+
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ _patched_session(db),
+ patch(FACTORY) as mock_factory,
+ ):
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ # Queries were issued (filters applied) but selected nothing.
+ assert query.filter.called
+ mock_factory.assert_not_called()
+
+
+def test_reconciler_caps_each_case_at_its_own_batch_budget():
+ """Each case has its OWN _LIBRARY_SWEEP_BATCH budget (independent, NOT a
+ shared/leftover budget). Even when case (a) returns a full batch, the
+ research-orphan path still runs with its own LIMIT(_LIBRARY_SWEEP_BATCH), so
+ total work is bounded at 2 x _LIBRARY_SWEEP_BATCH per tick.
+ """
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings(sweep_library_collections=True)
+
+ # Case (a) returns a full batch; case (b) also has rows to process.
+ rows = [(f"doc-{i}", "coll-A") for i in range(_LIBRARY_SWEEP_BATCH)]
+ db, query = _db_returning(rows, case_b_rows=[("orphan-doc",)])
+
+ rag_service = _rag_service()
+ rag_service.index_document.return_value = {
+ "status": "success",
+ "chunk_count": 1,
+ }
+
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ _patched_session(db),
+ patch(FACTORY, return_value=rag_service),
+ ):
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ # BOTH queries are capped at the module batch constant (independent budgets,
+ # not a single shared one). With case (a) at full batch the orphan query
+ # must STILL use the full _LIBRARY_SWEEP_BATCH limit (no `remaining`
+ # subtraction), so .limit is called with the constant for both cases.
+ assert query.limit.call_args_list == [
+ ((_LIBRARY_SWEEP_BATCH,), {}),
+ ((_LIBRARY_SWEEP_BATCH,), {}),
+ ]
+ # Case (a) docs (BATCH) plus the one orphan were all indexed: the orphan was
+ # NOT starved by a full case (a).
+ assert rag_service.index_document.call_count == _LIBRARY_SWEEP_BATCH + 1
+ indexed_collections = {
+ c.kwargs["collection_id"]
+ for c in rag_service.index_document.call_args_list
+ }
+ assert indexed_collections == {"coll-A", "default-lib"}
+
+
+def test_reconciler_per_doc_error_does_not_crash_tick_or_leak_password(
+ loguru_caplog_full,
+):
+ """A per-doc indexing error is logged and the loop continues with the next
+ doc; the password is never present in the captured log output.
+
+ Uses ``loguru_caplog_full`` (which re-enables the package's loguru logging,
+ disabled by default in tests) so the leak assertion is NOT vacuous — the
+ error line really is captured and checked for the secret.
+ """
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings(sweep_library_collections=True)
+
+ db, _ = _db_returning(
+ [("doc-1", "coll-A"), ("doc-2", "coll-A")], case_b_rows=[]
+ )
+
+ rag_service = _rag_service()
+ # First doc raises an error containing the password; second succeeds.
+ rag_service.index_document.side_effect = [
+ RuntimeError("boom with secret testpass inside"),
+ {"status": "success", "chunk_count": 2},
+ ]
+
+ with loguru_caplog_full.at_level("DEBUG"):
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ _patched_session(db),
+ patch(FACTORY, return_value=rag_service),
+ ):
+ # Must not raise even though the first doc errored.
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ # Both docs were attempted (the error didn't abort the loop).
+ assert rag_service.index_document.call_count == 2
+ text = loguru_caplog_full.text
+ # The per-doc error handler ran (path exercised) ...
+ assert "[RECONCILER] Failed to index document" in text
+ # ... and the plaintext password never appears in the log output.
+ assert "testpass" not in text, "Password leaked into reconciler log output"
+
+
+def test_schedule_reconciler_adds_job_when_sweep_enabled():
+ """_schedule_reconciler registers the interval job (with max_instances=1)
+ and tracks it in the session's scheduled-jobs set when sweep is ON.
+ """
+ scheduler = _fresh_scheduler()
+ session_info = scheduler.user_sessions["testuser"]
+ settings = DocumentSchedulerSettings(
+ sweep_library_collections=True, interval_seconds=1800
+ )
+
+ # remove_job has no prior job -> raise JobLookupError so the add path runs.
+ from apscheduler.jobstores.base import JobLookupError
+
+ scheduler.scheduler.remove_job.side_effect = JobLookupError("library_sweep")
+
+ scheduler._schedule_reconciler("testuser", settings, session_info)
+
+ assert scheduler.scheduler.add_job.called
+ kwargs = scheduler.scheduler.add_job.call_args.kwargs
+ assert kwargs["id"] == "testuser_library_sweep"
+ assert kwargs["trigger"] == "interval"
+ assert kwargs["seconds"] == 1800
+ assert kwargs["max_instances"] == 1
+ assert "testuser_library_sweep" in session_info["scheduled_jobs"]
+
+
+def test_schedule_reconciler_adds_job_when_generate_rag_enabled():
+ """The legacy generate_rag setting alone also schedules the reconciler
+ (no-regression: research downloads keep getting indexed).
+ """
+ scheduler = _fresh_scheduler()
+ session_info = scheduler.user_sessions["testuser"]
+ settings = DocumentSchedulerSettings(
+ sweep_library_collections=False,
+ generate_rag=True,
+ interval_seconds=1800,
+ )
+
+ from apscheduler.jobstores.base import JobLookupError
+
+ scheduler.scheduler.remove_job.side_effect = JobLookupError("library_sweep")
+
+ scheduler._schedule_reconciler("testuser", settings, session_info)
+
+ assert scheduler.scheduler.add_job.called
+ assert (
+ scheduler.scheduler.add_job.call_args.kwargs["id"]
+ == "testuser_library_sweep"
+ )
+ assert "testuser_library_sweep" in session_info["scheduled_jobs"]
+
+
+def test_schedule_reconciler_removes_job_when_both_disabled():
+ """When BOTH gating settings are OFF, no job is added and any existing one is
+ removed from both the scheduler and the session's tracked-jobs set.
+ """
+ scheduler = _fresh_scheduler()
+ session_info = scheduler.user_sessions["testuser"]
+ session_info["scheduled_jobs"].add("testuser_library_sweep")
+ settings = DocumentSchedulerSettings(
+ sweep_library_collections=False, generate_rag=False
+ )
+
+ scheduler._schedule_reconciler("testuser", settings, session_info)
+
+ scheduler.scheduler.remove_job.assert_called_once_with(
+ "testuser_library_sweep"
+ )
+ scheduler.scheduler.add_job.assert_not_called()
+ assert "testuser_library_sweep" not in session_info["scheduled_jobs"]
+
+
+# ---------------------------------------------------------------------------
+# reschedule_document_jobs: the settings-save seam that makes a
+# document_scheduler.* toggle take effect on the next tick instead of only
+# after the user logs out and back in.
+# ---------------------------------------------------------------------------
+
+
+def test_reschedule_document_jobs_creates_reconciler_on_enable():
+ """Toggling sweep ON re-creates the {username}_library_sweep job for an
+ active user (no re-login needed)."""
+ scheduler = _fresh_scheduler()
+ scheduler.is_running = True
+ settings = DocumentSchedulerSettings(
+ enabled=True, sweep_library_collections=True, interval_seconds=1800
+ )
+
+ with patch.object(
+ scheduler, "_get_document_scheduler_settings", return_value=settings
+ ):
+ result = scheduler.reschedule_document_jobs("testuser")
+
+ assert result is True
+ scheduled_ids = {
+ call.kwargs.get("id")
+ for call in scheduler.scheduler.add_job.call_args_list
+ }
+ assert "testuser_library_sweep" in scheduled_ids
+
+
+def test_reschedule_document_jobs_removes_reconciler_on_disable():
+ """Toggling both gating settings OFF tears the reconciler job down on the
+ next save (not only on the next login)."""
+ scheduler = _fresh_scheduler()
+ scheduler.is_running = True
+ scheduler.user_sessions["testuser"]["scheduled_jobs"].add(
+ "testuser_library_sweep"
+ )
+ settings = DocumentSchedulerSettings(
+ enabled=True,
+ sweep_library_collections=False,
+ generate_rag=False,
+ interval_seconds=1800,
+ )
+
+ with patch.object(
+ scheduler, "_get_document_scheduler_settings", return_value=settings
+ ):
+ result = scheduler.reschedule_document_jobs("testuser")
+
+ assert result is True
+ scheduler.scheduler.remove_job.assert_any_call("testuser_library_sweep")
+ add_ids = {
+ call.kwargs.get("id")
+ for call in scheduler.scheduler.add_job.call_args_list
+ }
+ assert "testuser_library_sweep" not in add_ids
+ assert (
+ "testuser_library_sweep"
+ not in scheduler.user_sessions["testuser"]["scheduled_jobs"]
+ )
+
+
+def test_reschedule_document_jobs_noop_for_inactive_user():
+ """A user the scheduler isn't tracking is skipped (their jobs are rebuilt
+ from current settings on their next login) — returns False, no scheduling.
+ """
+ scheduler = _fresh_scheduler()
+ scheduler.is_running = True
+
+ result = scheduler.reschedule_document_jobs("ghost")
+
+ assert result is False
+ scheduler.scheduler.add_job.assert_not_called()
+
+
+def test_reschedule_document_jobs_noop_when_scheduler_not_running():
+ """No rescheduling is attempted when the scheduler isn't running."""
+ scheduler = _fresh_scheduler()
+ scheduler.is_running = False
+
+ result = scheduler.reschedule_document_jobs("testuser")
+
+ assert result is False
+ scheduler.scheduler.add_job.assert_not_called()
+
+
+def test_reschedule_helper_only_fires_for_document_scheduler_keys():
+ """The settings-save helper reschedules ONLY when a document_scheduler.* key
+ changed, so an unrelated settings save never churns the document jobs."""
+ from local_deep_research.web.services.settings_service import (
+ reschedule_document_jobs_if_needed,
+ )
+
+ with patch(f"{MODULE}.get_background_job_scheduler") as get_sched:
+ sched = get_sched.return_value
+
+ # Unrelated key -> the scheduler is never even looked up.
+ reschedule_document_jobs_if_needed("u", ["llm.temperature"])
+ get_sched.assert_not_called()
+
+ # A document_scheduler.* key -> reschedule that user's document jobs.
+ reschedule_document_jobs_if_needed(
+ "u", ["document_scheduler.sweep_library_collections"]
+ )
+ sched.reschedule_document_jobs.assert_called_once_with("u")
+
+ # Missing / empty inputs are no-ops (return before touching the scheduler).
+ reschedule_document_jobs_if_needed(None, ["document_scheduler.enabled"])
+ reschedule_document_jobs_if_needed("u", [])
+
+
+# ---------------------------------------------------------------------------
+# Finding 1: case (b) must not be starved when case (a) is full of failures
+# ---------------------------------------------------------------------------
+
+
+def test_case_b_not_starved_when_case_a_full_batch_all_fail():
+ """Regression guard for the case-(b) starvation bug.
+
+ Case (a) returns a FULL batch of in-collection docs that ALL fail to index
+ (index_document raises every time, so none flip to indexed=True), AND there
+ is a research orphan pending. With the old shared/leftover budget
+ (``remaining = _LIBRARY_SWEEP_BATCH - len(unindexed)`` == 0) the orphan path
+ would never run. With independent per-case budgets it MUST still run and
+ index the orphan.
+
+ Mutation check: revert the fix (gate case (b) on
+ ``remaining = _LIBRARY_SWEEP_BATCH - len(unindexed)`` and ``if remaining >
+ 0``) and this test fails because the orphan is never indexed.
+ """
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings(sweep_library_collections=True)
+
+ # Case (a): a full batch, all in coll-A. Case (b): one orphan.
+ case_a = [(f"doc-{i}", "coll-A") for i in range(_LIBRARY_SWEEP_BATCH)]
+ db, _ = _db_returning(case_a, case_b_rows=[("orphan-doc",)])
+
+ # One service object, used for BOTH the per-collection path (coll-A) and the
+ # default-library path. Case-(a) docs always raise; the orphan succeeds.
+ rag_service = _rag_service()
+
+ def index_side_effect(*, document_id, collection_id, force_reindex):
+ if collection_id == "coll-A":
+ raise RuntimeError(f"index failed for {document_id}")
+ return {"status": "success", "chunk_count": 1}
+
+ rag_service.index_document.side_effect = index_side_effect
+
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ _patched_session(db),
+ patch(FACTORY, return_value=rag_service),
+ ):
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ # The orphan was indexed into the default library DESPITE case (a) filling a
+ # whole batch with failures: case (b) is not starved.
+ orphan_calls = [
+ c
+ for c in rag_service.index_document.call_args_list
+ if c.kwargs["collection_id"] == "default-lib"
+ ]
+ assert len(orphan_calls) == 1
+ assert orphan_calls[0].kwargs["document_id"] == "orphan-doc"
+
+
+# ---------------------------------------------------------------------------
+# Finding 2: real in-memory DB so the actual query predicates are exercised
+# ---------------------------------------------------------------------------
+
+
+def _seed_document(
+ session,
+ source_type_id,
+ *,
+ doc_id,
+ text_content="some text",
+ research_id=None,
+):
+ """Insert one Document row with all NOT-NULL columns satisfied."""
+ from local_deep_research.database.models.library import (
+ Document,
+ DocumentStatus,
+ )
+
+ doc = Document(
+ id=doc_id,
+ source_type_id=source_type_id,
+ research_id=research_id,
+ document_hash=(doc_id + "x" * 64)[:64],
+ file_size=10,
+ file_type="txt",
+ text_content=text_content,
+ status=DocumentStatus.COMPLETED,
+ )
+ session.add(doc)
+ return doc
+
+
+def _real_db_session():
+ """Build an in-memory SQLite session with the library schema created and a
+ SourceType + two collections (a default library + a normal collection)
+ seeded. Returns (session, source_type_id, default_lib_id, coll_id).
+ """
+ import uuid
+
+ 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,
+ SourceType,
+ )
+
+ engine = create_engine("sqlite:///:memory:")
+ Base.metadata.create_all(engine)
+ session = sessionmaker(bind=engine)()
+
+ st = SourceType(
+ id=str(uuid.uuid4()),
+ name="research_download",
+ display_name="Research Download",
+ )
+ default_lib = Collection(
+ id="default-lib",
+ name="Library",
+ collection_type="default_library",
+ is_default=True,
+ )
+ other = Collection(
+ id="coll-A",
+ name="Coll A",
+ collection_type="user_collection",
+ )
+ session.add_all([st, default_lib, other])
+ session.commit()
+ return session, st.id, "default-lib", "coll-A"
+
+
+def test_case_a_predicate_selects_only_unindexed_with_text_real_db():
+ """Finding 2 (a): with a REAL DB, the case-(a) query selects an unindexed
+ in-collection doc with text, and excludes an already-indexed doc and a
+ null-text doc. A wrong predicate (e.g. indexed.is_(True)) fails here.
+ """
+ from local_deep_research.database.models.library import DocumentCollection
+
+ session, st_id, default_lib_id, coll_id = _real_db_session()
+
+ # Doc 1: unindexed, has text, in coll-A -> SHOULD be selected.
+ _seed_document(session, st_id, doc_id="doc-unindexed", text_content="hi")
+ # Doc 2: already indexed in coll-A -> should NOT be selected.
+ _seed_document(session, st_id, doc_id="doc-indexed", text_content="hi")
+ # Doc 3: unindexed but NULL text -> should NOT be selected.
+ _seed_document(session, st_id, doc_id="doc-notext", text_content=None)
+ session.add_all(
+ [
+ DocumentCollection(
+ document_id="doc-unindexed",
+ collection_id=coll_id,
+ indexed=False,
+ ),
+ DocumentCollection(
+ document_id="doc-indexed",
+ collection_id=coll_id,
+ indexed=True,
+ ),
+ DocumentCollection(
+ document_id="doc-notext",
+ collection_id=coll_id,
+ indexed=False,
+ ),
+ ]
+ )
+ session.commit()
+
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings(sweep_library_collections=True)
+
+ rag_service = _rag_service()
+ indexed_ids = []
+ rag_service.index_document.side_effect = (
+ lambda *, document_id, collection_id, force_reindex: (
+ indexed_ids.append(document_id)
+ or {"status": "success", "chunk_count": 1}
+ )
+ )
+
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ _patched_session(session),
+ patch(FACTORY, return_value=rag_service),
+ ):
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ # Only the unindexed, text-bearing, in-collection doc was selected for case
+ # (a). (doc-indexed excluded by indexed.is_(False); doc-notext excluded by
+ # text_content.isnot(None).)
+ case_a_indexed = [
+ i for i in indexed_ids if i in {"doc-unindexed", "doc-indexed"}
+ ]
+ assert case_a_indexed == ["doc-unindexed"]
+ assert "doc-notext" not in indexed_ids
+
+
+def test_case_b_predicate_selects_research_orphans_real_db():
+ """Finding 2 (b): with a REAL DB, the case-(b) outerjoin/predicate selects a
+ research orphan (research_id set, text not null, NO default-library link)
+ and excludes a research doc already linked in the default library. Inverting
+ ``DocumentCollection.id.is_(None)`` -> ``isnot(None)`` fails here.
+ """
+ from local_deep_research.database.models.library import DocumentCollection
+
+ session, st_id, default_lib_id, coll_id = _real_db_session()
+
+ # Orphan: research_id set, text, NO link in default library -> selected.
+ _seed_document(
+ session, st_id, doc_id="orphan", text_content="t", research_id="r1"
+ )
+ # Already in default library -> NOT selected by case (b).
+ _seed_document(
+ session, st_id, doc_id="in-lib", text_content="t", research_id="r2"
+ )
+ session.add(
+ DocumentCollection(
+ document_id="in-lib",
+ collection_id=default_lib_id,
+ indexed=True,
+ )
+ )
+ session.commit()
+
+ scheduler = _fresh_scheduler()
+ # generate_rag-only: the no-regression path that depends on case (b).
+ settings = DocumentSchedulerSettings(
+ sweep_library_collections=False, generate_rag=True
+ )
+
+ rag_service = _rag_service()
+ indexed_into_default = []
+ rag_service.index_document.side_effect = (
+ lambda *, document_id, collection_id, force_reindex: (
+ indexed_into_default.append((document_id, collection_id))
+ or {"status": "success", "chunk_count": 1}
+ )
+ )
+
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ _patched_session(session),
+ patch(FACTORY, return_value=rag_service),
+ ):
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ default_targets = [
+ doc_id
+ for (doc_id, coll) in indexed_into_default
+ if coll == "default-lib"
+ ]
+ # The orphan was ingested into the default library; the already-linked doc
+ # was NOT re-selected by the orphan query.
+ assert default_targets == ["orphan"]
+
+
+# ---------------------------------------------------------------------------
+# Finding 3: per-collection isolation + orphan/per-collection password redaction
+# ---------------------------------------------------------------------------
+
+
+def test_per_collection_error_isolated_other_collections_still_indexed():
+ """Finding 3 (i): when coll-B's get_rag_service raises, the tick completes,
+ coll-A's docs are still indexed, and the shared session was rolled back via
+ safe_rollback (the per-collection coll_error handler).
+ """
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings(sweep_library_collections=True)
+
+ db, _ = _db_returning(
+ [("doc-a", "coll-A"), ("doc-b", "coll-B")], case_b_rows=[]
+ )
+
+ good_service = _rag_service()
+
+ def factory_side_effect(username, *, collection_id, db_password):
+ if collection_id == "coll-B":
+ raise RuntimeError("coll-B factory boom")
+ return good_service
+
+ rollback_calls = []
+
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ _patched_session(db),
+ patch(FACTORY, side_effect=factory_side_effect),
+ patch(
+ f"{MODULE}.safe_rollback",
+ side_effect=lambda *a, **kw: rollback_calls.append(a),
+ ),
+ ):
+ # Must not raise even though coll-B blew up.
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ # coll-A's doc was indexed despite coll-B failing (cross-collection
+ # isolation).
+ indexed_docs = {
+ c.kwargs["document_id"]
+ for c in good_service.index_document.call_args_list
+ }
+ assert indexed_docs == {"doc-a"}
+ # The per-collection handler rolled back the poisoned session at least once.
+ assert len(rollback_calls) >= 1
+
+
+def test_per_collection_error_does_not_leak_password(loguru_caplog_full):
+ """Finding 3 (ii): a per-collection failure whose message contains the
+ sentinel password must not leak it into the log output (coll_error path uses
+ redact_secrets).
+
+ Uses ``loguru_caplog_full`` because the package disables loguru by default
+ in tests; without re-enabling it the capture would be empty and the leak
+ assertion would pass vacuously (it also captures the exception block).
+ """
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings(sweep_library_collections=True)
+
+ db, _ = _db_returning([("doc-a", "coll-A")], case_b_rows=[])
+
+ def factory_side_effect(username, *, collection_id, db_password):
+ raise RuntimeError("collection failure with secret testpass inside")
+
+ with loguru_caplog_full.at_level("DEBUG"):
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ _patched_session(db),
+ patch(FACTORY, side_effect=factory_side_effect),
+ ):
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ text = loguru_caplog_full.text
+ # The per-collection error handler ran (proving the path was exercised).
+ assert "[RECONCILER] Failed to index collection" in text
+ # ...and the plaintext password never reached the log output.
+ assert "testpass" not in text, (
+ "Password leaked into per-collection error log output"
+ )
+
+
+def test_orphan_path_error_does_not_leak_password(loguru_caplog_full):
+ """Finding 3 (ii): an orphan-path failure whose message contains the
+ sentinel password must not leak it (orphan_error path uses redact_secrets).
+ """
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings(sweep_library_collections=True)
+
+ # No case (a) work; one orphan whose service build raises.
+ db, _ = _db_returning([], case_b_rows=[("orphan-doc",)])
+
+ def factory_side_effect(username, *, collection_id, db_password):
+ raise RuntimeError("orphan failure with secret testpass inside")
+
+ with loguru_caplog_full.at_level("DEBUG"):
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ _patched_session(db),
+ patch(FACTORY, side_effect=factory_side_effect),
+ ):
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ text = loguru_caplog_full.text
+ assert "[RECONCILER] Failed to index research" in text
+ assert "testpass" not in text, (
+ "Password leaked into orphan error log output"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Finding 4: partial case-(a) budget; case (b) still uses its own full budget
+# ---------------------------------------------------------------------------
+
+
+def test_case_a_selection_is_randomized_not_deterministic_real_db():
+ """Finding 1: the case-(a) query uses ``order_by(func.random())`` (not a
+ stable id order) so a block of permanently-failing low-id rows can't pin the
+ LIMIT slots every tick and starve indexable higher-id rows forever.
+
+ Seed MORE than ``_LIBRARY_SWEEP_BATCH`` selectable in-collection unindexed
+ rows and run the case-(a) SELECTION several times WITHOUT letting any row
+ flip to indexed=True between draws (``index_document`` is a no-op stub that
+ only records which ids were drawn). With a pool of (BATCH + 25) and a LIMIT
+ of BATCH, the probability that two random draws return the identical
+ BATCH-subset is astronomically small (C(75, 50) is ~2.5e19 possible
+ subsets), so "not all draws identical" is a deterministic pass in practice.
+
+ Mutation check: change BOTH ``order_by(func.random())`` to a stable
+ ``order_by(DocumentCollection.document_id)`` / ``order_by(Document.id)`` and
+ this test fails because every draw returns the SAME id set.
+ """
+ from local_deep_research.database.models.library import DocumentCollection
+
+ session, st_id, default_lib_id, coll_id = _real_db_session()
+
+ # Seed a pool LARGER than the batch so the LIMIT(BATCH) must subsample it.
+ pool_size = _LIBRARY_SWEEP_BATCH + 25
+ links = []
+ for i in range(pool_size):
+ # Zero-padded ids so a stable id-order would be a well-defined, fixed
+ # prefix (making the mutation's determinism unambiguous).
+ doc_id = f"doc-{i:04d}"
+ _seed_document(session, st_id, doc_id=doc_id, text_content="hi")
+ links.append(
+ DocumentCollection(
+ document_id=doc_id,
+ collection_id=coll_id,
+ indexed=False,
+ )
+ )
+ session.add_all(links)
+ session.commit()
+
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings(sweep_library_collections=True)
+
+ # Capture the set of document ids drawn on the most recent reconcile run.
+ # CRITICAL: the stub does NOT flip indexed=True, so every draw sees the same
+ # candidate pool — any change in the selected set is due to random ordering,
+ # not to rows leaving the pool.
+ last_draw: set = set()
+ rag_service = _rag_service()
+
+ def index_side_effect(*, document_id, collection_id, force_reindex):
+ last_draw.add(document_id)
+ return {"status": "success", "chunk_count": 1}
+
+ rag_service.index_document.side_effect = index_side_effect
+
+ draws = []
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ _patched_session(session),
+ patch(FACTORY, return_value=rag_service),
+ ):
+ # Up to 4 draws for extra robustness: assert they are NOT all identical.
+ for _ in range(4):
+ last_draw = set()
+ scheduler._reconcile_unindexed_documents("testuser")
+ draws.append(frozenset(last_draw))
+
+ # Sanity: each draw selected exactly the LIMIT (the pool is larger).
+ for draw in draws:
+ assert len(draw) == _LIBRARY_SWEEP_BATCH
+
+ # Randomized order_by => the draws are NOT all the same BATCH-subset. A
+ # stable order_by(id) would make every draw identical (mutation fails here).
+ assert len(set(draws)) > 1, (
+ "case-(a) selection appears deterministic across draws; "
+ "order_by(func.random()) regressed to a stable order"
+ )
+
+
+def test_case_b_orphan_selection_is_randomized_not_deterministic_real_db():
+ """Finding 4: case-(b) (research orphans) ALSO uses order_by(func.random())
+ so a block of permanently-failing low-id orphans can't pin the LIMIT slots
+ every tick and starve the rest. The case-(a) randomization test above seeds
+ only case-(a) rows (research_id=None) so it does NOT guard case (b); this
+ seeds > _LIBRARY_SWEEP_BATCH research orphans.
+
+ Mutation check: change case (b)'s order_by(func.random()) to a stable
+ order_by(Document.id) and this test fails (every draw identical) while the
+ case-(a) test still passes.
+ """
+ session, st_id, default_lib_id, coll_id = _real_db_session()
+
+ # Seed a pool of research ORPHANS (research_id set, text, and NO
+ # default-library DocumentCollection link) larger than the batch. With no
+ # link they are excluded from case (a) (which inner-joins DocumentCollection)
+ # and selected only by case (b).
+ pool_size = _LIBRARY_SWEEP_BATCH + 25
+ for i in range(pool_size):
+ _seed_document(
+ session,
+ st_id,
+ doc_id=f"orphan-{i:04d}",
+ text_content="hi",
+ research_id=f"r{i:04d}",
+ )
+ session.commit()
+
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings(sweep_library_collections=True)
+
+ # No-op stub: does NOT create the default-library link, so every orphan
+ # stays an orphan and the candidate pool is stable across draws — any
+ # variation in the selected set is due to random ordering alone.
+ last_draw: set = set()
+ rag_service = _rag_service()
+
+ def index_side_effect(*, document_id, collection_id, force_reindex):
+ last_draw.add(document_id)
+ return {"status": "success", "chunk_count": 1}
+
+ rag_service.index_document.side_effect = index_side_effect
+
+ draws = []
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ _patched_session(session),
+ patch(FACTORY, return_value=rag_service),
+ ):
+ for _ in range(4):
+ last_draw = set()
+ scheduler._reconcile_unindexed_documents("testuser")
+ draws.append(frozenset(last_draw))
+
+ for draw in draws:
+ assert len(draw) == _LIBRARY_SWEEP_BATCH
+
+ assert len(set(draws)) > 1, (
+ "case-(b) orphan selection appears deterministic across draws; "
+ "order_by(func.random()) regressed to a stable order"
+ )
+
+
+def test_partial_case_a_budget_orphan_uses_own_full_budget():
+ """Finding 4: when case (a) returns a PARTIAL batch (0 < N < BATCH), the
+ orphan query still uses its OWN full _LIBRARY_SWEEP_BATCH limit (independent
+ budgets), and total index_document work is bounded by N + (orphans found).
+ """
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings(sweep_library_collections=True)
+
+ # Partial case-(a) batch: 0 < n < _LIBRARY_SWEEP_BATCH so the OLD shared
+ # budget would have reduced the orphan limit to (BATCH - n).
+ n = 3
+ case_a = [(f"doc-{i}", "coll-A") for i in range(n)]
+ db, query = _db_returning(case_a, case_b_rows=[("orphan-doc",)])
+
+ rag_service = _rag_service()
+
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ _patched_session(db),
+ patch(FACTORY, return_value=rag_service),
+ ):
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ # Both queries used the full per-case budget — the orphan query's limit is
+ # NOT reduced by the partial case (a) count (no `remaining` subtraction).
+ assert query.limit.call_args_list == [
+ ((_LIBRARY_SWEEP_BATCH,), {}),
+ ((_LIBRARY_SWEEP_BATCH,), {}),
+ ]
+ # Total work = N case-(a) docs + 1 orphan, all bounded.
+ assert rag_service.index_document.call_count == n + 1
+
+
+# ---------------------------------------------------------------------------
+# Finding 2: the egress backstop is armed for the scheduled reconcile run
+# ---------------------------------------------------------------------------
+
+
+def test_reconciler_arms_egress_backstop_in_body():
+ """Finding 2: once past the gate, the reconciler arms the PEP-578 audit-hook
+ egress backstop exactly once via ``_arm_egress_backstop(settings_manager,
+ username)`` — defense-in-depth parity with an interactive run, since embedding
+ providers may make network calls during indexing.
+
+ Drives the reconciler fully THROUGH the body (enabled + sweep ON) with both
+ the case-(a) and case-(b) queries returning EMPTY so it does minimal work,
+ and asserts the backstop was armed once with (settings_manager, username).
+ Uses a spy (MagicMock) for ``_arm_egress_backstop`` rather than the no-op
+ lambda the shared helper installs, so the call is actually observed.
+
+ Mutation check: delete the ``self._arm_egress_backstop(...)`` line and this
+ test fails (the spy is never called).
+ """
+ scheduler = _fresh_scheduler()
+ settings = DocumentSchedulerSettings(sweep_library_collections=True)
+
+ # Both queries empty => the reconciler still passes the gate, opens the
+ # session, arms the backstop, then finds no work.
+ db, _ = _db_returning([], case_b_rows=[])
+
+ @contextmanager
+ def fake_get_user_db_session(*a, **kw):
+ yield db
+
+ # Capture the SettingsManager instance constructed inside the body so we can
+ # assert it is exactly what was passed to the backstop.
+ settings_manager_instance = MagicMock()
+
+ with (
+ patch.object(
+ scheduler,
+ "_get_document_scheduler_settings",
+ return_value=settings,
+ ),
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ side_effect=fake_get_user_db_session,
+ ),
+ patch(
+ "local_deep_research.settings.manager.SettingsManager",
+ return_value=settings_manager_instance,
+ ),
+ # autospec=True preserves the descriptor so the spy is invoked as a
+ # bound method (``self`` is the implicit first arg).
+ patch.object(
+ BackgroundJobScheduler,
+ "_arm_egress_backstop",
+ autospec=True,
+ ) as arm_spy,
+ patch(DEFAULT_LIB, return_value="default-lib"),
+ patch(FACTORY) as mock_factory,
+ ):
+ scheduler._reconcile_unindexed_documents("testuser")
+
+ # The backstop was armed exactly once with the in-body SettingsManager and
+ # the username (``self`` is the scheduler since autospec keeps it bound).
+ arm_spy.assert_called_once_with(
+ scheduler, settings_manager_instance, "testuser"
+ )
+ # No work to do, so no RAG service was built.
+ mock_factory.assert_not_called()
diff --git a/tests/news/test_scheduler.py b/tests/news/test_scheduler.py
index f3cc068c89..41a9ae2876 100644
--- a/tests/news/test_scheduler.py
+++ b/tests/news/test_scheduler.py
@@ -1319,7 +1319,11 @@ class TestScheduleDocumentProcessing:
):
scheduler._schedule_document_processing("testuser")
- scheduler.scheduler.remove_job.assert_called_with(
+ # The document-processing job is torn down before being re-added.
+ # (_schedule_document_processing also tears down the opt-in
+ # library-sweep job, so use assert_any_call rather than asserting the
+ # last call.)
+ scheduler.scheduler.remove_job.assert_any_call(
"testuser_document_processing"
)
diff --git a/tests/research_library/services/test_download_service_3827_fix.py b/tests/research_library/services/test_download_service_3827_fix.py
index 79250b2027..553c3ff5fa 100644
--- a/tests/research_library/services/test_download_service_3827_fix.py
+++ b/tests/research_library/services/test_download_service_3827_fix.py
@@ -855,9 +855,10 @@ def test_process_user_documents_rolls_back_on_resource_error():
def test_process_user_documents_rolls_back_on_text_extraction_wrapper_error():
"""If the text-extraction block raises before the per-resource loop —
- e.g. the resources query itself fails — the WRAPPER except at line ~944
- must roll back, otherwise the subsequent RAG block and the post-loop
- last_run commit run on a poisoned session.
+ e.g. the resources query itself fails — the WRAPPER except must roll back,
+ otherwise the post-loop last_run commit runs on a poisoned session. (RAG
+ indexing has moved to _reconcile_unindexed_documents, but text-extraction
+ rollback is still required for the last_run commit.)
"""
from datetime import datetime, UTC
@@ -940,24 +941,37 @@ def test_process_user_documents_rolls_back_on_text_extraction_wrapper_error():
# ---------------------------------------------------------------------------
-# Change 3 (continued): the RAG WRAPPER except at ~line 1058 also calls
-# safe_rollback. Triggered when an exception escapes the RAG block — e.g.
-# LibraryRAGService construction itself fails.
+# Change 3 (continued): RAG indexing of research downloads has been RETIRED from
+# _process_user_documents. It now lives in the unified
+# _reconcile_unindexed_documents reconciler (its own scheduled job). These tests
+# assert the inline RAG block is gone: generate_rag no longer drives any RAG
+# work in this download/extract pass, and the module no longer imports
+# LibraryRAGService at all.
# ---------------------------------------------------------------------------
-def test_process_user_documents_rolls_back_on_rag_wrapper_error():
- """If the RAG generation block raises (e.g. LibraryRAGService init
- fails), the WRAPPER except at line ~1058 must roll back so the
- post-loop last_run commit doesn't trip on a poisoned session.
+def test_process_user_documents_no_longer_indexes_rag_inline():
+ """With generate_rag=True but download/extract OFF, _process_user_documents
+ short-circuits (no download/extract work) and never builds a RAG service —
+ the inline RAG-indexing block has been retired into the reconciler. There is
+ no longer a RAG wrapper rollback path here to exercise.
"""
from datetime import datetime, UTC
+ import local_deep_research.scheduler.background as bg
from local_deep_research.scheduler.background import (
BackgroundJobScheduler,
DocumentSchedulerSettings,
)
+ # The retired block was the only consumer of LibraryRAGService at module
+ # scope; its removal must hold so a regression can't quietly reintroduce
+ # inline indexing.
+ assert not hasattr(bg, "LibraryRAGService"), (
+ "LibraryRAGService should no longer be imported in background.py — "
+ "RAG indexing moved to _reconcile_unindexed_documents."
+ )
+
BackgroundJobScheduler._instance = None
with patch("local_deep_research.scheduler.background.BackgroundScheduler"):
scheduler = BackgroundJobScheduler()
@@ -975,28 +989,14 @@ def test_process_user_documents_rolls_back_on_rag_wrapper_error():
last_run="",
)
- research = MagicMock()
- research.id = "research-rag"
- research.title = "T"
- research.completed_at = None
+ from contextlib import contextmanager as _cm
db = MagicMock()
- research_query = MagicMock()
- research_query.filter.return_value = research_query
- research_query.order_by.return_value = research_query
- research_query.limit.return_value = research_query
- research_query.all.return_value = [research]
- db.query.return_value = research_query
-
- from contextlib import contextmanager as _cm
@_cm
def fake_get_user_db_session(*a, **kw):
yield db
- # Make LibraryRAGService construction raise — escapes to line ~1058.
- rag_failure = RuntimeError("simulated RAG init failure")
-
with (
patch.object(
scheduler,
@@ -1006,19 +1006,14 @@ def test_process_user_documents_rolls_back_on_rag_wrapper_error():
patch(
"local_deep_research.database.session_context.get_user_db_session",
side_effect=fake_get_user_db_session,
- ),
+ ) as mock_session,
patch(
"local_deep_research.settings.manager.SettingsManager",
return_value=MagicMock(),
),
- patch(
- "local_deep_research.scheduler.background.LibraryRAGService",
- side_effect=rag_failure,
- ),
):
scheduler._process_user_documents("testuser")
- assert db.rollback.called, (
- "db.rollback() must fire in the RAG wrapper except at line ~1058 "
- "so the post-loop last_run commit runs on a clean session."
- )
+ # generate_rag alone no longer enables this pass: it short-circuits before
+ # opening a DB session (download/extract are both off).
+ mock_session.assert_not_called()
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 08df548394..47e718bd14 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -756,11 +756,11 @@
},
"document_scheduler.generate_rag": {
"category": "document_scheduler",
- "description": "Generate RAG embeddings for semantic search",
+ "description": "Index documents in the background for semantic search. LEGACY/DEPRECATED: this is now equivalent to \"Auto-index documents in the background\" below — both enable the unified reconciler that indexes every unindexed document (library uploads AND research downloads). Kept for backward compatibility so existing users keep their research downloads indexed; prefer the auto-index setting for new configurations.",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Generate RAG Embeddings",
+ "name": "Generate RAG Embeddings (legacy)",
"options": null,
"step": null,
"type": "APP",
@@ -782,6 +782,20 @@
"value": 1800,
"visible": true
},
+ "document_scheduler.sweep_library_collections": {
+ "category": "document_scheduler",
+ "description": "Periodically index ALL unindexed documents in the background — both library uploads that weren't indexed immediately (e.g. because the immediate auto-index queue was full) AND research downloads that haven't been ingested into your library yet. Idempotent and processed in small batches per run; already-indexed documents are skipped. Off by default. Requires \"Enable Document Scheduler\" above to be on — the background sweep only runs while the document scheduler is enabled.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "Auto-index documents in the background",
+ "options": null,
+ "step": null,
+ "type": "APP",
+ "ui_element": "checkbox",
+ "value": false,
+ "visible": true
+ },
"embeddings.ollama.num_ctx": {
"category": "embeddings",
"description": "Context window size (in tokens) used when generating Ollama embeddings. Must be at least as large as the longest chunk after tokenization; otherwise Ollama returns 'input length exceeds the context length' (HTTP 500) and indexing fails. The default of 8192 covers chunk sizes up to ~5000 characters for most models. Increase for very large chunks; decrease to save VRAM. qwen3-embedding supports up to 32768; nomic-embed-text supports 8192.",