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(db): race-free prerequisites for dropping IMMEDIATE isolation (#3490)

LearningCircuitdc70698df8f6
diff --git a/src/local_deep_research/database/library_init.py b/src/local_deep_research/database/library_init.py
index 82e36f0621..1ba70c8420 100644
--- a/src/local_deep_research/database/library_init.py
+++ b/src/local_deep_research/database/library_init.py
@@ -7,6 +7,7 @@ This module handles:
- Must be called on app startup for each user
"""
+import threading
import uuid
from loguru import logger
from sqlalchemy.exc import IntegrityError
@@ -19,6 +20,28 @@ from ..constants import (
)
+# Per-user locks serialise the check-then-insert critical sections below.
+# Under IMMEDIATE isolation this was unnecessary; under DEFERRED, two
+# concurrent invocations (e.g. two logins of the same user from two
+# browser tabs) could both see the absent row and both insert, creating
+# duplicate default collections. An application-level lock is simpler
+# than a migration adding a partial UNIQUE constraint, and cheap.
+_user_init_locks: dict[str, threading.Lock] = {}
+_user_init_locks_lock = threading.Lock()
+
+
+def _get_user_init_lock(username: str) -> threading.Lock:
+ """Get (or lazily create) the per-user lock used to serialise the
+ check-then-insert idempotent collection initialisers.
+ """
+ with _user_init_locks_lock:
+ lock = _user_init_locks.get(username)
+ if lock is None:
+ lock = threading.Lock()
+ _user_init_locks[username] = lock
+ return lock
+
+
def seed_source_types(username: str, password: str = None) -> None:
"""
Seed the source_types table with predefined document source types.
@@ -100,7 +123,10 @@ def ensure_default_library_collection(
UUID of the Library collection
"""
try:
- with get_user_db_session(username, password) as session:
+ with (
+ _get_user_init_lock(username),
+ get_user_db_session(username, password) as session,
+ ):
# Check if default library exists
library = (
session.query(Collection).filter_by(is_default=True).first()
@@ -146,7 +172,10 @@ def ensure_research_history_collection(
UUID of the Research History collection
"""
try:
- with get_user_db_session(username, password) as session:
+ with (
+ _get_user_init_lock(username),
+ get_user_db_session(username, password) as session,
+ ):
# Check if research history collection exists
collection = (
session.query(Collection)
diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.py
index 80ec5a2f5b..535725c33f 100644
--- a/src/local_deep_research/web/queue/processor_v2.py
+++ b/src/local_deep_research/web/queue/processor_v2.py
@@ -71,6 +71,14 @@ class QueueProcessorV2:
self.pending_operations = {}
self._pending_operations_lock = threading.Lock()
+ # Per-user serialisation for the "count active → start direct"
+ # critical section. Without this the count-then-insert races with
+ # itself for the same user (e.g. two concurrent research submissions
+ # from two browser tabs), and IMMEDIATE isolation was what used to
+ # paper over it at the DB layer.
+ self._user_critical_locks: Dict[str, threading.Lock] = {}
+ self._user_critical_locks_lock = threading.Lock()
+
# Count consecutive spawn failures per research_id. Entries are
# popped on success or after hitting SPAWN_RETRY_LIMIT (then the
# research is marked FAILED). In-memory is sufficient: a restart
@@ -79,6 +87,17 @@ class QueueProcessorV2:
# (thread pool, memory) cleared.
self._spawn_retry_counts: dict[str, int] = {}
+ def _get_user_critical_lock(self, username: str) -> threading.Lock:
+ """Get (or lazily create) the per-user lock used to serialise the
+ count-active-and-start-direct critical section for a given user.
+ """
+ with self._user_critical_locks_lock:
+ lock = self._user_critical_locks.get(username)
+ if lock is None:
+ lock = threading.Lock()
+ self._user_critical_locks[username] = lock
+ return lock
+
def start(self):
"""Start the queue processor thread."""
if self.running:
@@ -160,31 +179,39 @@ class QueueProcessorV2:
# Only try direct execution if user has queue_mode="direct"
if queue_mode == "direct":
- # Count active researches
- active_count = (
- db_session.query(UserActiveResearch)
- .filter_by(
- username=username,
- status=ResearchStatus.IN_PROGRESS,
+ # Serialise the count→check→start critical
+ # section at the application layer. Two
+ # concurrent submissions for the same user
+ # must not both observe the same active
+ # count and both start — that would exceed
+ # max_concurrent. A per-user Python lock
+ # gives us that atomicity independent of
+ # the DB isolation level.
+ with self._get_user_critical_lock(username):
+ active_count = (
+ db_session.query(UserActiveResearch)
+ .filter_by(
+ username=username,
+ status=ResearchStatus.IN_PROGRESS,
+ )
+ .count()
)
- .count()
- )
- if active_count < max_concurrent:
- # We have slots - start directly!
- logger.info(
- f"Direct mode: Starting research {research_id} immediately "
- f"(active: {active_count}/{max_concurrent})"
- )
-
- # Start the research directly
- self._start_research_directly(
- username,
- research_id,
- password,
- **kwargs,
- )
- return
+ if active_count < max_concurrent:
+ # We have slots - start directly!
+ logger.info(
+ f"Direct mode: Starting research {research_id} immediately "
+ f"(active: {active_count}/{max_concurrent})"
+ )
+
+ # Start the research directly
+ self._start_research_directly(
+ username,
+ research_id,
+ password,
+ **kwargs,
+ )
+ return
logger.info(
f"Direct mode: Max concurrent reached ({active_count}/"
f"{max_concurrent}), queueing {research_id}"
@@ -582,9 +609,32 @@ class QueueProcessorV2:
for queued_research in queued:
research_id = queued_research.research_id
try:
- # Mark as processing
- queued_research.is_processing = True
+ # Atomically claim this item by flipping is_processing from
+ # False to True in a single UPDATE. If another worker has
+ # already claimed it since our SELECT above, the UPDATE will
+ # match zero rows and we skip. Under non-IMMEDIATE isolation
+ # the previous SELECT+assign pattern would race and two
+ # workers could both process the same queued item.
+ claimed = (
+ db_session.query(QueuedResearch)
+ .filter_by(
+ id=queued_research.id,
+ is_processing=False,
+ )
+ .update(
+ {QueuedResearch.is_processing: True},
+ synchronize_session=False,
+ )
+ )
db_session.commit()
+ if not claimed:
+ logger.debug(
+ f"Queued research {research_id} "
+ f"already claimed by another worker; skipping"
+ )
+ continue
+ # Refresh local object state now that we hold the claim
+ db_session.refresh(queued_research)
# Update task status
queue_service.update_task_status(research_id, "processing")
diff --git a/tests/web/queue/test_processor_v2_concurrency.py b/tests/web/queue/test_processor_v2_concurrency.py
index 26aa030e6b..a6dbc58cef 100644
--- a/tests/web/queue/test_processor_v2_concurrency.py
+++ b/tests/web/queue/test_processor_v2_concurrency.py
@@ -222,6 +222,36 @@ class TestStartQueuedResearchesErrorRecovery:
mock_query.limit.assert_called_with(5)
+ def test_skip_when_already_claimed_by_another_worker(self, processor):
+ """When the atomic UPDATE matches zero rows (another worker
+ already flipped is_processing to True since our SELECT), we must
+ skip the item without starting or deleting it."""
+ queued = Mock()
+ queued.is_processing = False
+ queued.research_id = "res-claimed"
+
+ mock_session = Mock()
+ mock_query = Mock()
+ mock_query.filter_by.return_value = mock_query
+ mock_query.order_by.return_value = mock_query
+ mock_query.limit.return_value = mock_query
+ mock_query.all.return_value = [queued]
+ # Simulate lost claim race: another worker beat us to it.
+ mock_query.update.return_value = 0
+ mock_session.query.return_value = mock_query
+
+ mock_queue_service = Mock()
+ processor._start_research = Mock()
+
+ processor._start_queued_researches(
+ mock_session, mock_queue_service, "alice", "pw", 1
+ )
+
+ processor._start_research.assert_not_called()
+ mock_session.delete.assert_not_called()
+ mock_session.refresh.assert_not_called()
+ mock_queue_service.update_task_status.assert_not_called()
+
# ---------------------------------------------------------------------------
# _start_research_directly cleanup