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: extract calculate_warnings into web/warning_checks/ module (#2493)

LearningCircuit0c37179aa4fe
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index ec136b464c..7d3581a7e8 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -73,6 +73,7 @@ from ..services.settings_service import (
from ..utils.templates import render_template_with_defaults
from ..server_config import sync_from_settings
from ...security import safe_get
+from ..warning_checks import calculate_warnings
# Create a Blueprint for settings
settings_bp = Blueprint("settings", __name__, url_prefix="/settings")
@@ -149,158 +150,6 @@ def _get_setting_from_session(key: str, default=None):
return default
-def calculate_warnings():
- """Calculate current warning conditions based on settings"""
- warnings = []
-
- try:
- # Get current settings using proper session context
- username = session.get("username")
- with get_user_db_session(username) as db_session:
- if db_session:
- settings_manager = get_settings_manager(db_session, username)
- provider = settings_manager.get_setting(
- "llm.provider", "ollama"
- ).lower()
- local_context = settings_manager.get_setting(
- "llm.local_context_window_size", 4096
- )
-
- # Get dismissal settings
- dismiss_high_context = settings_manager.get_setting(
- "app.warnings.dismiss_high_context", False
- )
-
- logger.debug(
- f"Starting warning calculation - provider={provider}"
- )
-
- # Check warning conditions
- is_local_provider = provider in [
- "ollama",
- "llamacpp",
- "lmstudio",
- "vllm",
- ]
-
- # High context warning for local providers
- if (
- is_local_provider
- and local_context > 8192
- and not dismiss_high_context
- ):
- warnings.append(
- {
- "type": "high_context",
- "icon": "⚠️",
- "title": "High Context Warning",
- "message": f"Context size ({local_context:,} tokens) may cause memory issues with {provider}. Increase VRAM or reduce context size if you experience slowdowns.",
- "dismissKey": "app.warnings.dismiss_high_context",
- }
- )
-
- # Get additional warning settings
- with get_user_db_session(username) as db_session:
- if db_session:
- settings_manager = get_settings_manager(db_session, username)
- dismiss_model_mismatch = settings_manager.get_setting(
- "app.warnings.dismiss_model_mismatch", False
- )
-
- # Get current strategy and model (these need to be passed from the frontend or retrieved differently)
- # For now, we'll implement basic warnings that don't require form state
-
- # Model mismatch warning (simplified - checking setting instead of form value)
- current_model = settings_manager.get_setting("llm.model", "")
- if (
- current_model
- and "70b" in current_model.lower()
- and is_local_provider
- and local_context > 8192
- and not dismiss_model_mismatch
- ):
- warnings.append(
- {
- "type": "model_mismatch",
- "icon": "🧠",
- "title": "Model & Context Warning",
- "message": f"Large model ({current_model}) with high context ({local_context:,}) may exceed VRAM. Consider reducing context size or upgrading GPU memory.",
- "dismissKey": "app.warnings.dismiss_model_mismatch",
- }
- )
-
- # History-based context warning
- # Compare current setting against actual historical usage
- with get_user_db_session(username) as db_session:
- if db_session and is_local_provider:
- from sqlalchemy import desc, func
- from ...database.models import TokenUsage
-
- settings_manager = get_settings_manager(db_session, username)
- dismiss_context_warning = settings_manager.get_setting(
- "app.warnings.dismiss_context_reduced", False
- )
-
- if not dismiss_context_warning:
- # Get context usage from recent researches (last 100)
- recent_contexts = (
- db_session.query(TokenUsage.context_limit)
- .filter(TokenUsage.context_limit.isnot(None))
- .order_by(desc(TokenUsage.timestamp))
- .limit(100)
- .all()
- )
-
- if recent_contexts and len(recent_contexts) >= 5:
- # Calculate percentile-based threshold
- context_values = sorted(
- [r[0] for r in recent_contexts if r[0]]
- )
- if context_values:
- # Use 1st percentile (bottom 1%) as minimum safe context
- # This means 99% of researches used at least this much
- percentile_idx = max(
- 0, int(len(context_values) * 0.01)
- )
- min_safe_context = context_values[percentile_idx]
-
- # Warn if current setting is below the safe minimum
- if local_context < min_safe_context:
- warnings.append(
- {
- "type": "context_below_history",
- "icon": "📉",
- "title": "Context Below Historical Usage",
- "message": f"Current context ({local_context:,}) is below the context window size that 99% of your past researches ran with (min safe: {min_safe_context:,}). This may cause truncation.",
- "dismissKey": "app.warnings.dismiss_context_reduced",
- }
- )
-
- # Also check if previous researches had truncation issues
- truncation_count = (
- db_session.query(func.count(TokenUsage.id))
- .filter(TokenUsage.context_truncated.is_(True))
- .filter(TokenUsage.context_limit >= local_context)
- .scalar()
- )
-
- if truncation_count and truncation_count > 0:
- warnings.append(
- {
- "type": "context_truncation_history",
- "icon": "⚠️",
- "title": "Previous Truncation Detected",
- "message": f"Research was truncated {truncation_count} time(s) with similar or higher context. Consider increasing context window.",
- "dismissKey": "app.warnings.dismiss_context_reduced",
- }
- )
-
- except Exception as e:
- logger.warning(f"Error calculating warnings: {e}")
-
- return warnings
-
-
def validate_setting(
setting: Setting, value: Any
) -> Tuple[bool, Optional[str]]:
diff --git a/src/local_deep_research/web/warning_checks/__init__.py b/src/local_deep_research/web/warning_checks/__init__.py
new file mode 100644
index 0000000000..27791fc20a
--- /dev/null
+++ b/src/local_deep_research/web/warning_checks/__init__.py
@@ -0,0 +1,105 @@
+"""Warning calculation for the settings UI.
+
+Thin orchestrator: reads settings from a single DB session,
+delegates to pure check functions in hardware.py and context.py.
+"""
+
+from typing import List
+
+from flask import session
+from loguru import logger
+
+from ...database.session_context import get_user_db_session
+from ...utilities.db_utils import get_settings_manager
+from .context import (
+ check_context_below_history,
+ check_context_truncation_history,
+)
+from .hardware import LOCAL_PROVIDERS, check_high_context, check_model_mismatch
+
+
+def _safe_check(check_fn, *args, **kwargs):
+ """Run a single warning check, returning None on failure."""
+ try:
+ return check_fn(*args, **kwargs)
+ except Exception:
+ name = getattr(check_fn, "__name__", repr(check_fn))
+ logger.exception(f"Warning check {name} failed")
+ return None
+
+
+def calculate_warnings() -> List[dict]:
+ """Calculate current warning conditions based on settings.
+
+ Uses a single DB session for all setting reads and history queries.
+ """
+ warnings: List[dict] = []
+
+ try:
+ username = session.get("username")
+ with get_user_db_session(username) as db_session:
+ if not db_session:
+ return []
+
+ settings_manager = get_settings_manager(db_session, username)
+
+ # Read all needed settings in one session
+ provider = settings_manager.get_setting(
+ "llm.provider", "ollama"
+ ).lower()
+ local_context = settings_manager.get_setting(
+ "llm.local_context_window_size", 4096
+ )
+ current_model = settings_manager.get_setting("llm.model", "")
+ dismiss_high_context = settings_manager.get_setting(
+ "app.warnings.dismiss_high_context", False
+ )
+ dismiss_model_mismatch = settings_manager.get_setting(
+ "app.warnings.dismiss_model_mismatch", False
+ )
+ dismiss_context_warning = settings_manager.get_setting(
+ "app.warnings.dismiss_context_reduced", False
+ )
+
+ logger.debug(f"Starting warning calculation - provider={provider}")
+
+ is_local = provider in LOCAL_PROVIDERS
+
+ # --- Hardware / settings checks (pure functions) ---
+ w = _safe_check(
+ check_high_context,
+ provider,
+ local_context,
+ dismiss_high_context,
+ )
+ if w:
+ warnings.append(w)
+
+ w = _safe_check(
+ check_model_mismatch,
+ provider,
+ current_model,
+ local_context,
+ dismiss_model_mismatch,
+ )
+ if w:
+ warnings.append(w)
+
+ # --- History-based checks (need DB queries) ---
+ if is_local and not dismiss_context_warning:
+ w = _safe_check(
+ check_context_below_history, db_session, local_context
+ )
+ if w:
+ warnings.append(w)
+
+ w = _safe_check(
+ check_context_truncation_history, db_session, local_context
+ )
+ if w:
+ warnings.append(w)
+
+ except Exception:
+ logger.exception("Error calculating warnings")
+
+ return warnings
diff --git a/src/local_deep_research/web/warning_checks/context.py b/src/local_deep_research/web/warning_checks/context.py
new file mode 100644
index 0000000000..078391d712
--- /dev/null
+++ b/src/local_deep_research/web/warning_checks/context.py
@@ -0,0 +1,79 @@
+"""DB-backed context warning checks.
+
+These functions take an open SQLAlchemy session — no Flask dependency.
+"""
+
+from typing import Optional
+
+from sqlalchemy import desc, func
+from sqlalchemy.orm import Session
+
+from ...database.models import TokenUsage
+
+
+def check_context_below_history(
+ db_session: Session, local_context: int
+) -> Optional[dict]:
+ """Warn if the current context setting is below what 99% of past researches used.
+
+ Requires at least 5 historical records to produce a meaningful percentile.
+ """
+ recent_contexts = (
+ db_session.query(TokenUsage.context_limit)
+ .filter(TokenUsage.context_limit.isnot(None))
+ .order_by(desc(TokenUsage.timestamp))
+ .limit(100)
+ .all()
+ )
+
+ if not recent_contexts or len(recent_contexts) < 5:
+ return None
+
+ context_values = sorted([r[0] for r in recent_contexts if r[0]])
+ if not context_values:
+ return None
+
+ # 1st percentile — 99% of researches used at least this much
+ percentile_idx = max(0, int(len(context_values) * 0.01))
+ min_safe_context = context_values[percentile_idx]
+
+ if local_context >= min_safe_context:
+ return None
+
+ return {
+ "type": "context_below_history",
+ "icon": "📉",
+ "title": "Context Below Historical Usage",
+ "message": (
+ f"Current context ({local_context:,}) is below the context window "
+ f"size that 99% of your past researches ran with "
+ f"(min safe: {min_safe_context:,}). This may cause truncation."
+ ),
+ "dismissKey": "app.warnings.dismiss_context_reduced",
+ }
+
+
+def check_context_truncation_history(
+ db_session: Session, local_context: int
+) -> Optional[dict]:
+ """Warn if past researches experienced truncation at the same or higher context."""
+ truncation_count = (
+ db_session.query(func.count(TokenUsage.id))
+ .filter(TokenUsage.context_truncated.is_(True))
+ .filter(TokenUsage.context_limit >= local_context)
+ .scalar()
+ )
+
+ if not truncation_count or truncation_count <= 0:
+ return None
+
+ return {
+ "type": "context_truncation_history",
+ "icon": "⚠️",
+ "title": "Previous Truncation Detected",
+ "message": (
+ f"Research was truncated {truncation_count} time(s) with similar "
+ f"or higher context. Consider increasing context window."
+ ),
+ "dismissKey": "app.warnings.dismiss_context_reduced",
+ }
diff --git a/src/local_deep_research/web/warning_checks/hardware.py b/src/local_deep_research/web/warning_checks/hardware.py
new file mode 100644
index 0000000000..6a6bf84d37
--- /dev/null
+++ b/src/local_deep_research/web/warning_checks/hardware.py
@@ -0,0 +1,61 @@
+"""Pure hardware/settings-based warning checks.
+
+These functions have zero dependencies on Flask or SQLAlchemy —
+they take primitive values and return warning dicts (or None).
+"""
+
+from typing import Optional
+
+LOCAL_PROVIDERS = frozenset({"ollama", "llamacpp", "lmstudio", "vllm"})
+
+
+def check_high_context(
+ provider: str, local_context: int, dismissed: bool
+) -> Optional[dict]:
+ """Return a high_context warning dict if context exceeds 8192 for a local provider."""
+ if provider not in LOCAL_PROVIDERS:
+ return None
+ if local_context <= 8192:
+ return None
+ if dismissed:
+ return None
+
+ return {
+ "type": "high_context",
+ "icon": "⚠️",
+ "title": "High Context Warning",
+ "message": (
+ f"Context size ({local_context:,} tokens) may cause memory issues "
+ f"with {provider}. Increase VRAM or reduce context size if you "
+ f"experience slowdowns."
+ ),
+ "dismissKey": "app.warnings.dismiss_high_context",
+ }
+
+
+def check_model_mismatch(
+ provider: str, model: str, local_context: int, dismissed: bool
+) -> Optional[dict]:
+ """Return a model_mismatch warning dict for large models with high context."""
+ if not model:
+ return None
+ if provider not in LOCAL_PROVIDERS:
+ return None
+ if "70b" not in model.lower():
+ return None
+ if local_context <= 8192:
+ return None
+ if dismissed:
+ return None
+
+ return {
+ "type": "model_mismatch",
+ "icon": "🧠",
+ "title": "Model & Context Warning",
+ "message": (
+ f"Large model ({model}) with high context ({local_context:,}) "
+ f"may exceed VRAM. Consider reducing context size or upgrading "
+ f"GPU memory."
+ ),
+ "dismissKey": "app.warnings.dismiss_model_mismatch",
+ }
diff --git a/tests/routes/test_settings_routes.py b/tests/routes/test_settings_routes.py
index fdde4e9e56..919d16a0ae 100644
--- a/tests/routes/test_settings_routes.py
+++ b/tests/routes/test_settings_routes.py
@@ -210,9 +210,7 @@ class TestCalculateWarnings:
def test_calculate_warnings_high_context(self):
"""Test warning for high context with local provider."""
- from local_deep_research.web.routes.settings_routes import (
- calculate_warnings,
- )
+ from local_deep_research.web.warning_checks import calculate_warnings
mock_settings_manager = Mock()
mock_settings_manager.get_setting.side_effect = (
@@ -221,22 +219,23 @@ class TestCalculateWarnings:
"llm.local_context_window_size": 16384,
"app.warnings.dismiss_high_context": False,
"app.warnings.dismiss_model_mismatch": False,
+ "app.warnings.dismiss_context_reduced": False,
"llm.model": "llama3",
}.get(key, default)
)
with patch(
- "local_deep_research.web.routes.settings_routes.session",
+ "local_deep_research.web.warning_checks.session",
{"username": "test"},
):
with patch(
- "local_deep_research.web.routes.settings_routes.get_user_db_session"
+ "local_deep_research.web.warning_checks.get_user_db_session"
) as mock_ctx:
mock_ctx.return_value.__enter__ = Mock(return_value=Mock())
mock_ctx.return_value.__exit__ = Mock(return_value=False)
with patch(
- "local_deep_research.web.routes.settings_routes.get_settings_manager",
+ "local_deep_research.web.warning_checks.get_settings_manager",
return_value=mock_settings_manager,
):
warnings = calculate_warnings()
@@ -246,9 +245,7 @@ class TestCalculateWarnings:
def test_calculate_warnings_no_warnings(self):
"""Test no warnings when conditions are fine."""
- from local_deep_research.web.routes.settings_routes import (
- calculate_warnings,
- )
+ from local_deep_research.web.warning_checks import calculate_warnings
mock_settings_manager = Mock()
mock_settings_manager.get_setting.side_effect = (
@@ -257,22 +254,23 @@ class TestCalculateWarnings:
"llm.local_context_window_size": 4096,
"app.warnings.dismiss_high_context": False,
"app.warnings.dismiss_model_mismatch": False,
+ "app.warnings.dismiss_context_reduced": False,
"llm.model": "gpt-4",
}.get(key, default)
)
with patch(
- "local_deep_research.web.routes.settings_routes.session",
+ "local_deep_research.web.warning_checks.session",
{"username": "test"},
):
with patch(
- "local_deep_research.web.routes.settings_routes.get_user_db_session"
+ "local_deep_research.web.warning_checks.get_user_db_session"
) as mock_ctx:
mock_ctx.return_value.__enter__ = Mock(return_value=Mock())
mock_ctx.return_value.__exit__ = Mock(return_value=False)
with patch(
- "local_deep_research.web.routes.settings_routes.get_settings_manager",
+ "local_deep_research.web.warning_checks.get_settings_manager",
return_value=mock_settings_manager,
):
warnings = calculate_warnings()
@@ -281,9 +279,7 @@ class TestCalculateWarnings:
def test_calculate_warnings_context_below_history(self):
"""Test warning when context is below historical usage."""
- from local_deep_research.web.routes.settings_routes import (
- calculate_warnings,
- )
+ from local_deep_research.web.warning_checks import calculate_warnings
mock_settings_manager = Mock()
mock_settings_manager.get_setting.side_effect = (
@@ -315,11 +311,11 @@ class TestCalculateWarnings:
]
with patch(
- "local_deep_research.web.routes.settings_routes.session",
+ "local_deep_research.web.warning_checks.session",
{"username": "test"},
):
with patch(
- "local_deep_research.web.routes.settings_routes.get_user_db_session"
+ "local_deep_research.web.warning_checks.get_user_db_session"
) as mock_ctx:
mock_ctx.return_value.__enter__ = Mock(
return_value=mock_db_session
@@ -327,7 +323,7 @@ class TestCalculateWarnings:
mock_ctx.return_value.__exit__ = Mock(return_value=False)
with patch(
- "local_deep_research.web.routes.settings_routes.get_settings_manager",
+ "local_deep_research.web.warning_checks.get_settings_manager",
return_value=mock_settings_manager,
):
warnings = calculate_warnings()
@@ -338,9 +334,7 @@ class TestCalculateWarnings:
def test_calculate_warnings_context_below_history_not_enough_samples(self):
"""Test no history warning when fewer than 5 samples exist."""
- from local_deep_research.web.routes.settings_routes import (
- calculate_warnings,
- )
+ from local_deep_research.web.warning_checks import calculate_warnings
mock_settings_manager = Mock()
mock_settings_manager.get_setting.side_effect = (
@@ -372,11 +366,11 @@ class TestCalculateWarnings:
]
with patch(
- "local_deep_research.web.routes.settings_routes.session",
+ "local_deep_research.web.warning_checks.session",
{"username": "test"},
):
with patch(
- "local_deep_research.web.routes.settings_routes.get_user_db_session"
+ "local_deep_research.web.warning_checks.get_user_db_session"
) as mock_ctx:
mock_ctx.return_value.__enter__ = Mock(
return_value=mock_db_session
@@ -384,7 +378,7 @@ class TestCalculateWarnings:
mock_ctx.return_value.__exit__ = Mock(return_value=False)
with patch(
- "local_deep_research.web.routes.settings_routes.get_settings_manager",
+ "local_deep_research.web.warning_checks.get_settings_manager",
return_value=mock_settings_manager,
):
warnings = calculate_warnings()
@@ -395,9 +389,7 @@ class TestCalculateWarnings:
def test_calculate_warnings_truncation_history(self):
"""Test warning when past researches had truncation at same/higher context."""
- from local_deep_research.web.routes.settings_routes import (
- calculate_warnings,
- )
+ from local_deep_research.web.warning_checks import calculate_warnings
mock_settings_manager = Mock()
mock_settings_manager.get_setting.side_effect = (
@@ -429,11 +421,11 @@ class TestCalculateWarnings:
]
with patch(
- "local_deep_research.web.routes.settings_routes.session",
+ "local_deep_research.web.warning_checks.session",
{"username": "test"},
):
with patch(
- "local_deep_research.web.routes.settings_routes.get_user_db_session"
+ "local_deep_research.web.warning_checks.get_user_db_session"
) as mock_ctx:
mock_ctx.return_value.__enter__ = Mock(
return_value=mock_db_session
@@ -441,7 +433,7 @@ class TestCalculateWarnings:
mock_ctx.return_value.__exit__ = Mock(return_value=False)
with patch(
- "local_deep_research.web.routes.settings_routes.get_settings_manager",
+ "local_deep_research.web.warning_checks.get_settings_manager",
return_value=mock_settings_manager,
):
warnings = calculate_warnings()
@@ -453,9 +445,7 @@ class TestCalculateWarnings:
def test_calculate_warnings_context_warnings_dismissed(self):
"""Test no history warnings when dismiss_context_reduced is True."""
- from local_deep_research.web.routes.settings_routes import (
- calculate_warnings,
- )
+ from local_deep_research.web.warning_checks import calculate_warnings
mock_settings_manager = Mock()
mock_settings_manager.get_setting.side_effect = (
@@ -472,11 +462,11 @@ class TestCalculateWarnings:
mock_db_session = Mock()
with patch(
- "local_deep_research.web.routes.settings_routes.session",
+ "local_deep_research.web.warning_checks.session",
{"username": "test"},
):
with patch(
- "local_deep_research.web.routes.settings_routes.get_user_db_session"
+ "local_deep_research.web.warning_checks.get_user_db_session"
) as mock_ctx:
mock_ctx.return_value.__enter__ = Mock(
return_value=mock_db_session
@@ -484,7 +474,7 @@ class TestCalculateWarnings:
mock_ctx.return_value.__exit__ = Mock(return_value=False)
with patch(
- "local_deep_research.web.routes.settings_routes.get_settings_manager",
+ "local_deep_research.web.warning_checks.get_settings_manager",
return_value=mock_settings_manager,
):
warnings = calculate_warnings()
diff --git a/tests/security/test_session_username_hardening.py b/tests/security/test_session_username_hardening.py
index 8560c6bfc7..b4be6d27e5 100644
--- a/tests/security/test_session_username_hardening.py
+++ b/tests/security/test_session_username_hardening.py
@@ -216,8 +216,8 @@ class TestSettingsRoutesSessionAccess:
"""Helper functions (not decorated) should still use session.get('username')."""
from local_deep_research.web.routes.settings_routes import (
_get_setting_from_session,
- calculate_warnings,
)
+ from local_deep_research.web.warning_checks import calculate_warnings
for func in [_get_setting_from_session, calculate_warnings]:
source = _get_function_source(func)
diff --git a/tests/web/routes/test_settings_routes.py b/tests/web/routes/test_settings_routes.py
index 97cc087bfa..4c55e37924 100644
--- a/tests/web/routes/test_settings_routes.py
+++ b/tests/web/routes/test_settings_routes.py
@@ -129,26 +129,24 @@ class TestCalculateWarnings:
def test_calculate_warnings_returns_list(self):
"""Test that calculate_warnings returns a list."""
- from local_deep_research.web.routes.settings_routes import (
- calculate_warnings,
- )
+ from local_deep_research.web.warning_checks import calculate_warnings
with patch(
- "local_deep_research.web.routes.settings_routes.get_user_db_session"
+ "local_deep_research.web.warning_checks.get_user_db_session"
) as mock_session:
mock_ctx = MagicMock()
mock_session.return_value.__enter__ = Mock(return_value=mock_ctx)
mock_session.return_value.__exit__ = Mock(return_value=False)
with patch(
- "local_deep_research.web.routes.settings_routes.SettingsManager"
- ) as mock_sm:
+ "local_deep_research.web.warning_checks.get_settings_manager"
+ ) as mock_gsm:
mock_instance = MagicMock()
mock_instance.get_setting.return_value = "test"
- mock_sm.return_value = mock_instance
+ mock_gsm.return_value = mock_instance
with patch(
- "local_deep_research.web.routes.settings_routes.session",
+ "local_deep_research.web.warning_checks.session",
{"username": "testuser"},
):
result = calculate_warnings()
@@ -803,20 +801,18 @@ class TestCalculateWarningsExtended:
def test_calculate_warnings_with_various_settings(self):
"""Test calculate_warnings with various settings."""
- from local_deep_research.web.routes.settings_routes import (
- calculate_warnings,
- )
+ from local_deep_research.web.warning_checks import calculate_warnings
with patch(
- "local_deep_research.web.routes.settings_routes.get_user_db_session"
+ "local_deep_research.web.warning_checks.get_user_db_session"
) as mock_session:
mock_ctx = MagicMock()
mock_session.return_value.__enter__ = Mock(return_value=mock_ctx)
mock_session.return_value.__exit__ = Mock(return_value=False)
with patch(
- "local_deep_research.web.routes.settings_routes.SettingsManager"
- ) as mock_sm:
+ "local_deep_research.web.warning_checks.get_settings_manager"
+ ) as mock_gsm:
mock_instance = MagicMock()
# Simulate various settings that might trigger warnings
mock_instance.get_setting.side_effect = (
@@ -825,10 +821,10 @@ class TestCalculateWarningsExtended:
"search.tool": "", # No search engine
}.get(key, default)
)
- mock_sm.return_value = mock_instance
+ mock_gsm.return_value = mock_instance
with patch(
- "local_deep_research.web.routes.settings_routes.session",
+ "local_deep_research.web.warning_checks.session",
{"username": "testuser"},
):
result = calculate_warnings()
diff --git a/tests/web/warning_checks/__init__.py b/tests/web/warning_checks/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/tests/web/warning_checks/test_context.py b/tests/web/warning_checks/test_context.py
new file mode 100644
index 0000000000..50fac3e3d1
--- /dev/null
+++ b/tests/web/warning_checks/test_context.py
@@ -0,0 +1,166 @@
+"""Tests for DB-backed context warning checks.
+
+Only mock needed: SQLAlchemy session (no Flask dependency).
+"""
+
+from unittest.mock import Mock
+
+from local_deep_research.web.warning_checks.context import (
+ check_context_below_history,
+ check_context_truncation_history,
+)
+
+
+def _mock_db_with_context_records(records, truncation_count=0):
+ """Build a mock db_session that returns *records* for the context query
+ and *truncation_count* for the truncation count query.
+ """
+ db_session = Mock()
+
+ context_query = Mock()
+ context_query.filter.return_value.order_by.return_value.limit.return_value.all.return_value = records
+
+ truncation_query = Mock()
+ truncation_query.filter.return_value.filter.return_value.scalar.return_value = truncation_count
+
+ db_session.query.side_effect = [context_query, truncation_query]
+ return db_session
+
+
+class TestCheckContextBelowHistory:
+ """Tests for check_context_below_history."""
+
+ def test_warns_when_below_historical_min(self):
+ db = _mock_db_with_context_records([(8192,)] * 10)
+ result = check_context_below_history(db, local_context=2048)
+ assert result is not None
+ assert result["type"] == "context_below_history"
+ assert "2,048" in result["message"]
+
+ def test_no_warning_when_at_or_above_historical(self):
+ db = _mock_db_with_context_records([(4096,)] * 10)
+ result = check_context_below_history(db, local_context=4096)
+ assert result is None
+
+ def test_no_warning_fewer_than_5_records(self):
+ db = _mock_db_with_context_records([(8192,)] * 3)
+ result = check_context_below_history(db, local_context=2048)
+ assert result is None
+
+ def test_no_warning_empty_records(self):
+ db = _mock_db_with_context_records([])
+ result = check_context_below_history(db, local_context=2048)
+ assert result is None
+
+ def test_exactly_5_records_is_enough(self):
+ """Boundary: exactly 5 records should be sufficient."""
+ db = _mock_db_with_context_records([(8192,)] * 5)
+ result = check_context_below_history(db, local_context=2048)
+ assert result is not None
+ assert result["type"] == "context_below_history"
+
+ def test_exactly_4_records_not_enough(self):
+ """Boundary: 4 records is below the threshold of 5."""
+ db = _mock_db_with_context_records([(8192,)] * 4)
+ result = check_context_below_history(db, local_context=2048)
+ assert result is None
+
+ def test_none_values_filtered_out(self):
+ """Records with None context_limit are filtered from percentile calc."""
+ # 6 records total but 4 are None → only 2 valid → below threshold
+ records = [(None,)] * 4 + [(8192,)] * 2
+ db = _mock_db_with_context_records(records)
+ result = check_context_below_history(db, local_context=2048)
+ # Only 2 non-None records < 5 threshold, but the query returned 6 rows
+ # so len(recent_contexts) >= 5 passes, but after filtering context_values
+ # has only 2 entries. Still, percentile calc should work on 2 values.
+ # With sorted [8192, 8192], idx=0, min_safe=8192, 2048 < 8192 → warn
+ assert result is not None
+
+ def test_all_none_values_after_filtering(self):
+ """If all records have None/0 context_limit after filtering, no warning."""
+ records = [(None,)] * 5 + [(0,)] * 5
+ db = _mock_db_with_context_records(records)
+ result = check_context_below_history(db, local_context=2048)
+ assert result is None
+
+ def test_mixed_context_values_percentile(self):
+ """With varied values, percentile should pick the 1st percentile."""
+ # 100 records: sorted values [1000, 2000, 2000, ..., 2000, 8000, 8000, ...]
+ records = [(1000,)] * 1 + [(2000,)] * 49 + [(8000,)] * 50
+ db = _mock_db_with_context_records(records)
+ # idx = max(0, int(100 * 0.01)) = 1 → sorted[1] = 2000
+ result = check_context_below_history(db, local_context=1500)
+ assert result is not None
+ assert "1,500" in result["message"]
+
+ def test_mixed_context_values_no_warning_above_percentile(self):
+ """No warning when above the 1st percentile threshold."""
+ records = [(1000,)] * 1 + [(2000,)] * 49 + [(8000,)] * 50
+ db = _mock_db_with_context_records(records)
+ result = check_context_below_history(db, local_context=2000)
+ assert result is None
+
+ def test_min_safe_context_in_message(self):
+ db = _mock_db_with_context_records([(16384,)] * 10)
+ result = check_context_below_history(db, local_context=4096)
+ assert "16,384" in result["message"]
+
+ def test_dismiss_key(self):
+ db = _mock_db_with_context_records([(8192,)] * 10)
+ result = check_context_below_history(db, local_context=2048)
+ assert result["dismissKey"] == "app.warnings.dismiss_context_reduced"
+
+
+class TestCheckContextTruncationHistory:
+ """Tests for check_context_truncation_history."""
+
+ def test_warns_when_truncation_exists(self):
+ db = Mock()
+ db.query.return_value.filter.return_value.filter.return_value.scalar.return_value = 3
+ result = check_context_truncation_history(db, local_context=4096)
+ assert result is not None
+ assert result["type"] == "context_truncation_history"
+ assert "3 time(s)" in result["message"]
+
+ def test_no_warning_zero_truncations(self):
+ db = Mock()
+ db.query.return_value.filter.return_value.filter.return_value.scalar.return_value = 0
+ result = check_context_truncation_history(db, local_context=4096)
+ assert result is None
+
+ def test_no_warning_none_truncations(self):
+ db = Mock()
+ db.query.return_value.filter.return_value.filter.return_value.scalar.return_value = None
+ result = check_context_truncation_history(db, local_context=4096)
+ assert result is None
+
+ def test_single_truncation_message(self):
+ db = Mock()
+ db.query.return_value.filter.return_value.filter.return_value.scalar.return_value = 1
+ result = check_context_truncation_history(db, local_context=4096)
+ assert "1 time(s)" in result["message"]
+
+ def test_large_truncation_count(self):
+ db = Mock()
+ db.query.return_value.filter.return_value.filter.return_value.scalar.return_value = 42
+ result = check_context_truncation_history(db, local_context=4096)
+ assert "42 time(s)" in result["message"]
+
+ def test_warning_dict_has_all_required_keys(self):
+ db = Mock()
+ db.query.return_value.filter.return_value.filter.return_value.scalar.return_value = 1
+ result = check_context_truncation_history(db, local_context=4096)
+ assert set(result.keys()) == {
+ "type",
+ "icon",
+ "title",
+ "message",
+ "dismissKey",
+ }
+
+ def test_dismiss_key(self):
+ db = Mock()
+ db.query.return_value.filter.return_value.filter.return_value.scalar.return_value = 1
+ result = check_context_truncation_history(db, local_context=4096)
+ assert result["dismissKey"] == "app.warnings.dismiss_context_reduced"
diff --git a/tests/web/warning_checks/test_hardware.py b/tests/web/warning_checks/test_hardware.py
new file mode 100644
index 0000000000..dcc9821354
--- /dev/null
+++ b/tests/web/warning_checks/test_hardware.py
@@ -0,0 +1,165 @@
+"""Pure-function tests for hardware warning checks — zero mocking needed."""
+
+from local_deep_research.web.warning_checks.hardware import (
+ LOCAL_PROVIDERS,
+ check_high_context,
+ check_model_mismatch,
+)
+
+
+class TestLocalProviders:
+ """Verify the LOCAL_PROVIDERS constant."""
+
+ def test_contains_expected_providers(self):
+ assert LOCAL_PROVIDERS == frozenset(
+ {"ollama", "llamacpp", "lmstudio", "vllm"}
+ )
+
+ def test_is_frozenset(self):
+ assert isinstance(LOCAL_PROVIDERS, frozenset)
+
+
+class TestCheckHighContext:
+ """Tests for check_high_context."""
+
+ def test_warns_local_provider_above_8192(self):
+ result = check_high_context("ollama", 16384, dismissed=False)
+ assert result is not None
+ assert result["type"] == "high_context"
+ assert "16,384" in result["message"]
+
+ def test_no_warning_at_8192(self):
+ assert check_high_context("ollama", 8192, dismissed=False) is None
+
+ def test_no_warning_below_8192(self):
+ assert check_high_context("ollama", 4096, dismissed=False) is None
+
+ def test_no_warning_non_local_provider(self):
+ assert check_high_context("openai", 32000, dismissed=False) is None
+
+ def test_no_warning_when_dismissed(self):
+ assert check_high_context("ollama", 16384, dismissed=True) is None
+
+ def test_all_local_providers_trigger(self):
+ for provider in LOCAL_PROVIDERS:
+ result = check_high_context(provider, 16384, dismissed=False)
+ assert result is not None, f"{provider} should trigger warning"
+
+ def test_warns_at_boundary_8193(self):
+ """8193 is just above the 8192 threshold — should trigger."""
+ result = check_high_context("ollama", 8193, dismissed=False)
+ assert result is not None
+ assert result["type"] == "high_context"
+
+ def test_provider_name_in_message(self):
+ result = check_high_context("vllm", 16384, dismissed=False)
+ assert "vllm" in result["message"]
+
+ def test_warning_dict_has_all_required_keys(self):
+ result = check_high_context("ollama", 16384, dismissed=False)
+ assert set(result.keys()) == {
+ "type",
+ "icon",
+ "title",
+ "message",
+ "dismissKey",
+ }
+
+ def test_dismiss_key(self):
+ result = check_high_context("ollama", 16384, dismissed=False)
+ assert result["dismissKey"] == "app.warnings.dismiss_high_context"
+
+
+class TestCheckModelMismatch:
+ """Tests for check_model_mismatch."""
+
+ def test_warns_70b_model_high_context(self):
+ result = check_model_mismatch(
+ "ollama", "llama3.1:70b", 16384, dismissed=False
+ )
+ assert result is not None
+ assert result["type"] == "model_mismatch"
+
+ def test_case_insensitive_70b(self):
+ result = check_model_mismatch(
+ "ollama", "Mixtral-70B-v2", 16384, dismissed=False
+ )
+ assert result is not None
+
+ def test_no_warning_small_model(self):
+ result = check_model_mismatch(
+ "ollama", "llama3:8b", 16384, dismissed=False
+ )
+ assert result is None
+
+ def test_no_warning_empty_model(self):
+ result = check_model_mismatch("ollama", "", 16384, dismissed=False)
+ assert result is None
+
+ def test_no_warning_non_local_provider(self):
+ result = check_model_mismatch(
+ "openai", "gpt-4-70b-fake", 16384, dismissed=False
+ )
+ assert result is None
+
+ def test_no_warning_at_boundary_8192(self):
+ """Context exactly at 8192 should NOT trigger (uses <=)."""
+ result = check_model_mismatch(
+ "ollama", "llama3.1:70b", 8192, dismissed=False
+ )
+ assert result is None
+
+ def test_warns_at_boundary_8193(self):
+ """Context at 8193 is just above the threshold — should trigger."""
+ result = check_model_mismatch(
+ "ollama", "llama3.1:70b", 8193, dismissed=False
+ )
+ assert result is not None
+ assert result["type"] == "model_mismatch"
+
+ def test_no_warning_low_context(self):
+ result = check_model_mismatch(
+ "ollama", "llama3.1:70b", 4096, dismissed=False
+ )
+ assert result is None
+
+ def test_no_warning_when_dismissed(self):
+ result = check_model_mismatch(
+ "ollama", "llama3.1:70b", 16384, dismissed=True
+ )
+ assert result is None
+
+ def test_model_name_in_message(self):
+ result = check_model_mismatch(
+ "ollama", "deepseek-r1:70b", 16384, dismissed=False
+ )
+ assert "deepseek-r1:70b" in result["message"]
+
+ def test_context_value_in_message(self):
+ result = check_model_mismatch(
+ "ollama", "llama3.1:70b", 32000, dismissed=False
+ )
+ assert "32,000" in result["message"]
+
+ def test_warning_dict_has_all_required_keys(self):
+ result = check_model_mismatch(
+ "ollama", "llama3.1:70b", 16384, dismissed=False
+ )
+ assert set(result.keys()) == {
+ "type",
+ "icon",
+ "title",
+ "message",
+ "dismissKey",
+ }
+
+ def test_no_warning_none_model(self):
+ """None model should not crash — treated as falsy like empty string."""
+ result = check_model_mismatch("ollama", None, 16384, dismissed=False)
+ assert result is None
+
+ def test_dismiss_key(self):
+ result = check_model_mismatch(
+ "ollama", "llama3.1:70b", 16384, dismissed=False
+ )
+ assert result["dismissKey"] == "app.warnings.dismiss_model_mismatch"
diff --git a/tests/web/warning_checks/test_orchestrator.py b/tests/web/warning_checks/test_orchestrator.py
new file mode 100644
index 0000000000..baaf2dbd59
--- /dev/null
+++ b/tests/web/warning_checks/test_orchestrator.py
@@ -0,0 +1,457 @@
+"""Tests for the calculate_warnings orchestrator (__init__.py).
+
+These test the integration logic: session reading, DB session lifecycle,
+setting dispatch to sub-checks, and error handling.
+"""
+
+from unittest.mock import Mock, patch
+
+
+def _make_settings_manager(overrides=None):
+ """Build a mock SettingsManager with sensible defaults."""
+ defaults = {
+ "llm.provider": "ollama",
+ "llm.local_context_window_size": 4096,
+ "llm.model": "llama3",
+ "app.warnings.dismiss_high_context": False,
+ "app.warnings.dismiss_model_mismatch": False,
+ "app.warnings.dismiss_context_reduced": False,
+ }
+ if overrides:
+ defaults.update(overrides)
+
+ mgr = Mock()
+ mgr.get_setting.side_effect = lambda key, default=None: defaults.get(
+ key, default
+ )
+ return mgr
+
+
+def _patch_orchestrator(settings_manager, db_session=None):
+ """Return a nested context manager that patches session, get_user_db_session,
+ and get_settings_manager for the warnings orchestrator.
+ """
+ if db_session is None:
+ db_session = Mock()
+
+ class _Ctx:
+ def __enter__(self_ctx):
+ self_ctx.p1 = patch(
+ "local_deep_research.web.warning_checks.session",
+ {"username": "test"},
+ )
+ self_ctx.p2 = patch(
+ "local_deep_research.web.warning_checks.get_user_db_session"
+ )
+ self_ctx.p3 = patch(
+ "local_deep_research.web.warning_checks.get_settings_manager",
+ return_value=settings_manager,
+ )
+ self_ctx.p1.start()
+ mock_ctx = self_ctx.p2.start()
+ mock_ctx.return_value.__enter__ = Mock(return_value=db_session)
+ mock_ctx.return_value.__exit__ = Mock(return_value=False)
+ self_ctx.p3.start()
+ return self_ctx
+
+ def __exit__(self_ctx, *args):
+ self_ctx.p3.stop()
+ self_ctx.p2.stop()
+ self_ctx.p1.stop()
+
+ return _Ctx()
+
+
+class TestCalculateWarningsNoDbSession:
+ """Tests for when db_session is None."""
+
+ def test_returns_empty_list_when_db_session_is_none(self):
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ with patch(
+ "local_deep_research.web.warning_checks.session",
+ {"username": "test"},
+ ):
+ with patch(
+ "local_deep_research.web.warning_checks.get_user_db_session"
+ ) as mock_ctx:
+ mock_ctx.return_value.__enter__ = Mock(return_value=None)
+ mock_ctx.return_value.__exit__ = Mock(return_value=False)
+
+ result = calculate_warnings()
+ assert result == []
+
+ def test_returns_empty_list_when_no_username(self):
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ with patch(
+ "local_deep_research.web.warning_checks.session",
+ {},
+ ):
+ with patch(
+ "local_deep_research.web.warning_checks.get_user_db_session"
+ ) as mock_ctx:
+ mock_ctx.return_value.__enter__ = Mock(return_value=None)
+ mock_ctx.return_value.__exit__ = Mock(return_value=False)
+
+ result = calculate_warnings()
+ assert result == []
+
+
+class TestCalculateWarningsErrorHandling:
+ """Tests for exception handling."""
+
+ def test_returns_empty_list_on_exception(self):
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ with patch(
+ "local_deep_research.web.warning_checks.session",
+ {"username": "test"},
+ ):
+ with patch(
+ "local_deep_research.web.warning_checks.get_user_db_session",
+ side_effect=RuntimeError("DB exploded"),
+ ):
+ result = calculate_warnings()
+ assert result == []
+
+ def test_returns_empty_list_on_settings_manager_error(self):
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ with patch(
+ "local_deep_research.web.warning_checks.session",
+ {"username": "test"},
+ ):
+ with patch(
+ "local_deep_research.web.warning_checks.get_user_db_session"
+ ) as mock_ctx:
+ mock_ctx.return_value.__enter__ = Mock(return_value=Mock())
+ mock_ctx.return_value.__exit__ = Mock(return_value=False)
+
+ with patch(
+ "local_deep_research.web.warning_checks.get_settings_manager",
+ side_effect=ValueError("bad settings"),
+ ):
+ result = calculate_warnings()
+ assert result == []
+
+
+class TestCalculateWarningsProviderNormalization:
+ """Provider string is lowercased before checks."""
+
+ def test_uppercase_provider_is_normalized(self):
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ mgr = _make_settings_manager(
+ {
+ "llm.provider": "OLLAMA",
+ "llm.local_context_window_size": 16384,
+ }
+ )
+ with _patch_orchestrator(mgr):
+ warnings = calculate_warnings()
+ assert any(w["type"] == "high_context" for w in warnings)
+
+
+class TestCalculateWarningsContextCheckGating:
+ """Context checks are gated on is_local AND not dismissed."""
+
+ def test_context_checks_skipped_for_non_local_provider(self):
+ """Non-local provider should never trigger context history checks,
+ even when context is low and history would normally warn."""
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ mock_db_session = Mock()
+
+ mgr = _make_settings_manager(
+ {
+ "llm.provider": "openai",
+ "llm.local_context_window_size": 2048,
+ "app.warnings.dismiss_context_reduced": False,
+ }
+ )
+ with _patch_orchestrator(mgr, db_session=mock_db_session):
+ warnings = calculate_warnings()
+
+ # DB should not have been queried for context history at all
+ mock_db_session.query.assert_not_called()
+ assert not any(w["type"] == "context_below_history" for w in warnings)
+ assert not any(
+ w["type"] == "context_truncation_history" for w in warnings
+ )
+
+ def test_context_checks_skipped_when_dismissed(self):
+ """Local provider with dismiss_context_reduced=True should skip DB queries."""
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ mock_db_session = Mock()
+
+ mgr = _make_settings_manager(
+ {
+ "llm.provider": "ollama",
+ "llm.local_context_window_size": 2048,
+ "app.warnings.dismiss_context_reduced": True,
+ }
+ )
+ with _patch_orchestrator(mgr, db_session=mock_db_session):
+ warnings = calculate_warnings()
+
+ mock_db_session.query.assert_not_called()
+ assert not any(w["type"] == "context_below_history" for w in warnings)
+
+
+class TestCalculateWarningsMultipleWarnings:
+ """Multiple warnings can fire simultaneously."""
+
+ def test_high_context_and_model_mismatch_together(self):
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ mgr = _make_settings_manager(
+ {
+ "llm.provider": "ollama",
+ "llm.local_context_window_size": 16384,
+ "llm.model": "llama3.1:70b",
+ }
+ )
+ with _patch_orchestrator(mgr):
+ warnings = calculate_warnings()
+
+ types = {w["type"] for w in warnings}
+ assert "high_context" in types
+ assert "model_mismatch" in types
+
+ def test_high_context_and_context_history_together(self):
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ mock_db_session = Mock()
+
+ # DB queries for context history
+ context_query = Mock()
+ context_query.filter.return_value.order_by.return_value.limit.return_value.all.return_value = (
+ [(32768,)] * 10
+ )
+
+ truncation_query = Mock()
+ truncation_query.filter.return_value.filter.return_value.scalar.return_value = 5
+
+ mock_db_session.query.side_effect = [context_query, truncation_query]
+
+ mgr = _make_settings_manager(
+ {
+ "llm.provider": "ollama",
+ "llm.local_context_window_size": 16384,
+ }
+ )
+ with _patch_orchestrator(mgr, db_session=mock_db_session):
+ warnings = calculate_warnings()
+
+ types = {w["type"] for w in warnings}
+ assert "high_context" in types
+ assert "context_below_history" in types
+ assert "context_truncation_history" in types
+
+ def test_all_four_warnings_simultaneously(self):
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ mock_db_session = Mock()
+
+ context_query = Mock()
+ context_query.filter.return_value.order_by.return_value.limit.return_value.all.return_value = (
+ [(32768,)] * 10
+ )
+
+ truncation_query = Mock()
+ truncation_query.filter.return_value.filter.return_value.scalar.return_value = 2
+
+ mock_db_session.query.side_effect = [context_query, truncation_query]
+
+ mgr = _make_settings_manager(
+ {
+ "llm.provider": "ollama",
+ "llm.local_context_window_size": 16384,
+ "llm.model": "llama3.1:70b",
+ }
+ )
+ with _patch_orchestrator(mgr, db_session=mock_db_session):
+ warnings = calculate_warnings()
+
+ types = {w["type"] for w in warnings}
+ assert types == {
+ "high_context",
+ "model_mismatch",
+ "context_below_history",
+ "context_truncation_history",
+ }
+
+
+class TestCalculateWarningsSingleSession:
+ """Verify all settings are read from a single DB session."""
+
+ def test_get_user_db_session_called_once(self):
+ """The orchestrator should open exactly one DB session."""
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ mgr = _make_settings_manager()
+
+ with patch(
+ "local_deep_research.web.warning_checks.session",
+ {"username": "test"},
+ ):
+ with patch(
+ "local_deep_research.web.warning_checks.get_user_db_session"
+ ) as mock_ctx:
+ mock_ctx.return_value.__enter__ = Mock(return_value=Mock())
+ mock_ctx.return_value.__exit__ = Mock(return_value=False)
+
+ with patch(
+ "local_deep_research.web.warning_checks.get_settings_manager",
+ return_value=mgr,
+ ):
+ calculate_warnings()
+
+ # Should be called exactly once (the whole point of the refactor)
+ assert mock_ctx.call_count == 1
+
+ def test_get_user_db_session_called_with_username(self):
+ """Verify username from session is passed to get_user_db_session."""
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ mgr = _make_settings_manager()
+
+ with patch(
+ "local_deep_research.web.warning_checks.session",
+ {"username": "alice"},
+ ):
+ with patch(
+ "local_deep_research.web.warning_checks.get_user_db_session"
+ ) as mock_get_db:
+ mock_get_db.return_value.__enter__ = Mock(return_value=Mock())
+ mock_get_db.return_value.__exit__ = Mock(return_value=False)
+
+ with patch(
+ "local_deep_research.web.warning_checks.get_settings_manager",
+ return_value=mgr,
+ ):
+ calculate_warnings()
+
+ mock_get_db.assert_called_once_with("alice")
+
+ def test_get_settings_manager_called_with_session_and_username(self):
+ """Verify both db_session and username are passed to get_settings_manager."""
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ mgr = _make_settings_manager()
+ mock_db = Mock()
+
+ with patch(
+ "local_deep_research.web.warning_checks.session",
+ {"username": "bob"},
+ ):
+ with patch(
+ "local_deep_research.web.warning_checks.get_user_db_session"
+ ) as mock_get_db:
+ mock_get_db.return_value.__enter__ = Mock(return_value=mock_db)
+ mock_get_db.return_value.__exit__ = Mock(return_value=False)
+
+ with patch(
+ "local_deep_research.web.warning_checks.get_settings_manager",
+ return_value=mgr,
+ ) as mock_get_sm:
+ calculate_warnings()
+
+ mock_get_sm.assert_called_once_with(mock_db, "bob")
+
+ def test_all_six_settings_read(self):
+ """All 6 required settings are read from the manager."""
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ mgr = _make_settings_manager()
+
+ with _patch_orchestrator(mgr):
+ calculate_warnings()
+
+ called_keys = [call.args[0] for call in mgr.get_setting.call_args_list]
+ assert "llm.provider" in called_keys
+ assert "llm.local_context_window_size" in called_keys
+ assert "llm.model" in called_keys
+ assert "app.warnings.dismiss_high_context" in called_keys
+ assert "app.warnings.dismiss_model_mismatch" in called_keys
+ assert "app.warnings.dismiss_context_reduced" in called_keys
+
+
+class TestCalculateWarningsFailureIsolation:
+ """Verify _safe_check isolates individual check failures."""
+
+ def test_first_check_crash_does_not_kill_second(self):
+ """If check_high_context raises, check_model_mismatch still runs."""
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ mgr = _make_settings_manager(
+ {
+ "llm.provider": "ollama",
+ "llm.local_context_window_size": 16384,
+ "llm.model": "llama3.1:70b",
+ }
+ )
+ with _patch_orchestrator(mgr):
+ with patch(
+ "local_deep_research.web.warning_checks.check_high_context",
+ side_effect=RuntimeError("boom"),
+ ):
+ warnings = calculate_warnings()
+
+ types = {w["type"] for w in warnings}
+ assert "high_context" not in types
+ assert "model_mismatch" in types
+
+ def test_context_check_crash_does_not_kill_other_context_check(self):
+ """If check_context_below_history raises, check_context_truncation_history still runs."""
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ mock_db_session = Mock()
+
+ truncation_query = Mock()
+ truncation_query.filter.return_value.filter.return_value.scalar.return_value = 3
+
+ mock_db_session.query.return_value = truncation_query
+
+ mgr = _make_settings_manager(
+ {
+ "llm.provider": "ollama",
+ "llm.local_context_window_size": 4096,
+ }
+ )
+ with _patch_orchestrator(mgr, db_session=mock_db_session):
+ with patch(
+ "local_deep_research.web.warning_checks.check_context_below_history",
+ side_effect=RuntimeError("db query failed"),
+ ):
+ warnings = calculate_warnings()
+
+ types = {w["type"] for w in warnings}
+ assert "context_below_history" not in types
+ assert "context_truncation_history" in types
+
+
+class TestCalculateWarningsNoneProvider:
+ """Document behavior when provider setting is None."""
+
+ def test_none_provider_does_not_crash(self):
+ """If get_setting returns None for provider, outer try/except catches the AttributeError."""
+ from local_deep_research.web.warning_checks import calculate_warnings
+
+ mgr = Mock()
+ mgr.get_setting.side_effect = lambda key, default=None: {
+ "llm.provider": None,
+ "llm.local_context_window_size": 4096,
+ "llm.model": "llama3",
+ "app.warnings.dismiss_high_context": False,
+ "app.warnings.dismiss_model_mismatch": False,
+ "app.warnings.dismiss_context_reduced": False,
+ }.get(key, default)
+
+ with _patch_orchestrator(mgr):
+ result = calculate_warnings()
+
+ # Should not crash — outer except catches AttributeError from None.lower()
+ assert isinstance(result, list)