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.

refactor: thread-safe accessors for global state (#2402)

LearningCircuit9f8dc647834d
diff --git a/src/local_deep_research/followup_research/routes.py b/src/local_deep_research/followup_research/routes.py
index 9125d81fba..ccd3ca951e 100644
--- a/src/local_deep_research/followup_research/routes.py
+++ b/src/local_deep_research/followup_research/routes.py
@@ -144,7 +144,6 @@ def start_followup():
start_research_process,
run_research_process,
)
- from ..web.routes.globals import active_research, termination_flags
import uuid
data = request.get_json()
@@ -287,8 +286,6 @@ def start_followup():
research_id,
research_params["query"],
"quick", # Use 'quick' for quick summary mode
- active_research,
- termination_flags,
run_research_process,
username=username,
user_password=user_password, # Pass password for metrics database access
diff --git a/src/local_deep_research/web/auth/cleanup_middleware.py b/src/local_deep_research/web/auth/cleanup_middleware.py
index 738d6f9e98..8385c9cb74 100644
--- a/src/local_deep_research/web/auth/cleanup_middleware.py
+++ b/src/local_deep_research/web/auth/cleanup_middleware.py
@@ -35,7 +35,7 @@ def cleanup_completed_research():
if username and hasattr(g, "db_session") and g.db_session:
try:
# Find completed researches that haven't been cleaned up
- from ..routes.globals import active_research
+ from ..routes.globals import is_research_active
# Get all active records for this user with limit and better error handling
active_records = (
@@ -48,7 +48,7 @@ def cleanup_completed_research():
cleaned_count = 0
for record in active_records:
# Check if this research is still active
- if record.research_id not in active_research:
+ if not is_research_active(record.research_id):
# Research has completed, clean up the record
g.db_session.delete(record)
cleaned_count += 1
diff --git a/src/local_deep_research/web/queue/processor_v2.py b/src/local_deep_research/web/queue/processor_v2.py
index 53fe6325bf..76782f9853 100644
--- a/src/local_deep_research/web/queue/processor_v2.py
+++ b/src/local_deep_research/web/queue/processor_v2.py
@@ -24,7 +24,6 @@ from ...notifications.queue_helpers import (
send_research_completed_notification_from_session,
send_research_failed_notification_from_session,
)
-from ..routes.globals import active_research, termination_flags
from ..services.research_service import (
run_research_process,
start_research_process,
@@ -253,8 +252,6 @@ class QueueProcessorV2:
research_id,
query,
mode,
- active_research,
- termination_flags,
run_research_process,
username=username,
user_password=password,
@@ -640,8 +637,6 @@ class QueueProcessorV2:
queued_research.research_id,
queued_research.query,
queued_research.mode,
- active_research,
- termination_flags,
run_research_process,
username=username,
user_password=password, # Pass password for metrics
diff --git a/src/local_deep_research/web/routes/globals.py b/src/local_deep_research/web/routes/globals.py
index 83f2a4f860..d78dc4687e 100644
--- a/src/local_deep_research/web/routes/globals.py
+++ b/src/local_deep_research/web/routes/globals.py
@@ -1,20 +1,232 @@
"""
-Stores global state.
+Thread-safe global state management.
+
+Wraps two module-level dicts (`_active_research`, `_termination_flags`)
+with accessor functions protected by a single ``threading.RLock``.
+All external code should use the accessor functions instead of touching the
+dicts directly.
"""
-# Active research processes
-active_research = {}
-# Termination flags dictionary
-termination_flags = {}
+import threading
+
+# ---------------------------------------------------------------------------
+# Internal state — never import these directly from other modules
+# ---------------------------------------------------------------------------
+_active_research = {}
+_termination_flags = {}
+
+# A single lock protects both dicts. They have strongly correlated lifecycles
+# (entries are created/destroyed together) and operations are fast dict lookups,
+# so a single lock is simpler and eliminates any deadlock risk from lock ordering.
+_lock = threading.RLock()
+
+
+# ===================================================================
+# active_research accessors
+# ===================================================================
+
+
+def is_research_active(research_id):
+ """Return True if *research_id* is in the active-research dict."""
+ with _lock:
+ return research_id in _active_research
+
+
+def get_active_research_ids():
+ """Return a list of all active research IDs (snapshot)."""
+ with _lock:
+ return list(_active_research.keys())
+
+
+def get_active_research_snapshot(research_id):
+ """Return a safe snapshot of an active-research entry, or ``None``.
+
+ The returned dict contains only serialisable fields (``thread`` is
+ excluded). The ``log`` list is shallow-copied — individual entries
+ are never mutated after creation, so this is safe.
+ """
+ with _lock:
+ entry = _active_research.get(research_id)
+ if entry is None:
+ return None
+ return {
+ "progress": entry.get("progress", 0),
+ "status": entry.get("status"),
+ "log": list(entry.get("log", [])),
+ "settings": dict(s)
+ if (s := entry.get("settings")) is not None
+ else None,
+ }
+
+
+def get_research_field(research_id, field, default=None):
+ """Return a single field from an active-research entry.
+
+ For mutable fields (``list``, ``dict``) a shallow copy is returned so
+ callers cannot accidentally mutate shared state.
+ """
+ with _lock:
+ entry = _active_research.get(research_id)
+ if entry is None:
+ return default
+ value = entry.get(field, default)
+ # We explicitly check for list/dict rather than using copy.copy()
+ # because entries may contain threading.Thread objects —
+ # copy.copy(Thread) creates a broken shallow copy sharing the same
+ # OS thread ident. Scalars (int, str, bool) are immutable and safe.
+ # For Thread objects, access them via iter_active_research() snapshots.
+ if isinstance(value, list):
+ return list(value)
+ if isinstance(value, dict):
+ return dict(value)
+ return value
+
+
+def set_active_research(research_id, data):
+ """Insert or replace the active-research entry for *research_id*."""
+ with _lock:
+ _active_research[research_id] = data
+
+
+def update_active_research(research_id, **fields):
+ """Update one or more fields on an existing entry.
+
+ Silently does nothing if *research_id* is not active.
+ """
+ with _lock:
+ entry = _active_research.get(research_id)
+ if entry is not None:
+ entry.update(fields)
+
+
+def append_research_log(research_id, log_entry):
+ """Append *log_entry* to the ``log`` list for *research_id*.
+
+ Silently does nothing if *research_id* is not active.
+ """
+ with _lock:
+ entry = _active_research.get(research_id)
+ if entry is not None:
+ entry.setdefault("log", []).append(log_entry)
+
+def update_progress_if_higher(research_id, new_progress):
+ """Atomically update progress only if *new_progress* exceeds current.
-def get_globals():
+ Returns the resulting progress value, or ``None`` if the research is
+ not active.
"""
- Returns:
- Global state for other modules to access.
+ with _lock:
+ entry = _active_research.get(research_id)
+ if entry is None:
+ return None
+ current = entry.get("progress", 0)
+ if new_progress is not None and new_progress > current:
+ entry["progress"] = new_progress
+ return new_progress
+ return current
+
+
+def remove_active_research(research_id):
+ """Remove *research_id* from the active-research dict (if present)."""
+ with _lock:
+ _active_research.pop(research_id, None)
+
+
+def iter_active_research():
+ """Yield ``(research_id, snapshot)`` pairs for all active research.
+
+ Each *snapshot* is a shallow copy of the entry dict, safe to read
+ outside the lock.
+ """
+ with _lock:
+ items = [
+ (
+ rid,
+ {
+ "progress": entry.get("progress", 0),
+ "status": entry.get("status"),
+ "log": list(entry.get("log", [])),
+ "settings": dict(s)
+ if (s := entry.get("settings")) is not None
+ else None,
+ },
+ )
+ for rid, entry in _active_research.items()
+ ]
+ for rid, data in items:
+ yield rid, data
+
+
+def get_active_research_count():
+ """Return the number of active research entries."""
+ with _lock:
+ return len(_active_research)
+
+
+# ===================================================================
+# termination_flags accessors
+# ===================================================================
+
+
+def is_termination_requested(research_id):
+ """Return ``True`` if termination was requested for *research_id*."""
+ with _lock:
+ return _termination_flags.get(research_id, False)
+
+
+def set_termination_flag(research_id):
+ """Signal that *research_id* should be terminated."""
+ with _lock:
+ _termination_flags[research_id] = True
+
+
+def clear_termination_flag(research_id):
+ """Remove the termination flag for *research_id* (if present)."""
+ with _lock:
+ _termination_flags.pop(research_id, None)
+
+
+# ===================================================================
+# Compound / cleanup helpers
+# ===================================================================
+
+
+def is_research_thread_alive(research_id):
+ """Return ``True`` if the research thread for *research_id* is alive.
+
+ Returns ``False`` if the research is not active or has no thread.
+ """
+ with _lock:
+ entry = _active_research.get(research_id)
+ if entry is None:
+ return False
+ thread = entry.get("thread")
+ return thread is not None and thread.is_alive()
+
+
+def update_progress_and_check_active(research_id, new_progress):
+ """Atomically update progress (if higher) and check if research is active.
+
+ Returns ``(progress_value, is_active)`` where *progress_value* is the
+ resulting progress (or ``None`` if not active) and *is_active* indicates
+ whether *research_id* is still in the active-research dict.
+ """
+ with _lock:
+ entry = _active_research.get(research_id)
+ if entry is None:
+ return (None, False)
+ current = entry.get("progress", 0)
+ if new_progress is not None and new_progress > current:
+ entry["progress"] = new_progress
+ return (new_progress, True)
+ return (current, True)
+
+def cleanup_research(research_id):
+ """Remove *research_id* from both active_research and termination_flags
+ atomically under the single shared lock.
"""
- return {
- "active_research": active_research,
- "termination_flags": termination_flags,
- }
+ with _lock:
+ _active_research.pop(research_id, None)
+ _termination_flags.pop(research_id, None)
diff --git a/src/local_deep_research/web/routes/history_routes.py b/src/local_deep_research/web/routes/history_routes.py
index 1d85de8ba1..a974c8a9c2 100644
--- a/src/local_deep_research/web/routes/history_routes.py
+++ b/src/local_deep_research/web/routes/history_routes.py
@@ -13,7 +13,7 @@ from ..models.database import (
get_logs_for_research,
get_total_logs_for_research,
)
-from ..routes.globals import get_globals
+from ..routes.globals import get_active_research_snapshot
from ..services.research_service import get_research_strategy
from ..utils.rate_limiter import limiter
from ...security import filter_research_metadata
@@ -153,13 +153,11 @@ def get_research_status(research_id):
"report_path": research.report_path,
}
- globals_dict = get_globals()
- active_research = globals_dict["active_research"]
-
- # Add progress information
- if research_id in active_research:
- result["progress"] = active_research[research_id]["progress"]
- result["log"] = active_research[research_id]["log"]
+ # Add progress information from active research (atomic snapshot)
+ snapshot = get_active_research_snapshot(research_id)
+ if snapshot is not None:
+ result["progress"] = snapshot["progress"]
+ result["log"] = snapshot["log"]
elif result.get("status") == ResearchStatus.COMPLETED:
result["progress"] = 100
try:
@@ -224,13 +222,13 @@ def get_research_details(research_id):
# Get strategy information
strategy_name = get_research_strategy(research_id)
- globals_dict = get_globals()
- active_research = globals_dict["active_research"]
+ # Get an atomic snapshot of active research state
+ snapshot = get_active_research_snapshot(research_id)
# If this is an active research, merge with any in-memory logs
- if research_id in active_research:
+ if snapshot is not None:
# Use the logs from memory temporarily until they're saved to the database
- memory_logs = active_research[research_id]["log"]
+ memory_logs = snapshot["log"]
# Filter out logs that are already in the database by timestamp
db_timestamps = {log["time"] for log in logs}
@@ -244,6 +242,12 @@ def get_research_details(research_id):
# Sort logs by timestamp
logs.sort(key=lambda x: x["time"])
+ progress = (
+ snapshot["progress"]
+ if snapshot is not None
+ else (100 if research_data["status"] == ResearchStatus.COMPLETED else 0)
+ )
+
return jsonify(
{
"research_id": research_id,
@@ -251,12 +255,7 @@ def get_research_details(research_id):
"mode": research_data["mode"],
"status": research_data["status"],
"strategy": strategy_name,
- "progress": active_research.get(research_id, {}).get(
- "progress",
- 100
- if research_data["status"] == ResearchStatus.COMPLETED
- else 0,
- ),
+ "progress": progress,
"created_at": research_data["created_at"],
"completed_at": research_data["completed_at"],
"log": logs,
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index a7a71f0faf..1c32781a10 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -48,7 +48,13 @@ from ..services.research_service import (
)
from ..utils.rate_limiter import limiter
from ..utils.templates import render_template_with_defaults
-from .globals import active_research, termination_flags
+from .globals import (
+ append_research_log,
+ get_active_research_ids,
+ get_research_field,
+ is_research_active,
+ set_termination_flag,
+)
# Create a Blueprint for the research application
research_bp = Blueprint("research", __name__)
@@ -688,8 +694,6 @@ def start_research():
research_id,
query,
mode,
- active_research,
- termination_flags,
run_research_process,
username=username, # Pass username to the thread
user_password=user_password, # Pass password for database access
@@ -759,7 +763,7 @@ def terminate_research(research_id):
)
# Check if it's in the active_research dict
- if research_id not in active_research:
+ if not is_research_active(research_id):
# Update the status in the database
research.status = ResearchStatus.SUSPENDED
db_session.commit()
@@ -768,12 +772,12 @@ def terminate_research(research_id):
)
# Set the termination flag
- termination_flags[research_id] = True
+ set_termination_flag(research_id)
# Log the termination request - using UTC timestamp
timestamp = datetime.now(UTC).isoformat()
termination_message = "Research termination requested by user"
- current_progress = active_research[research_id]["progress"]
+ current_progress = get_research_field(research_id, "progress", 0)
# Create log entry
log_entry = {
@@ -784,7 +788,7 @@ def terminate_research(research_id):
}
# Add to in-memory log
- active_research[research_id]["log"].append(log_entry)
+ append_research_log(research_id, log_entry)
# Add to database log
logger.log("MILESTONE", f"Research ended: {termination_message}")
@@ -858,9 +862,8 @@ def delete_research(research_id):
report_path = research.report_path
# Don't allow deleting research in progress
- if (
- status == ResearchStatus.IN_PROGRESS
- and research_id in active_research
+ if status == ResearchStatus.IN_PROGRESS and is_research_active(
+ research_id
):
return (
jsonify(
@@ -902,10 +905,13 @@ def clear_history():
# Get all research records first to clean up files
research_records = db_session.query(ResearchHistory).all()
+ # Get IDs of currently active research (snapshot)
+ active_ids = get_active_research_ids()
+
# Clean up report files
for research in research_records:
# Skip active research
- if research.id in active_research:
+ if research.id in active_ids:
continue
# Delete report file if it exists
@@ -916,9 +922,9 @@ def clear_history():
logger.exception("Error removing report file")
# Delete records from the database, except active research
- if active_research:
+ if active_ids:
db_session.query(ResearchHistory).filter(
- ~ResearchHistory.id.in_(list(active_research.keys()))
+ ~ResearchHistory.id.in_(active_ids)
).delete(synchronize_session=False)
else:
db_session.query(ResearchHistory).delete(
diff --git a/src/local_deep_research/web/routes/research_routes_orm.py b/src/local_deep_research/web/routes/research_routes_orm.py
index eda538b3c7..f865740b2f 100644
--- a/src/local_deep_research/web/routes/research_routes_orm.py
+++ b/src/local_deep_research/web/routes/research_routes_orm.py
@@ -22,7 +22,16 @@ from ...security import filter_research_metadata, strip_settings_snapshot
from ...security.decorators import require_json_body
from ..auth.decorators import login_required
from ..models.database import calculate_duration
-from .globals import active_research, termination_flags
+from .globals import (
+ append_research_log,
+ cleanup_research,
+ get_active_research_count,
+ get_research_field,
+ is_research_active,
+ is_research_thread_alive,
+ iter_active_research,
+ set_termination_flag,
+)
# Create a Blueprint for the research application
research_bp = Blueprint("research", __name__)
@@ -96,11 +105,11 @@ def start_research():
# ... validation code ...
# Check if there's any active research that's actually still running
- if active_research:
+ if get_active_research_count() > 0:
# Verify each active research is still valid
stale_research_ids = []
with get_user_db_session() as db_session:
- for research_id, research_data in list(active_research.items()):
+ for research_id, research_data in iter_active_research():
# Check database status using ORM
research = (
db_session.query(ResearchHistory)
@@ -112,20 +121,14 @@ def start_research():
if (
not research
or research.status != ResearchStatus.IN_PROGRESS
- or (
- not research_data.get("thread")
- or not research_data.get("thread").is_alive()
- )
+ or not is_research_thread_alive(research_id)
):
stale_research_ids.append(research_id)
# Clean up any stale research processes
for stale_id in stale_research_ids:
logger.info(f"Cleaning up stale research process: {stale_id}")
- if stale_id in active_research:
- del active_research[stale_id]
- if stale_id in termination_flags:
- del termination_flags[stale_id]
+ cleanup_research(stale_id)
# Create a record in the database with ORM
created_at = datetime.now(UTC).isoformat()
@@ -187,7 +190,7 @@ def terminate_research(research_id):
)
# Check if it's in the active_research dict
- if research_id not in active_research:
+ if not is_research_active(research_id):
# Update the status in the database
research.status = ResearchStatus.SUSPENDED
db_session.commit()
@@ -196,12 +199,12 @@ def terminate_research(research_id):
)
# Set the termination flag
- termination_flags[research_id] = True
+ set_termination_flag(research_id)
# Log the termination request
timestamp = datetime.now(UTC).isoformat()
termination_message = "Research termination requested by user"
- current_progress = active_research[research_id]["progress"]
+ current_progress = get_research_field(research_id, "progress", 0)
# Create log entry
log_entry = {
@@ -212,7 +215,7 @@ def terminate_research(research_id):
}
# Add to in-memory log
- active_research[research_id]["log"].append(log_entry)
+ append_research_log(research_id, log_entry)
# Update the log in the database
if research.progress_log:
@@ -439,8 +442,8 @@ def api_get_research(research_id):
}
# Add logs if available
- if research_id in active_research:
- data["logs"] = active_research[research_id].get("log", [])
+ if is_research_active(research_id):
+ data["logs"] = get_research_field(research_id, "log", [])
return jsonify(data)
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 8fc4bb3a6f..9da2a0920b 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -204,8 +204,6 @@ def start_research_process(
research_id,
query,
mode,
- active_research,
- termination_flags,
run_research_callback,
**kwargs,
):
@@ -216,14 +214,14 @@ def start_research_process(
research_id: The ID of the research
query: The research query
mode: The research mode (quick/detailed)
- active_research: Dictionary of active research processes
- termination_flags: Dictionary of termination flags
run_research_callback: The callback function to run the research
**kwargs: Additional parameters to pass to the research process (model, search_engine, etc.)
Returns:
threading.Thread: The thread running the research
"""
+ from ..routes.globals import set_active_research
+
# Pass the app context to the thread.
run_research_callback = thread_with_app_context(run_research_callback)
@@ -245,21 +243,22 @@ def start_research_process(
research_id,
query,
mode,
- active_research,
- termination_flags,
),
kwargs=kwargs,
)
thread.daemon = True
thread.start()
- active_research[research_id] = {
- "thread": thread,
- "progress": 0,
- "status": ResearchStatus.IN_PROGRESS,
- "log": [],
- "settings": kwargs, # Store settings for reference
- }
+ set_active_research(
+ research_id,
+ {
+ "thread": thread,
+ "progress": 0,
+ "status": ResearchStatus.IN_PROGRESS,
+ "log": [],
+ "settings": kwargs, # Store settings for reference
+ },
+ )
return thread
@@ -287,9 +286,7 @@ def _generate_report_path(query: str) -> Path:
@log_for_research
@thread_cleanup
-def run_research_process(
- research_id, query, mode, active_research, termination_flags, **kwargs
-):
+def run_research_process(research_id, query, mode, **kwargs):
"""
Run the research process in the background for a given research ID.
@@ -297,11 +294,14 @@ def run_research_process(
research_id: The ID of the research
query: The research query
mode: The research mode (quick/detailed)
- active_research: Dictionary of active research processes
- termination_flags: Dictionary of termination flags
**kwargs: Additional parameters for the research (model_provider, model, search_engine, etc.)
MUST include 'username' for database access
"""
+ from ..routes.globals import (
+ is_research_active,
+ is_termination_requested,
+ update_progress_and_check_active,
+ )
# Extract username - required for database access
username = kwargs.get("username")
@@ -311,13 +311,11 @@ def run_research_process(
raise ValueError("Username is required for research process")
try:
# Check if this research has been terminated before we even start
- if termination_flags.get(research_id):
+ if is_termination_requested(research_id):
logger.info(
f"Research {research_id} was terminated before starting"
)
- cleanup_research_resources(
- research_id, active_research, termination_flags, username
- )
+ cleanup_research_resources(research_id, username)
return
logger.info(
@@ -435,10 +433,8 @@ def run_research_process(
# Set up progress callback
def progress_callback(message, progress_percent, metadata):
# Frequent termination check
- if termination_flags.get(research_id):
- handle_termination(
- research_id, active_research, termination_flags, username
- )
+ if is_termination_requested(research_id):
+ handle_termination(research_id, username)
raise ResearchTerminatedException(
"Research was terminated by user"
)
@@ -503,18 +499,17 @@ def run_research_process(
normalized = progress_percent / 100
adjusted_progress = 85 + (normalized * 10)
- # Don't let progress go backwards
- if research_id in active_research and adjusted_progress is not None:
- current_progress = active_research[research_id].get(
- "progress", 0
+ # Atomically update progress and check if research is still active
+ if adjusted_progress is not None:
+ adjusted_progress, still_active = (
+ update_progress_and_check_active(
+ research_id, adjusted_progress
+ )
)
- adjusted_progress = max(current_progress, adjusted_progress)
-
- # Update active research record
- if research_id in active_research:
- if adjusted_progress is not None:
- active_research[research_id]["progress"] = adjusted_progress
+ else:
+ still_active = is_research_active(research_id)
+ if still_active:
# Queue the progress update to be processed in main thread
if adjusted_progress is not None:
from ..queue.processor_v2 import queue_processor
@@ -582,10 +577,8 @@ def run_research_process(
# Function to check termination during long-running operations
def check_termination():
- if termination_flags.get(research_id):
- handle_termination(
- research_id, active_research, termination_flags, username
- )
+ if is_termination_requested(research_id):
+ handle_termination(research_id, username)
raise ResearchTerminatedException(
"Research was terminated by user during long-running operation"
)
@@ -1210,12 +1203,7 @@ def run_research_process(
logger.info(
"Cleaning up resources for research_id: %s", research_id
)
- cleanup_research_resources(
- research_id,
- active_research,
- termination_flags,
- username,
- )
+ cleanup_research_resources(research_id, username)
logger.info(
"Resources cleaned up for research_id: %s", research_id
)
@@ -1459,9 +1447,7 @@ def run_research_process(
)
# Clean up resources
- cleanup_research_resources(
- research_id, active_research, termination_flags, username
- )
+ cleanup_research_resources(research_id, username)
except ResearchTerminatedException:
logger.info(f"Research {research_id} terminated by user")
@@ -1604,13 +1590,13 @@ def run_research_process(
metadata["has_enhanced_report"] = True
# If we still have an active research record, update its log
- if research_id in active_research:
+ if is_research_active(research_id):
progress_callback(user_friendly_error, None, metadata)
# If termination was requested, mark as suspended instead of failed
status = (
ResearchStatus.SUSPENDED
- if termination_flags.get(research_id)
+ if is_termination_requested(research_id)
else ResearchStatus.FAILED
)
message = (
@@ -1663,23 +1649,19 @@ def run_research_process(
logger.exception("Error in error handler")
# Clean up resources
- cleanup_research_resources(
- research_id, active_research, termination_flags, username
- )
+ cleanup_research_resources(research_id, username)
-def cleanup_research_resources(
- research_id, active_research, termination_flags, username=None
-):
+def cleanup_research_resources(research_id, username=None):
"""
Clean up resources for a completed research.
Args:
research_id: The ID of the research
- active_research: Dictionary of active research processes
- termination_flags: Dictionary of termination flags
username: The username for database access (required for thread context)
"""
+ from ..routes.globals import cleanup_research
+
logger.info("Cleaning up resources for research %s", research_id)
# For testing: Add a small delay to simulate research taking time
@@ -1716,13 +1698,8 @@ def cleanup_research_resources(
f"Cannot notify completion for research {research_id} - no username provided"
)
- # Remove from active research
- if research_id in active_research:
- del active_research[research_id]
-
- # Remove from termination flags
- if research_id in termination_flags:
- del termination_flags[research_id]
+ # Remove from active research and termination flags atomically
+ cleanup_research(research_id)
# Clean up throttle state for this research
with _last_emit_lock:
@@ -1730,11 +1707,16 @@ def cleanup_research_resources(
# Send a final message to subscribers
try:
- if current_status in (ResearchStatus.SUSPENDED, ResearchStatus.FAILED):
+ # Send a final message to any remaining subscribers with explicit status
+ # Use the proper status message based on database status
+ if current_status in (
+ ResearchStatus.SUSPENDED,
+ ResearchStatus.FAILED,
+ ):
final_message = {
"status": current_status,
"message": f"Research was {current_status}",
- "progress": 0,
+ "progress": 0, # For suspended research, show 0% not 100%
}
else:
final_message = {
@@ -1748,6 +1730,7 @@ def cleanup_research_resources(
current_status,
research_id,
)
+
SocketIOService().emit_to_subscribers(
"research_progress", research_id, final_message
)
@@ -1759,16 +1742,12 @@ def cleanup_research_resources(
logger.exception("Error sending final cleanup message")
-def handle_termination(
- research_id, active_research, termination_flags, username=None
-):
+def handle_termination(research_id, username=None):
"""
Handle the termination of a research process.
Args:
research_id: The ID of the research
- active_research: Dictionary of active research processes
- termination_flags: Dictionary of termination flags
username: The username for database access (required for thread context)
"""
logger.info(f"Handling termination for research {research_id}")
@@ -1799,9 +1778,7 @@ def handle_termination(
)
# Clean up resources (this already handles things properly)
- cleanup_research_resources(
- research_id, active_research, termination_flags, username
- )
+ cleanup_research_resources(research_id, username)
def cancel_research(research_id, username):
@@ -1816,22 +1793,15 @@ def cancel_research(research_id, username):
bool: True if the research was found and cancelled, False otherwise
"""
try:
- # Import globals from research routes
- from ..routes.globals import get_globals
-
- globals_dict = get_globals()
- active_research = globals_dict["active_research"]
- termination_flags = globals_dict["termination_flags"]
+ from ..routes.globals import is_research_active, set_termination_flag
# Set termination flag
- termination_flags[research_id] = True
+ set_termination_flag(research_id)
# Check if the research is active
- if research_id in active_research:
+ if is_research_active(research_id):
# Call handle_termination to update database
- handle_termination(
- research_id, active_research, termination_flags, username
- )
+ handle_termination(research_id, username)
return True
else:
try:
diff --git a/src/local_deep_research/web/services/socket_service.py b/src/local_deep_research/web/services/socket_service.py
index 490fb6ab05..0f1a41ea01 100644
--- a/src/local_deep_research/web/services/socket_service.py
+++ b/src/local_deep_research/web/services/socket_service.py
@@ -6,7 +6,7 @@ from flask_socketio import SocketIO
from loguru import logger
from ...constants import ResearchStatus
-from ..routes.globals import get_globals
+from ..routes.globals import get_active_research_snapshot
class SocketIOService:
@@ -101,9 +101,7 @@ class SocketIOService:
@self.__socketio.on("subscribe_to_research")
def on_subscribe(data):
- globals_dict = get_globals()
- active_research = globals_dict.get("active_research", {})
- self.__handle_subscribe(data, request, active_research)
+ self.__handle_subscribe(data, request)
@self.__socketio.on_error
def on_error(e):
@@ -258,7 +256,7 @@ class SocketIOService:
except Exception as e:
self.__log_exception(f"Error handling disconnect: {e}")
- def __handle_subscribe(self, data, request, active_research=None):
+ def __handle_subscribe(self, data, request):
"""Handle client subscription to research updates"""
research_id = data.get("research_id")
if research_id:
@@ -274,13 +272,10 @@ class SocketIOService:
)
# Send current status immediately if available in active research
- if active_research and research_id in active_research:
- progress = active_research[research_id]["progress"]
- latest_log = (
- active_research[research_id]["log"][-1]
- if active_research[research_id]["log"]
- else None
- )
+ snapshot = get_active_research_snapshot(research_id)
+ if snapshot is not None:
+ progress = snapshot["progress"]
+ latest_log = snapshot["log"][-1] if snapshot["log"] else None
if latest_log:
self.emit_socket_event(
diff --git a/tests/web/auth/test_cleanup_middleware.py b/tests/web/auth/test_cleanup_middleware.py
index ed24dc2a46..7d5fbef6d6 100644
--- a/tests/web/auth/test_cleanup_middleware.py
+++ b/tests/web/auth/test_cleanup_middleware.py
@@ -99,8 +99,8 @@ class TestCleanupCompletedResearch:
"local_deep_research.web.auth.cleanup_middleware.should_skip_database_middleware"
) as mock_skip,
patch(
- "local_deep_research.web.routes.globals.active_research",
- {},
+ "local_deep_research.web.routes.globals.is_research_active",
+ return_value=False,
),
):
mock_skip.return_value = False
@@ -137,8 +137,8 @@ class TestCleanupCompletedResearch:
"local_deep_research.web.auth.cleanup_middleware.should_skip_database_middleware"
) as mock_skip,
patch(
- "local_deep_research.web.routes.globals.active_research",
- {"active_research_456": {"status": "running"}},
+ "local_deep_research.web.routes.globals.is_research_active",
+ return_value=True,
),
):
mock_skip.return_value = False
@@ -311,8 +311,8 @@ class TestCleanupCompletedResearch:
"local_deep_research.web.auth.cleanup_middleware.should_skip_database_middleware"
) as mock_skip,
patch(
- "local_deep_research.web.routes.globals.active_research",
- {},
+ "local_deep_research.web.routes.globals.is_research_active",
+ return_value=False,
),
):
mock_skip.return_value = False
diff --git a/tests/web/routes/test_globals.py b/tests/web/routes/test_globals.py
deleted file mode 100644
index e129fe1be1..0000000000
--- a/tests/web/routes/test_globals.py
+++ /dev/null
@@ -1,48 +0,0 @@
-"""Tests for the globals module - module-level state and get_globals()."""
-
-from local_deep_research.web.routes.globals import (
- active_research,
- get_globals,
- termination_flags,
-)
-
-
-class TestGlobalVariables:
- """Tests for the module-level global dictionaries."""
-
- def test_active_research_is_dict(self):
- """active_research should be a dict."""
- assert isinstance(active_research, dict)
-
- def test_termination_flags_is_dict(self):
- """termination_flags should be a dict."""
- assert isinstance(termination_flags, dict)
-
-
-class TestGetGlobals:
- """Tests for the get_globals() helper."""
-
- def test_returns_dict_with_all_keys(self):
- """get_globals should return a dict containing the expected keys."""
- result = get_globals()
- assert isinstance(result, dict)
- assert "active_research" in result
- assert "termination_flags" in result
-
- def test_returns_same_objects_as_module_level(self):
- """The returned values should be the actual module-level dicts (same identity)."""
- result = get_globals()
- assert result["active_research"] is active_research
- assert result["termination_flags"] is termination_flags
-
- def test_modifying_returned_dict_modifies_module_state(self):
- """Because they are references, mutations through get_globals propagate."""
- sentinel_key = "__test_globals_sentinel__"
- result = get_globals()
-
- try:
- result["active_research"][sentinel_key] = "probe"
- assert active_research[sentinel_key] == "probe"
- finally:
- # Clean up so we don't pollute module-level state for other tests
- active_research.pop(sentinel_key, None)
diff --git a/tests/web/routes/test_globals_extended.py b/tests/web/routes/test_globals_extended.py
index cacbba80ba..8247509a4b 100644
--- a/tests/web/routes/test_globals_extended.py
+++ b/tests/web/routes/test_globals_extended.py
@@ -1,301 +1,372 @@
"""
-Extended tests for globals - Global state management.
+Tests for globals.py — thread-safe accessor functions.
Tests cover:
-- Global variable initialization
-- get_globals() function
-- Active research tracking
-- Termination flags management
-- Thread safety considerations
+- Accessor functions for active_research, termination_flags
+- Thread safety (concurrent read/write)
+- Atomic operations (update_progress_if_higher, cleanup_research)
+- Snapshot isolation (returned data cannot mutate shared state)
"""
+import threading
-class TestGlobalVariableInitialization:
- """Tests for global variable initialization."""
+import pytest
- def test_active_research_initialized_as_dict(self):
- """active_research should be initialized as empty dict."""
- active_research = {}
- assert isinstance(active_research, dict)
- assert len(active_research) == 0
+from local_deep_research.web.routes import globals as g
- def test_termination_flags_initialized_as_dict(self):
- """termination_flags should be initialized as empty dict."""
- termination_flags = {}
- assert isinstance(termination_flags, dict)
- assert len(termination_flags) == 0
[email protected](autouse=True)
+def _clean_globals():
+ """Reset all global state before each test."""
+ with g._lock:
+ g._active_research.clear()
+ g._termination_flags.clear()
+ yield
+ with g._lock:
+ g._active_research.clear()
+ g._termination_flags.clear()
-class TestGetGlobals:
- """Tests for get_globals function."""
- def test_returns_dict(self):
- """get_globals should return a dict."""
- active_research = {}
- termination_flags = {}
+# ===================================================================
+# active_research accessors
+# ===================================================================
- globals_dict = {
- "active_research": active_research,
- "termination_flags": termination_flags,
- }
- assert isinstance(globals_dict, dict)
+class TestIsResearchActive:
+ def test_returns_false_when_empty(self):
+ assert g.is_research_active("r1") is False
- def test_contains_active_research_key(self):
- """Globals dict should contain active_research key."""
- globals_dict = {
- "active_research": {},
- "termination_flags": {},
- }
+ def test_returns_true_when_present(self):
+ g.set_active_research("r1", {"progress": 0})
+ assert g.is_research_active("r1") is True
- assert "active_research" in globals_dict
+ def test_returns_false_after_removal(self):
+ g.set_active_research("r1", {"progress": 0})
+ g.remove_active_research("r1")
+ assert g.is_research_active("r1") is False
- def test_contains_termination_flags_key(self):
- """Globals dict should contain termination_flags key."""
- globals_dict = {
- "active_research": {},
- "termination_flags": {},
- }
- assert "termination_flags" in globals_dict
+class TestGetActiveResearchIds:
+ def test_empty(self):
+ assert g.get_active_research_ids() == []
- def test_values_are_references(self):
- """Values should be references to global dicts."""
- active_research = {}
- globals_dict = {"active_research": active_research}
+ def test_returns_all_ids(self):
+ g.set_active_research("r1", {})
+ g.set_active_research("r2", {})
+ ids = g.get_active_research_ids()
+ assert sorted(ids) == ["r1", "r2"]
- # Modifying through globals should affect original
- globals_dict["active_research"]["test"] = "value"
- assert active_research.get("test") == "value"
+ def test_returns_snapshot(self):
+ """Returned list should not be affected by later mutations."""
+ g.set_active_research("r1", {})
+ ids = g.get_active_research_ids()
+ g.set_active_research("r2", {})
+ assert ids == ["r1"]
-class TestActiveResearchTracking:
- """Tests for active research tracking."""
+class TestGetActiveResearchSnapshot:
+ def test_returns_none_when_missing(self):
+ assert g.get_active_research_snapshot("r1") is None
+
+ def test_returns_projected_fields(self):
+ g.set_active_research(
+ "r1",
+ {
+ "thread": threading.current_thread(),
+ "progress": 42,
+ "status": "in_progress",
+ "log": [{"time": "t1", "message": "msg"}],
+ "settings": {"key": "val"},
+ },
+ )
+ snap = g.get_active_research_snapshot("r1")
+ assert snap["progress"] == 42
+ assert snap["status"] == "in_progress"
+ assert len(snap["log"]) == 1
+ assert snap["settings"] == {"key": "val"}
+ assert "thread" not in snap
+
+ def test_log_is_a_copy(self):
+ """Mutating the returned log should not affect shared state."""
+ g.set_active_research(
+ "r1",
+ {
+ "log": [{"m": "a"}],
+ "progress": 0,
+ "status": None,
+ "settings": None,
+ },
+ )
+ snap = g.get_active_research_snapshot("r1")
+ snap["log"].append({"m": "b"})
+ assert len(g.get_active_research_snapshot("r1")["log"]) == 1
+
+ def test_settings_is_a_copy(self):
+ """Mutating returned settings must not affect internal state."""
+ g.set_active_research(
+ "r1", {"settings": {"key": "val"}, "log": [], "progress": 0}
+ )
+ snap = g.get_active_research_snapshot("r1")
+ snap["settings"]["injected"] = True
+ assert (
+ "injected" not in g.get_active_research_snapshot("r1")["settings"]
+ )
+
+
+class TestGetResearchField:
+ def test_returns_default_when_missing(self):
+ assert g.get_research_field("r1", "progress", 99) == 99
+
+ def test_returns_value(self):
+ g.set_active_research("r1", {"progress": 50})
+ assert g.get_research_field("r1", "progress") == 50
+
+ def test_returns_shallow_copy_of_list(self):
+ g.set_active_research("r1", {"log": [1, 2, 3]})
+ log = g.get_research_field("r1", "log")
+ log.append(4)
+ assert g.get_research_field("r1", "log") == [1, 2, 3]
+
+ def test_returns_shallow_copy_of_dict(self):
+ g.set_active_research("r1", {"settings": {"a": 1}})
+ s = g.get_research_field("r1", "settings")
+ s["b"] = 2
+ assert "b" not in g.get_research_field("r1", "settings")
+
+
+class TestSetActiveResearch:
+ def test_insert(self):
+ g.set_active_research("r1", {"progress": 0})
+ assert g.is_research_active("r1")
+
+ def test_overwrite(self):
+ g.set_active_research("r1", {"progress": 10})
+ g.set_active_research("r1", {"progress": 20})
+ assert g.get_research_field("r1", "progress") == 20
+
+
+class TestUpdateActiveResearch:
+ def test_updates_existing(self):
+ g.set_active_research("r1", {"progress": 0, "status": "pending"})
+ g.update_active_research("r1", progress=50)
+ assert g.get_research_field("r1", "progress") == 50
+ assert g.get_research_field("r1", "status") == "pending"
+
+ def test_noop_when_missing(self):
+ # Should not raise
+ g.update_active_research("r1", progress=50)
+
+
+class TestAppendResearchLog:
+ def test_appends(self):
+ g.set_active_research("r1", {"log": []})
+ g.append_research_log("r1", {"time": "t1"})
+ g.append_research_log("r1", {"time": "t2"})
+ assert g.get_research_field("r1", "log") == [
+ {"time": "t1"},
+ {"time": "t2"},
+ ]
+
+ def test_creates_log_list_if_missing(self):
+ g.set_active_research("r1", {})
+ g.append_research_log("r1", {"time": "t1"})
+ assert g.get_research_field("r1", "log") == [{"time": "t1"}]
+
+ def test_noop_when_research_missing(self):
+ g.append_research_log("r1", {"time": "t1"})
+
+
+class TestUpdateProgressIfHigher:
+ def test_updates_when_higher(self):
+ g.set_active_research("r1", {"progress": 10})
+ result = g.update_progress_if_higher("r1", 50)
+ assert result == 50
+ assert g.get_research_field("r1", "progress") == 50
+
+ def test_does_not_go_backwards(self):
+ g.set_active_research("r1", {"progress": 80})
+ result = g.update_progress_if_higher("r1", 50)
+ assert result == 80
+ assert g.get_research_field("r1", "progress") == 80
+
+ def test_returns_none_when_missing(self):
+ assert g.update_progress_if_higher("r1", 50) is None
+
+ def test_handles_none_progress(self):
+ g.set_active_research("r1", {"progress": 30})
+ result = g.update_progress_if_higher("r1", None)
+ assert result == 30
- def test_add_active_research(self):
- """Should be able to add active research."""
- active_research = {}
- research_id = "test-123"
-
- active_research[research_id] = {
- "status": "in_progress",
- "query": "Test query",
- }
-
- assert research_id in active_research
-
- def test_get_active_research(self):
- """Should be able to get active research."""
- active_research = {
- "test-123": {"status": "in_progress", "query": "Test query"}
- }
-
- result = active_research.get("test-123")
- assert result is not None
- assert result["status"] == "in_progress"
-
- def test_remove_active_research(self):
- """Should be able to remove active research."""
- active_research = {"test-123": {"status": "completed"}}
-
- del active_research["test-123"]
- assert "test-123" not in active_research
-
- def test_check_research_exists(self):
- """Should be able to check if research exists."""
- active_research = {"test-123": {}}
-
- exists = "test-123" in active_research
- assert exists is True
-
- not_exists = "test-456" in active_research
- assert not_exists is False
-
- def test_list_active_research_ids(self):
- """Should be able to list all active research IDs."""
- active_research = {
- "test-123": {},
- "test-456": {},
- "test-789": {},
- }
-
- ids = list(active_research.keys())
- assert len(ids) == 3
- assert "test-123" in ids
-
- def test_active_research_count(self):
- """Should be able to count active research."""
- active_research = {
- "test-123": {},
- "test-456": {},
- }
-
- count = len(active_research)
- assert count == 2
-
- def test_update_active_research_status(self):
- """Should be able to update research status."""
- active_research = {"test-123": {"status": "in_progress"}}
-
- active_research["test-123"]["status"] = "completed"
- assert active_research["test-123"]["status"] == "completed"
-
-
-class TestTerminationFlagsManagement:
- """Tests for termination flags management."""
-
- def test_set_termination_flag(self):
- """Should be able to set termination flag."""
- termination_flags = {}
- research_id = "test-123"
-
- termination_flags[research_id] = True
- assert termination_flags[research_id] is True
-
- def test_check_termination_flag(self):
- """Should be able to check termination flag."""
- termination_flags = {
- "test-123": True,
- "test-456": False,
- }
-
- assert termination_flags.get("test-123", False) is True
- assert termination_flags.get("test-456", False) is False
- assert termination_flags.get("test-789", False) is False
-
- def test_clear_termination_flag(self):
- """Should be able to clear termination flag."""
- termination_flags = {"test-123": True}
-
- del termination_flags["test-123"]
- assert "test-123" not in termination_flags
-
- def test_default_termination_false(self):
- """Default termination flag should be False."""
- termination_flags = {}
-
- is_terminated = termination_flags.get("nonexistent", False)
- assert is_terminated is False
-
- def test_multiple_termination_flags(self):
- """Should track multiple termination flags."""
- termination_flags = {
- "test-123": True,
- "test-456": True,
- "test-789": False,
- }
-
- terminated = [k for k, v in termination_flags.items() if v]
- assert len(terminated) == 2
-
-
-class TestConcurrentAccess:
- """Tests for concurrent access patterns."""
-
- def test_dict_supports_concurrent_reads(self):
- """Dict should support concurrent reads."""
- active_research = {"test-123": {"status": "in_progress"}}
-
- # Multiple reads should be safe
- result1 = active_research.get("test-123")
- result2 = active_research.get("test-123")
-
- assert result1 == result2
-
- def test_dict_copy_for_iteration(self):
- """Should copy dict keys for safe iteration."""
- active_research = {
- "test-123": {},
- "test-456": {},
- }
-
- # Copy keys before iteration to avoid modification during iteration
- keys = list(active_research.keys())
- assert len(keys) == 2
-
- def test_atomic_key_check_and_set(self):
- """Key check and set should be atomic."""
- active_research = {}
- research_id = "test-123"
-
- # Use setdefault for atomic check-and-set
- active_research.setdefault(research_id, {})
- active_research[research_id]["status"] = "in_progress"
-
- assert active_research[research_id]["status"] == "in_progress"
+class TestRemoveActiveResearch:
+ def test_removes(self):
+ g.set_active_research("r1", {})
+ g.remove_active_research("r1")
+ assert not g.is_research_active("r1")
-class TestGlobalStateIsolation:
- """Tests for global state isolation."""
+ def test_noop_when_missing(self):
+ g.remove_active_research("r1") # Should not raise
- def test_termination_flags_independent(self):
- """termination_flags should be independent."""
- active_research = {"test-123": {}}
- termination_flags = {}
- # Terminating doesn't automatically remove from active
- termination_flags["test-123"] = True
- assert "test-123" in active_research
- assert termination_flags["test-123"] is True
+class TestIterActiveResearch:
+ def test_yields_all_entries(self):
+ g.set_active_research("r1", {"progress": 10})
+ g.set_active_research("r2", {"progress": 20})
+ entries = dict(g.iter_active_research())
+ assert "r1" in entries
+ assert "r2" in entries
+ assert entries["r1"]["progress"] == 10
- def test_globals_dict_is_snapshot(self):
- """get_globals returns references, not copies."""
- active_research = {}
- termination_flags = {}
+ def test_yields_copies(self):
+ g.set_active_research("r1", {"progress": 10})
+ for _, data in g.iter_active_research():
+ data["progress"] = 999
+ assert g.get_research_field("r1", "progress") == 10
- globals_dict = {
- "active_research": active_research,
- "termination_flags": termination_flags,
- }
+ def test_does_not_hold_lock_during_iteration(self):
+ """Another thread should be able to write while we iterate."""
+ g.set_active_research("r1", {"progress": 10})
+ g.set_active_research("r2", {"progress": 20})
- # References should be same object
- assert globals_dict["active_research"] is active_research
+ write_succeeded = threading.Event()
+
+ for _, _ in g.iter_active_research():
+ # Mid-iteration: a writer thread should not be blocked
+ def writer():
+ g.set_active_research("r3", {"progress": 30})
+ write_succeeded.set()
+
+ t = threading.Thread(target=writer)
+ t.start()
+ t.join(timeout=2)
+ break # Only need one iteration to test
+
+ assert write_succeeded.is_set(), "Writer was blocked by iter lock"
-class TestEdgeCases:
- """Tests for edge cases."""
+class TestGetActiveResearchCount:
+ def test_empty(self):
+ assert g.get_active_research_count() == 0
+
+ def test_counts(self):
+ g.set_active_research("r1", {})
+ g.set_active_research("r2", {})
+ assert g.get_active_research_count() == 2
+
- def test_empty_research_id(self):
- """Should handle empty research ID."""
- active_research = {}
- research_id = ""
+# ===================================================================
+# termination_flags accessors
+# ===================================================================
+
+
+class TestTerminationFlags:
+ def test_default_is_false(self):
+ assert g.is_termination_requested("r1") is False
+
+ def test_set_and_check(self):
+ g.set_termination_flag("r1")
+ assert g.is_termination_requested("r1") is True
+
+ def test_clear(self):
+ g.set_termination_flag("r1")
+ g.clear_termination_flag("r1")
+ assert g.is_termination_requested("r1") is False
- active_research[research_id] = {}
- assert "" in active_research
+ def test_clear_noop_when_missing(self):
+ g.clear_termination_flag("r1") # Should not raise
+
+ def test_independent_flags(self):
+ g.set_termination_flag("r1")
+ assert g.is_termination_requested("r1") is True
+ assert g.is_termination_requested("r2") is False
+
+
+# ===================================================================
+# cleanup_research
+# ===================================================================
+
+
+class TestCleanupResearch:
+ def test_removes_from_all_dicts(self):
+ g.set_active_research("r1", {"progress": 50})
+ g.set_termination_flag("r1")
+ g.cleanup_research("r1")
+ assert not g.is_research_active("r1")
+ assert not g.is_termination_requested("r1")
+
+ def test_noop_when_missing(self):
+ g.cleanup_research("r1") # Should not raise
- def test_special_characters_in_id(self):
- """Should handle special characters in ID."""
- active_research = {}
- research_id = "test-123_abc.def"
- active_research[research_id] = {}
- assert research_id in active_research
+# ===================================================================
+# Thread safety
+# ===================================================================
+
+
+class TestThreadSafety:
+ def test_concurrent_progress_updates(self):
+ """Multiple threads updating progress should not lose data."""
+ g.set_active_research("r1", {"progress": 0})
+ barrier = threading.Barrier(10)
+
+ def updater(value):
+ barrier.wait()
+ g.update_progress_if_higher("r1", value)
+
+ threads = [
+ threading.Thread(target=updater, args=(i * 10,)) for i in range(10)
+ ]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ # Progress should be the maximum value
+ assert g.get_research_field("r1", "progress") == 90
- def test_uuid_format_id(self):
- """Should handle UUID format ID."""
- active_research = {}
- research_id = "550e8400-e29b-41d4-a716-446655440000"
+ def test_concurrent_set_and_remove(self):
+ """Concurrent add/remove should not crash."""
+ errors = []
- active_research[research_id] = {}
- assert research_id in active_research
+ def worker(i):
+ try:
+ for _ in range(100):
+ rid = f"r-{i}"
+ g.set_active_research(rid, {"progress": 0})
+ g.is_research_active(rid)
+ g.remove_active_research(rid)
+ except Exception as e:
+ errors.append(e)
- def test_none_value_in_research(self):
- """Should handle None values in research data."""
- active_research = {"test-123": {"status": None, "query": "Test"}}
+ threads = [threading.Thread(target=worker, args=(i,)) for i in range(5)]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
- assert active_research["test-123"]["status"] is None
+ assert errors == []
+
+ def test_concurrent_cleanup(self):
+ """cleanup_research from multiple threads should not crash."""
+ for i in range(20):
+ g.set_active_research(f"r-{i}", {"progress": i})
+ g.set_termination_flag(f"r-{i}")
- def test_nested_data_in_research(self):
- """Should handle nested data in research."""
- active_research = {
- "test-123": {
- "status": "in_progress",
- "metadata": {
- "iterations": 3,
- "sources": ["a", "b", "c"],
- },
- }
- }
-
- assert active_research["test-123"]["metadata"]["iterations"] == 3
- assert len(active_research["test-123"]["metadata"]["sources"]) == 3
+ errors = []
+
+ def cleaner(i):
+ try:
+ g.cleanup_research(f"r-{i}")
+ except Exception as e:
+ errors.append(e)
+
+ threads = [
+ threading.Thread(target=cleaner, args=(i,)) for i in range(20)
+ ]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ assert errors == []
+ assert g.get_active_research_count() == 0
diff --git a/tests/web/routes/test_history_routes.py b/tests/web/routes/test_history_routes.py
index db0b2194be..471bcb4ab8 100644
--- a/tests/web/routes/test_history_routes.py
+++ b/tests/web/routes/test_history_routes.py
@@ -289,9 +289,9 @@ class TestGetResearchStatus:
mock_session.query.return_value = mock_query
with patch(
- "local_deep_research.web.routes.history_routes.get_globals"
- ) as mock_globals:
- mock_globals.return_value = {"active_research": {}}
+ "local_deep_research.web.routes.history_routes.get_active_research_snapshot"
+ ) as mock_snapshot:
+ mock_snapshot.return_value = None
response = authenticated_client.get(
f"{HISTORY_PREFIX}/status/test-id"
@@ -376,9 +376,9 @@ class TestGetResearchDetails:
mock_strategy.return_value = "standard"
with patch(
- "local_deep_research.web.routes.history_routes.get_globals"
- ) as mock_globals:
- mock_globals.return_value = {"active_research": {}}
+ "local_deep_research.web.routes.history_routes.get_active_research_snapshot"
+ ) as mock_snapshot:
+ mock_snapshot.return_value = None
response = authenticated_client.get(
f"{HISTORY_PREFIX}/details/test-id"
diff --git a/tests/web/routes/test_history_routes_extended.py b/tests/web/routes/test_history_routes_extended.py
index 5cab0950b7..0622efc70e 100644
--- a/tests/web/routes/test_history_routes_extended.py
+++ b/tests/web/routes/test_history_routes_extended.py
@@ -240,11 +240,11 @@ class TestGetResearchStatus:
mock_query.filter_by.return_value.first.return_value = mock_research
mock_session.query.return_value = mock_query
- fake_active = {
- "active-1": {
- "progress": 42,
- "log": [{"time": "10:01", "message": "step 1"}],
- }
+ fake_snapshot = {
+ "progress": 42,
+ "status": "in_progress",
+ "log": [{"time": "10:01", "message": "step 1"}],
+ "settings": None,
}
with (
@@ -253,8 +253,8 @@ class TestGetResearchStatus:
return_value=_make_db_session_ctx(mock_session),
),
patch(
- f"{_HR}.get_globals",
- return_value={"active_research": fake_active},
+ f"{_HR}.get_active_research_snapshot",
+ return_value=fake_snapshot,
),
patch(_AUTH_DB_MANAGER, _mock_auth_db_manager()),
):
@@ -290,7 +290,7 @@ class TestGetResearchStatus:
f"{_HR}.get_user_db_session",
return_value=_make_db_session_ctx(mock_session),
),
- patch(f"{_HR}.get_globals", return_value={"active_research": {}}),
+ patch(f"{_HR}.get_active_research_snapshot", return_value=None),
patch(_AUTH_DB_MANAGER, _mock_auth_db_manager()),
):
with app.test_client() as c:
diff --git a/tests/web/routes/test_research_routes_orm.py b/tests/web/routes/test_research_routes_orm.py
index b51c2b9f6e..988d1a1863 100644
--- a/tests/web/routes/test_research_routes_orm.py
+++ b/tests/web/routes/test_research_routes_orm.py
@@ -693,8 +693,8 @@ class TestGetResearchEndpoint:
"local_deep_research.web.auth.decorators.db_manager"
) as mock_db_manager,
patch(
- "local_deep_research.web.routes.research_routes_orm.active_research",
- {},
+ "local_deep_research.web.routes.research_routes_orm.is_research_active",
+ return_value=False,
),
):
mock_get_session.return_value.__enter__ = MagicMock(
@@ -791,8 +791,12 @@ class TestGetResearchEndpoint:
"local_deep_research.web.auth.decorators.db_manager"
) as mock_db_manager,
patch(
- "local_deep_research.web.routes.research_routes_orm.active_research",
- {"research_123": {"log": active_logs}},
+ "local_deep_research.web.routes.research_routes_orm.is_research_active",
+ return_value=True,
+ ),
+ patch(
+ "local_deep_research.web.routes.research_routes_orm.get_research_field",
+ return_value=active_logs,
),
):
mock_get_session.return_value.__enter__ = MagicMock(
diff --git a/tests/web/services/test_research_service.py b/tests/web/services/test_research_service.py
index 509b9f8441..340e1453c1 100644
--- a/tests/web/services/test_research_service.py
+++ b/tests/web/services/test_research_service.py
@@ -288,8 +288,9 @@ class TestStartResearchProcess:
"local_deep_research.web.services.research_service.thread_with_app_context"
)
@patch("local_deep_research.web.services.research_service.thread_context")
+ @patch("local_deep_research.web.routes.globals.set_active_research")
def test_start_research_process_creates_thread(
- self, mock_thread_context, mock_thread_with_context
+ self, mock_set_active, mock_thread_context, mock_thread_with_context
):
"""start_research_process creates and starts a thread."""
from local_deep_research.web.services.research_service import (
@@ -300,9 +301,6 @@ class TestStartResearchProcess:
mock_thread_with_context.return_value = mock_callback
mock_thread_context.return_value = {}
- active_research = {}
- termination_flags = {}
-
# Mock threading.Thread to not actually start
with patch(
"local_deep_research.web.services.research_service.threading.Thread"
@@ -314,21 +312,22 @@ class TestStartResearchProcess:
research_id=123,
query="test query",
mode="quick",
- active_research=active_research,
- termination_flags=termination_flags,
run_research_callback=mock_callback,
)
mock_thread.start.assert_called_once()
- assert 123 in active_research
- assert active_research[123]["status"] == "in_progress"
+ mock_set_active.assert_called_once()
+ call_args = mock_set_active.call_args
+ assert call_args[0][0] == 123
+ assert call_args[0][1]["status"] == "in_progress"
@patch(
"local_deep_research.web.services.research_service.thread_with_app_context"
)
@patch("local_deep_research.web.services.research_service.thread_context")
+ @patch("local_deep_research.web.routes.globals.set_active_research")
def test_start_research_process_stores_settings(
- self, mock_thread_context, mock_thread_with_context
+ self, mock_set_active, mock_thread_context, mock_thread_with_context
):
"""start_research_process stores settings in active_research."""
from local_deep_research.web.services.research_service import (
@@ -339,9 +338,6 @@ class TestStartResearchProcess:
mock_thread_with_context.return_value = mock_callback
mock_thread_context.return_value = {}
- active_research = {}
- termination_flags = {}
-
with patch(
"local_deep_research.web.services.research_service.threading.Thread"
) as mock_thread_class:
@@ -352,15 +348,15 @@ class TestStartResearchProcess:
research_id=123,
query="test query",
mode="detailed",
- active_research=active_research,
- termination_flags=termination_flags,
run_research_callback=mock_callback,
model="gpt-4",
search_engine="google",
)
- assert active_research[123]["settings"]["model"] == "gpt-4"
- assert active_research[123]["settings"]["search_engine"] == "google"
+ call_args = mock_set_active.call_args
+ settings = call_args[0][1]["settings"]
+ assert settings["model"] == "gpt-4"
+ assert settings["search_engine"] == "google"
class TestCleanupResearchResources:
@@ -368,32 +364,36 @@ class TestCleanupResearchResources:
@patch("local_deep_research.settings.env_registry.is_test_mode")
@patch("local_deep_research.web.queue.processor_v2.queue_processor")
+ @patch("local_deep_research.web.routes.globals.cleanup_research")
@patch("local_deep_research.web.services.socket_service.SocketIOService")
- def test_cleanup_removes_from_active_research(
- self, mock_socket, mock_queue, mock_test_mode
+ def test_cleanup_calls_cleanup_research(
+ self,
+ mock_socket,
+ mock_cleanup,
+ mock_queue,
+ mock_test_mode,
):
- """cleanup_research_resources removes from active_research."""
+ """cleanup_research_resources calls cleanup_research to remove from dicts."""
from local_deep_research.web.services.research_service import (
cleanup_research_resources,
)
mock_test_mode.return_value = False
- active_research = {123: {"thread": Mock(), "progress": 100}}
- termination_flags = {123: False}
-
- cleanup_research_resources(
- 123, active_research, termination_flags, username="testuser"
- )
+ cleanup_research_resources(123, username="testuser")
- assert 123 not in active_research
- assert 123 not in termination_flags
+ mock_cleanup.assert_called_once_with(123)
@patch("local_deep_research.settings.env_registry.is_test_mode")
@patch("local_deep_research.web.queue.processor_v2.queue_processor")
+ @patch("local_deep_research.web.routes.globals.cleanup_research")
@patch("local_deep_research.web.services.socket_service.SocketIOService")
def test_cleanup_notifies_queue_processor(
- self, mock_socket, mock_queue, mock_test_mode
+ self,
+ mock_socket,
+ mock_cleanup,
+ mock_queue,
+ mock_test_mode,
):
"""cleanup_research_resources notifies queue processor."""
from local_deep_research.web.services.research_service import (
@@ -402,12 +402,7 @@ class TestCleanupResearchResources:
mock_test_mode.return_value = False
- active_research = {}
- termination_flags = {}
-
- cleanup_research_resources(
- 123, active_research, termination_flags, username="testuser"
- )
+ cleanup_research_resources(123, username="testuser")
mock_queue.notify_research_completed.assert_called_once_with(
"testuser", 123
@@ -417,48 +412,44 @@ class TestCleanupResearchResources:
class TestCancelResearch:
"""Tests for cancel_research function."""
- @patch("local_deep_research.web.routes.globals.get_globals")
+ @patch(
+ "local_deep_research.web.routes.globals.is_research_active",
+ return_value=True,
+ )
+ @patch("local_deep_research.web.routes.globals.set_termination_flag")
@patch(
"local_deep_research.web.services.research_service.handle_termination"
)
def test_cancel_research_sets_termination_flag(
- self, mock_handle_termination, mock_get_globals
+ self, mock_handle_termination, mock_set_flag, mock_is_active
):
"""cancel_research sets termination flag."""
from local_deep_research.web.services.research_service import (
cancel_research,
)
- active_research = {123: {"thread": Mock()}}
- termination_flags = {}
- mock_get_globals.return_value = {
- "active_research": active_research,
- "termination_flags": termination_flags,
- }
-
result = cancel_research(123, username="testuser")
assert result is True
- assert termination_flags[123] is True
- mock_handle_termination.assert_called_once()
+ mock_set_flag.assert_called_once_with(123)
+ mock_handle_termination.assert_called_once_with(123, "testuser")
- @patch("local_deep_research.web.routes.globals.get_globals")
+ @patch(
+ "local_deep_research.web.routes.globals.is_research_active",
+ return_value=False,
+ )
+ @patch("local_deep_research.web.routes.globals.set_termination_flag")
@patch(
"local_deep_research.web.services.research_service.get_user_db_session"
)
def test_cancel_research_updates_db_for_inactive(
- self, mock_get_session, mock_get_globals
+ self, mock_get_session, mock_set_flag, mock_is_active
):
"""cancel_research updates database for inactive research."""
from local_deep_research.web.services.research_service import (
cancel_research,
)
- mock_get_globals.return_value = {
- "active_research": {},
- "termination_flags": {},
- }
-
mock_research = Mock()
mock_research.status = "in_progress"
@@ -475,23 +466,22 @@ class TestCancelResearch:
assert result is True
assert mock_research.status == "suspended"
- @patch("local_deep_research.web.routes.globals.get_globals")
+ @patch(
+ "local_deep_research.web.routes.globals.is_research_active",
+ return_value=False,
+ )
+ @patch("local_deep_research.web.routes.globals.set_termination_flag")
@patch(
"local_deep_research.web.services.research_service.get_user_db_session"
)
def test_cancel_research_already_completed(
- self, mock_get_session, mock_get_globals
+ self, mock_get_session, mock_set_flag, mock_is_active
):
"""cancel_research returns True for already completed research."""
from local_deep_research.web.services.research_service import (
cancel_research,
)
- mock_get_globals.return_value = {
- "active_research": {},
- "termination_flags": {},
- }
-
mock_research = Mock()
mock_research.status = "completed"
@@ -521,12 +511,7 @@ class TestHandleTermination:
handle_termination,
)
- active_research = {123: {"thread": Mock()}}
- termination_flags = {123: True}
-
- handle_termination(
- 123, active_research, termination_flags, username="testuser"
- )
+ handle_termination(123, username="testuser")
mock_queue.queue_error_update.assert_called_once()
call_kwargs = mock_queue.queue_error_update.call_args[1]
@@ -543,16 +528,9 @@ class TestHandleTermination:
handle_termination,
)
- active_research = {}
- termination_flags = {}
+ handle_termination(123, username="testuser")
- handle_termination(
- 123, active_research, termination_flags, username="testuser"
- )
-
- mock_cleanup.assert_called_once_with(
- 123, active_research, termination_flags, "testuser"
- )
+ mock_cleanup.assert_called_once_with(123, "testuser")
class TestExportQuartoFormat:
@@ -638,8 +616,9 @@ class TestStartResearchProcessWithOptions:
"local_deep_research.web.services.research_service.thread_with_app_context"
)
@patch("local_deep_research.web.services.research_service.thread_context")
+ @patch("local_deep_research.web.routes.globals.set_active_research")
def test_start_research_with_local_collections(
- self, mock_thread_context, mock_thread_with_context
+ self, mock_set_active, mock_thread_context, mock_thread_with_context
):
"""start_research_process handles local_collections option."""
from local_deep_research.web.services.research_service import (
@@ -650,9 +629,6 @@ class TestStartResearchProcessWithOptions:
mock_thread_with_context.return_value = mock_callback
mock_thread_context.return_value = {}
- active_research = {}
- termination_flags = {}
-
with patch(
"local_deep_research.web.services.research_service.threading.Thread"
) as mock_thread_class:
@@ -663,14 +639,13 @@ class TestStartResearchProcessWithOptions:
research_id=123,
query="test query",
mode="detailed",
- active_research=active_research,
- termination_flags=termination_flags,
run_research_callback=mock_callback,
local_collections=["collection1", "collection2"],
)
- assert 123 in active_research
- assert active_research[123]["settings"]["local_collections"] == [
+ call_args = mock_set_active.call_args
+ settings = call_args[0][1]["settings"]
+ assert settings["local_collections"] == [
"collection1",
"collection2",
]
@@ -679,8 +654,9 @@ class TestStartResearchProcessWithOptions:
"local_deep_research.web.services.research_service.thread_with_app_context"
)
@patch("local_deep_research.web.services.research_service.thread_context")
+ @patch("local_deep_research.web.routes.globals.set_active_research")
def test_start_research_stores_knowledge_graph_option(
- self, mock_thread_context, mock_thread_with_context
+ self, mock_set_active, mock_thread_context, mock_thread_with_context
):
"""start_research_process stores knowledge_graph option."""
from local_deep_research.web.services.research_service import (
@@ -691,9 +667,6 @@ class TestStartResearchProcessWithOptions:
mock_thread_with_context.return_value = mock_callback
mock_thread_context.return_value = {}
- active_research = {}
- termination_flags = {}
-
with patch(
"local_deep_research.web.services.research_service.threading.Thread"
) as mock_thread_class:
@@ -704,17 +677,13 @@ class TestStartResearchProcessWithOptions:
research_id=456,
query="test query",
mode="quick",
- active_research=active_research,
- termination_flags=termination_flags,
run_research_callback=mock_callback,
enable_knowledge_graph=True,
)
- assert 456 in active_research
- assert (
- active_research[456]["settings"]["enable_knowledge_graph"]
- is True
- )
+ call_args = mock_set_active.call_args
+ settings = call_args[0][1]["settings"]
+ assert settings["enable_knowledge_graph"] is True
class TestResearchServiceExportFormats:
diff --git a/tests/web/services/test_research_service_errors.py b/tests/web/services/test_research_service_errors.py
index c00b94198a..ff189a1729 100644
--- a/tests/web/services/test_research_service_errors.py
+++ b/tests/web/services/test_research_service_errors.py
@@ -279,10 +279,7 @@ class TestTerminationHandling:
handle_termination,
)
- active_research = {123: {"thread": Mock()}}
- termination_flags = {123: True}
-
- handle_termination(123, active_research, termination_flags, "testuser")
+ handle_termination(123, "testuser")
mock_queue.queue_error_update.assert_called_once()
call_kwargs = mock_queue.queue_error_update.call_args[1]
@@ -347,10 +344,7 @@ class TestTerminationHandling:
handle_termination,
)
- active_research = {123: {"thread": Mock()}}
- termination_flags = {123: True}
-
- handle_termination(123, active_research, termination_flags, "testuser")
+ handle_termination(123, "testuser")
mock_cleanup.assert_called_once()
@@ -364,10 +358,7 @@ class TestTerminationHandling:
handle_termination,
)
- active_research = {}
- termination_flags = {}
-
- handle_termination(123, active_research, termination_flags, "testuser")
+ handle_termination(123, "testuser")
# Should queue error update
mock_queue.queue_error_update.assert_called_once()
diff --git a/tests/web/services/test_research_service_lifecycle.py b/tests/web/services/test_research_service_lifecycle.py
index 93d459bf1b..8caad49e34 100644
--- a/tests/web/services/test_research_service_lifecycle.py
+++ b/tests/web/services/test_research_service_lifecycle.py
@@ -15,31 +15,36 @@ class TestResourceCleanup:
@patch("local_deep_research.settings.env_registry.is_test_mode")
@patch("local_deep_research.web.queue.processor_v2.queue_processor")
+ @patch("local_deep_research.web.routes.globals.cleanup_research")
@patch("local_deep_research.web.services.socket_service.SocketIOService")
def test_cleanup_removes_from_active_dict(
- self, mock_socket, mock_queue, mock_test_mode
+ self,
+ mock_socket,
+ mock_cleanup,
+ mock_queue,
+ mock_test_mode,
):
- """Cleanup removes research from active_research dict."""
+ """Cleanup calls cleanup_research to remove from active dicts."""
from local_deep_research.web.services.research_service import (
cleanup_research_resources,
)
mock_test_mode.return_value = False
- active_research = {123: {"thread": Mock(), "progress": 100}}
- termination_flags = {}
+ cleanup_research_resources(123, "testuser")
- cleanup_research_resources(
- 123, active_research, termination_flags, "testuser"
- )
-
- assert 123 not in active_research
+ mock_cleanup.assert_called_once_with(123)
@patch("local_deep_research.settings.env_registry.is_test_mode")
@patch("local_deep_research.web.queue.processor_v2.queue_processor")
+ @patch("local_deep_research.web.routes.globals.cleanup_research")
@patch("local_deep_research.web.services.socket_service.SocketIOService")
def test_cleanup_notifies_queue_processor(
- self, mock_socket, mock_queue, mock_test_mode
+ self,
+ mock_socket,
+ mock_cleanup,
+ mock_queue,
+ mock_test_mode,
):
"""Cleanup notifies queue processor of completion."""
from local_deep_research.web.services.research_service import (
@@ -48,12 +53,7 @@ class TestResourceCleanup:
mock_test_mode.return_value = False
- active_research = {}
- termination_flags = {}
-
- cleanup_research_resources(
- 123, active_research, termination_flags, "testuser"
- )
+ cleanup_research_resources(123, "testuser")
mock_queue.notify_research_completed.assert_called_once_with(
"testuser", 123
@@ -75,9 +75,14 @@ class TestResourceCleanup:
@patch("local_deep_research.settings.env_registry.is_test_mode")
@patch("local_deep_research.web.queue.processor_v2.queue_processor")
+ @patch("local_deep_research.web.routes.globals.cleanup_research")
@patch("local_deep_research.web.services.socket_service.SocketIOService")
def test_cleanup_socket_emit_failure_handling(
- self, mock_socket_class, mock_queue, mock_test_mode
+ self,
+ mock_socket_class,
+ mock_cleanup,
+ mock_queue,
+ mock_test_mode,
):
"""Cleanup handles socket emit failure gracefully."""
from local_deep_research.web.services.research_service import (
@@ -89,19 +94,19 @@ class TestResourceCleanup:
mock_socket.emit_to_subscribers.side_effect = Exception("Socket error")
mock_socket_class.return_value = mock_socket
- active_research = {}
- termination_flags = {}
-
# Should not raise even with socket error
- cleanup_research_resources(
- 123, active_research, termination_flags, "testuser"
- )
+ cleanup_research_resources(123, "testuser")
@patch("local_deep_research.settings.env_registry.is_test_mode")
@patch("local_deep_research.web.queue.processor_v2.queue_processor")
+ @patch("local_deep_research.web.routes.globals.cleanup_research")
@patch("local_deep_research.web.services.socket_service.SocketIOService")
def test_cleanup_database_session_handling(
- self, mock_socket, mock_queue, mock_test_mode
+ self,
+ mock_socket,
+ mock_cleanup,
+ mock_queue,
+ mock_test_mode,
):
"""Cleanup handles database session properly."""
from local_deep_research.web.services.research_service import (
@@ -110,13 +115,8 @@ class TestResourceCleanup:
mock_test_mode.return_value = False
- active_research = {}
- termination_flags = {}
-
# Should complete without database errors
- cleanup_research_resources(
- 123, active_research, termination_flags, "testuser"
- )
+ cleanup_research_resources(123, "testuser")
mock_queue.notify_research_completed.assert_called()