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(scheduler): run one document pass per user at a time (#6786)

Lukas023cd5f7011a
diff --git a/changelog.d/6722.bugfix.md b/changelog.d/6722.bugfix.md
new file mode 100644
index 0000000000..6d2fd52e8f
--- /dev/null
+++ b/changelog.d/6722.bugfix.md
@@ -0,0 +1 @@
+Triggering document processing by hand while a scheduled pass is running no longer starts a second pass for the same user alongside it: a pass that finds one already running for that user now skips, instead of repeating the work and racing it on the stored last-run time.
diff --git a/src/local_deep_research/scheduler/background.py b/src/local_deep_research/scheduler/background.py
index 47143e9783..8a9c221da9 100644
--- a/src/local_deep_research/scheduler/background.py
+++ b/src/local_deep_research/scheduler/background.py
@@ -41,6 +41,37 @@ SCHEDULER_AVAILABLE = True # Always available since it's a required dependency
# plus this batch cap).
_LIBRARY_SWEEP_BATCH = 50
+# One lock per user for the document pass, held for the length of a pass.
+_document_pass_locks: Dict[str, threading.Lock] = {}
+_document_pass_locks_guard = threading.Lock()
+
+
+def _one_document_pass_per_user(method: Callable) -> Callable:
+ """Skip a document pass while another one for the same user is running.
+
+ The interval job and a manual trigger are separate APScheduler jobs, and
+ max_instances=1 limits each job only by its own id, so a manual trigger
+ during a scheduled pass started a second pass for the same user,
+ concurrently with the first (#6722).
+ """
+
+ @wraps(method)
+ def run_unless_running(self, username: str, *args, **kwargs):
+ with _document_pass_locks_guard:
+ lock = _document_pass_locks.setdefault(username, threading.Lock())
+ if not lock.acquire(blocking=False):
+ logger.info(
+ f"[DOC_SCHEDULER] Document processing is already running for "
+ f"{username}; skipping this run"
+ )
+ return None
+ try:
+ return method(self, username, *args, **kwargs)
+ finally:
+ lock.release()
+
+ return run_unless_running
+
class SchedulerCredentialStore(CredentialStoreBase):
"""Credential store for the news scheduler.
@@ -910,6 +941,7 @@ class BackgroundJobScheduler:
return True
@thread_cleanup
+ @_one_document_pass_per_user
def _process_user_documents(self, username: str):
"""Process documents for a user."""
logger.info(f"[DOC_SCHEDULER] Processing documents for user {username}")
diff --git a/tests/news/test_scheduler_document_pass_lock.py b/tests/news/test_scheduler_document_pass_lock.py
new file mode 100644
index 0000000000..17e0f69f3c
--- /dev/null
+++ b/tests/news/test_scheduler_document_pass_lock.py
@@ -0,0 +1,100 @@
+"""One document pass per user at a time (#6722).
+
+The interval job ``{username}_document_processing`` and the manual trigger
+``{username}_document_processing_manual`` are separate APScheduler jobs, and
+``max_instances=1`` limits each job only by its own id. A manual trigger during
+a scheduled pass therefore started a second ``_process_user_documents`` for the
+same user, concurrently with the first. The pass itself now skips while another
+one for the same user is running.
+"""
+
+import threading
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from local_deep_research.scheduler.background import (
+ BackgroundJobScheduler,
+ _one_document_pass_per_user,
+)
+
+
+def scheduler():
+ BackgroundJobScheduler._instance = None
+ with patch(
+ "local_deep_research.scheduler.background.BackgroundScheduler"
+ ) as background_scheduler:
+ background_scheduler.return_value = MagicMock()
+ instance = BackgroundJobScheduler()
+ yield instance
+ BackgroundJobScheduler._instance = None
+
+
+def test_a_second_pass_for_the_same_user_skips_while_the_first_runs(
+ scheduler,
+):
+ scheduler.user_sessions = {
+ "alice": {"scheduled_jobs": set()},
+ "bob": {"scheduled_jobs": set()},
+ }
+ inside = threading.Event()
+ release = threading.Event()
+ lookups = []
+
+ def retrieve(username):
+ # The first thing a pass does after finding the user's session. Hold
+ # alice's first pass here; no credentials then end it cleanly.
+ lookups.append(username)
+ if username == "alice" and not release.is_set():
+ inside.set()
+ release.wait(5)
+
+ scheduler._credential_store = MagicMock()
+ scheduler._credential_store.retrieve.side_effect = retrieve
+
+ first = threading.Thread(
+ target=scheduler._process_user_documents, args=("alice",)
+ )
+ first.start()
+ try:
+ assert inside.wait(2), "the first pass never started"
+
+ # The same user again, as a manual trigger mid-pass would: skipped,
+ # at once rather than after waiting for the first pass.
+ second = threading.Thread(
+ target=scheduler._process_user_documents, args=("alice",)
+ )
+ second.start()
+ second.join(0.5)
+ assert not second.is_alive(), "the second pass waited for the first"
+ assert lookups == ["alice"]
+
+ # Another user's pass is not held up by alice's.
+ scheduler._process_user_documents("bob")
+ assert lookups == ["alice", "bob"]
+ finally:
+ release.set()
+ first.join(2)
+
+ # Once the first pass is over, alice's next one runs.
+ scheduler._process_user_documents("alice")
+ assert lookups == ["alice", "bob", "alice"]
+
+
+def test_a_pass_that_raises_still_lets_the_next_one_run():
+ runs = []
+
+ class Owner:
+ @_one_document_pass_per_user
+ def process(self, username):
+ runs.append(username)
+ raise RuntimeError("pass failed")
+
+ owner = Owner()
+ with pytest.raises(RuntimeError):
+ owner.process("carol")
+ with pytest.raises(RuntimeError):
+ owner.process("carol")
+
+ assert runs == ["carol", "carol"]