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: add thread safety to queue operations

LearningCircuit123919dc6f2c
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_service.py b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
index 8ffc439eed..816c11fd3a 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
@@ -39,35 +39,78 @@ class BenchmarkQueueTracker:
This replaces the removed memory_queue functionality for benchmarks.
Since benchmarks are temporary and don't need persistence,
this simple in-memory solution is sufficient.
+
+ Thread-safe for concurrent access from multiple benchmark threads.
"""
def __init__(self):
self.tasks = {}
+ self._lock = threading.Lock()
def add_task(
self, task_id: str, username: str, task_type: str = "benchmark"
):
"""Add a new task to tracking."""
- self.tasks[task_id] = {
- "username": username,
- "task_type": task_type,
- "status": BenchmarkTaskStatus.QUEUED.value,
- "created_at": datetime.now(UTC),
- }
+ with self._lock:
+ self.tasks[task_id] = {
+ "username": username,
+ "task_type": task_type,
+ "status": BenchmarkTaskStatus.QUEUED.value,
+ "created_at": datetime.now(UTC),
+ }
def update_task_status(self, task_id: str, status: BenchmarkTaskStatus):
"""Update the status of a task."""
- if task_id in self.tasks:
- self.tasks[task_id]["status"] = status.value
- self.tasks[task_id]["updated_at"] = datetime.now(UTC)
+ with self._lock:
+ if task_id in self.tasks:
+ self.tasks[task_id]["status"] = status.value
+ self.tasks[task_id]["updated_at"] = datetime.now(UTC)
+ else:
+ logger.warning(
+ f"Attempted to update status for non-existent task: {task_id}"
+ )
def get_task_status(self, task_id: str) -> Optional[Dict]:
"""Get the current status of a task."""
- return self.tasks.get(task_id)
+ with self._lock:
+ return self.tasks.get(task_id)
def remove_task(self, task_id: str):
"""Remove a task from tracking."""
- self.tasks.pop(task_id, None)
+ with self._lock:
+ self.tasks.pop(task_id, None)
+
+ def cleanup_completed_tasks(self, max_age_seconds: int = 3600):
+ """Remove completed tasks older than max_age_seconds.
+
+ Args:
+ max_age_seconds: Maximum age in seconds for completed tasks (default 1 hour)
+ """
+ with self._lock:
+ now = datetime.now(UTC)
+ to_remove = []
+ for task_id, task_data in self.tasks.items():
+ # Only cleanup completed, failed, or cancelled tasks
+ if task_data["status"] in [
+ BenchmarkTaskStatus.COMPLETED.value,
+ BenchmarkTaskStatus.FAILED.value,
+ BenchmarkTaskStatus.CANCELLED.value,
+ ]:
+ # Check if task has updated_at timestamp
+ updated_at = task_data.get(
+ "updated_at", task_data.get("created_at")
+ )
+ if updated_at:
+ age = (now - updated_at).total_seconds()
+ if age > max_age_seconds:
+ to_remove.append(task_id)
+
+ for task_id in to_remove:
+ self.tasks.pop(task_id, None)
+ logger.debug(f"Cleaned up old task: {task_id}")
+
+ if to_remove:
+ logger.info(f"Cleaned up {len(to_remove)} old benchmark tasks")
class BenchmarkService:
diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.py
index 9f0b063873..19fa08bfe3 100644
--- a/src/local_deep_research/web/queue/processor_v2.py
+++ b/src/local_deep_research/web/queue/processor_v2.py
@@ -55,6 +55,7 @@ class QueueProcessorV2:
# Track pending operations from background threads
self.pending_operations = {}
+ self._pending_operations_lock = threading.Lock()
def start(self):
"""Start the queue processor thread."""
@@ -625,13 +626,14 @@ class QueueProcessorV2:
# In processor_v2, we can update directly if we have database access
# or queue it for later processing
operation_id = str(uuid.uuid4())
- self.pending_operations[operation_id] = {
- "username": username,
- "operation_type": "progress_update",
- "research_id": research_id,
- "progress": progress,
- "timestamp": time.time(),
- }
+ with self._pending_operations_lock:
+ self.pending_operations[operation_id] = {
+ "username": username,
+ "operation_type": "progress_update",
+ "research_id": research_id,
+ "progress": progress,
+ "timestamp": time.time(),
+ }
logger.debug(
f"Queued progress update for research {research_id}: {progress}%"
)
@@ -660,17 +662,18 @@ class QueueProcessorV2:
report_path: Optional path to error report
"""
operation_id = str(uuid.uuid4())
- self.pending_operations[operation_id] = {
- "username": username,
- "operation_type": "error_update",
- "research_id": research_id,
- "status": status,
- "error_message": error_message,
- "metadata": metadata,
- "completed_at": completed_at,
- "report_path": report_path,
- "timestamp": time.time(),
- }
+ with self._pending_operations_lock:
+ self.pending_operations[operation_id] = {
+ "username": username,
+ "operation_type": "error_update",
+ "research_id": research_id,
+ "status": status,
+ "error_message": error_message,
+ "metadata": metadata,
+ "completed_at": completed_at,
+ "report_path": report_path,
+ "timestamp": time.time(),
+ }
logger.info(
f"Queued error update for research {research_id} with status {status}"
)
@@ -690,17 +693,21 @@ class QueueProcessorV2:
Returns:
Number of operations processed
"""
- # Find pending operations for this user
+ # Find pending operations for this user (with lock)
operations_to_process = []
- for op_id, op_data in list(self.pending_operations.items()):
- if op_data["username"] == username:
- operations_to_process.append((op_id, op_data))
+ with self._pending_operations_lock:
+ for op_id, op_data in list(self.pending_operations.items()):
+ if op_data["username"] == username:
+ operations_to_process.append((op_id, op_data))
+ # Remove immediately to prevent duplicate processing
+ del self.pending_operations[op_id]
if not operations_to_process:
return 0
processed_count = 0
+ # Process operations outside the lock (to avoid holding lock during DB operations)
for op_id, op_data in operations_to_process:
try:
operation_type = op_data.get("operation_type")
@@ -744,9 +751,6 @@ class QueueProcessorV2:
db_session.commit()
processed_count += 1
- # Remove processed operation
- del self.pending_operations[op_id]
-
except Exception:
logger.exception(f"Error processing operation {op_id}")