Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix: resolve circular dependency between settings service and routes (#2898)

LearningCircuit8eb23bdc167c
diff --git a/src/local_deep_research/web/routes/research_routes.py b/src/local_deep_research/web/routes/research_routes.py
index 6afe087264..ab41bc8775 100644
--- a/src/local_deep_research/web/routes/research_routes.py
+++ b/src/local_deep_research/web/routes/research_routes.py
@@ -556,7 +556,7 @@ def start_research():
data["metadata"] = metadata
# Get parameters from request or use database settings
- from ...settings.manager import SettingsManager
+ from ...settings import SettingsManager
username = session["username"]
@@ -745,7 +745,7 @@ def start_research():
research_settings.update(additional_metadata)
# Get complete settings snapshot for this research
try:
- from local_deep_research.settings import SettingsManager
+ from ...settings import SettingsManager
# Get or lazily create a session for settings snapshot
db_session_for_settings = get_g_db_session()
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index e007f0e942..f865253fc4 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -40,7 +40,7 @@ optimal experience when JavaScript is available.
import platform
import time
-from typing import Any, Optional, Tuple
+from typing import Any, Optional
from datetime import UTC, datetime, timedelta, timezone
import requests
@@ -79,11 +79,13 @@ from ...settings.manager import (
parse_boolean,
)
from ..services.settings_service import (
+ DYNAMIC_SETTINGS, # noqa: F401 — re-exported for tests that import from routes
create_or_update_setting,
invalidate_settings_caches,
reschedule_document_jobs_if_needed,
reschedule_zotero_jobs_if_needed,
set_setting,
+ validate_setting,
)
from ..utils.route_decorators import with_user_session
from ..utils.templates import render_template_with_defaults
@@ -140,10 +142,6 @@ def _filter_editable_settings(form_data: dict, db_session: Session) -> dict:
# @login_required guarantees the key exists; direct access fails fast
# if the decorator is ever removed.
-# Settings with dynamically populated options (excluded from validation)
-DYNAMIC_SETTINGS = ["llm.provider", "llm.model", "search.tool"]
-
-
# Namespace validation for new setting creation via the web API.
# Keys starting with any ALLOWED prefix may be created; any prefix in
# BLOCKED takes precedence and is rejected even if it also matches an
@@ -289,64 +287,6 @@ def _model_list_local_only() -> bool:
return False
-def validate_setting(
- setting: Setting, value: Any
-) -> Tuple[bool, Optional[str]]:
- """
- Validate a setting value based on its type and constraints.
-
- Args:
- setting: The Setting object to validate against
- value: The value to validate
-
- Returns:
- Tuple of (is_valid, error_message)
- """
- # Convert value to appropriate type first using SettingsManager's logic
- value = get_typed_setting_value(
- key=str(setting.key),
- value=value,
- ui_element=str(setting.ui_element),
- default=None,
- check_env=False,
- )
-
- # Validate based on UI element type
- if setting.ui_element == "checkbox":
- # After conversion, should be boolean
- if not isinstance(value, bool):
- return False, "Value must be a boolean"
-
- elif setting.ui_element in ("number", "slider", "range"):
- # After conversion, should be numeric
- if not isinstance(value, (int, float)):
- return False, "Value must be a number"
-
- # Check min/max constraints if defined
- if setting.min_value is not None and value < setting.min_value:
- return False, f"Value must be at least {setting.min_value}"
- if setting.max_value is not None and value > setting.max_value:
- return False, f"Value must be at most {setting.max_value}"
-
- elif setting.ui_element == "select":
- # Check if value is in the allowed options
- if setting.options:
- # Skip options validation for dynamically populated dropdowns
- if setting.key not in DYNAMIC_SETTINGS:
- allowed_values = [
- opt.get("value") if isinstance(opt, dict) else opt
- for opt in list(setting.options) # type: ignore[arg-type]
- ]
- if value not in allowed_values:
- return (
- False,
- f"Value must be one of: {', '.join(str(v) for v in allowed_values)}",
- )
-
- # All checks passed
- return True, None
-
-
def coerce_setting_for_write(key: str, value: Any, ui_element: str) -> Any:
"""Coerce an incoming value to the correct type before writing to the DB.
diff --git a/src/local_deep_research/web/services/settings_service.py b/src/local_deep_research/web/services/settings_service.py
index 46bb7cd503..b2a2d983eb 100644
--- a/src/local_deep_research/web/services/settings_service.py
+++ b/src/local_deep_research/web/services/settings_service.py
@@ -4,8 +4,12 @@ from loguru import logger
from sqlalchemy.orm import Session
from ...database.models import Setting
+from ...settings.manager import get_typed_setting_value
from ...utilities.db_utils import get_settings_manager
+# Settings with dynamically populated options (excluded from validation)
+DYNAMIC_SETTINGS = ["llm.provider", "llm.model", "search.tool"]
+
def set_setting(
key: str,
@@ -163,7 +167,7 @@ def validate_setting(
setting: Setting, value: Any
) -> tuple[bool, Optional[str]]:
"""
- Validate a setting value based on its type and constraints
+ Validate a setting value based on its type and constraints.
Args:
setting: The Setting object to validate against
@@ -172,8 +176,46 @@ def validate_setting(
Returns:
tuple[bool, Optional[str]]: (is_valid, error_message)
"""
- from ..routes.settings_routes import (
- validate_setting as routes_validate_setting,
+ # Convert value to appropriate type first using SettingsManager's logic
+ value = get_typed_setting_value(
+ key=str(setting.key),
+ value=value,
+ ui_element=str(setting.ui_element),
+ default=None,
+ check_env=False,
)
- return routes_validate_setting(setting, value)
+ # Validate based on UI element type
+ if setting.ui_element == "checkbox":
+ # After conversion, should be boolean
+ if not isinstance(value, bool):
+ return False, "Value must be a boolean"
+
+ elif setting.ui_element in ("number", "slider", "range"):
+ # After conversion, should be numeric
+ if not isinstance(value, (int, float)):
+ return False, "Value must be a number"
+
+ # Check min/max constraints if defined
+ if setting.min_value is not None and value < setting.min_value:
+ return False, f"Value must be at least {setting.min_value}"
+ if setting.max_value is not None and value > setting.max_value:
+ return False, f"Value must be at most {setting.max_value}"
+
+ elif setting.ui_element == "select":
+ # Check if value is in the allowed options
+ if setting.options:
+ # Skip options validation for dynamically populated dropdowns
+ if setting.key not in DYNAMIC_SETTINGS:
+ allowed_values = [
+ opt.get("value") if isinstance(opt, dict) else opt
+ for opt in list(setting.options)
+ ]
+ if value not in allowed_values:
+ return (
+ False,
+ f"Value must be one of: {', '.join(str(v) for v in allowed_values)}",
+ )
+
+ # All checks passed
+ return True, None
diff --git a/tests/routes/test_settings_routes.py b/tests/routes/test_settings_routes.py
index 1aa526e91b..eed4828cea 100644
--- a/tests/routes/test_settings_routes.py
+++ b/tests/routes/test_settings_routes.py
@@ -58,7 +58,7 @@ class TestValidateSetting:
mock_setting.ui_element = "checkbox"
with patch(
- "local_deep_research.web.routes.settings_routes.get_typed_setting_value",
+ "local_deep_research.web.services.settings_service.get_typed_setting_value",
return_value=True,
):
is_valid, error = validate_setting(mock_setting, True)
@@ -76,7 +76,7 @@ class TestValidateSetting:
mock_setting.ui_element = "checkbox"
with patch(
- "local_deep_research.web.routes.settings_routes.get_typed_setting_value",
+ "local_deep_research.web.services.settings_service.get_typed_setting_value",
return_value=False,
):
is_valid, error = validate_setting(mock_setting, False)
@@ -96,7 +96,7 @@ class TestValidateSetting:
mock_setting.max_value = 100
with patch(
- "local_deep_research.web.routes.settings_routes.get_typed_setting_value",
+ "local_deep_research.web.services.settings_service.get_typed_setting_value",
return_value=50,
):
is_valid, error = validate_setting(mock_setting, 50)
@@ -116,7 +116,7 @@ class TestValidateSetting:
mock_setting.max_value = 100
with patch(
- "local_deep_research.web.routes.settings_routes.get_typed_setting_value",
+ "local_deep_research.web.services.settings_service.get_typed_setting_value",
return_value=5,
):
is_valid, error = validate_setting(mock_setting, 5)
@@ -136,7 +136,7 @@ class TestValidateSetting:
mock_setting.max_value = 100
with patch(
- "local_deep_research.web.routes.settings_routes.get_typed_setting_value",
+ "local_deep_research.web.services.settings_service.get_typed_setting_value",
return_value=200,
):
is_valid, error = validate_setting(mock_setting, 200)
@@ -159,7 +159,7 @@ class TestValidateSetting:
]
with patch(
- "local_deep_research.web.routes.settings_routes.get_typed_setting_value",
+ "local_deep_research.web.services.settings_service.get_typed_setting_value",
return_value="option2",
):
is_valid, error = validate_setting(mock_setting, "option2")
@@ -178,7 +178,7 @@ class TestValidateSetting:
mock_setting.options = [{"value": "option1"}, {"value": "option2"}]
with patch(
- "local_deep_research.web.routes.settings_routes.get_typed_setting_value",
+ "local_deep_research.web.services.settings_service.get_typed_setting_value",
return_value="invalid",
):
is_valid, error = validate_setting(mock_setting, "invalid")
@@ -197,7 +197,7 @@ class TestValidateSetting:
mock_setting.options = [{"value": "old_model"}]
with patch(
- "local_deep_research.web.routes.settings_routes.get_typed_setting_value",
+ "local_deep_research.web.services.settings_service.get_typed_setting_value",
return_value="new_model",
):
is_valid, error = validate_setting(mock_setting, "new_model")
@@ -815,7 +815,7 @@ class TestValidationIntegration:
mock_setting.max_value = 1
with patch(
- "local_deep_research.web.routes.settings_routes.get_typed_setting_value",
+ "local_deep_research.web.services.settings_service.get_typed_setting_value",
return_value=0.5,
):
is_valid, error = validate_setting(mock_setting, 0.5)
@@ -834,7 +834,7 @@ class TestValidationIntegration:
mock_setting.max_value = 10
with patch(
- "local_deep_research.web.routes.settings_routes.get_typed_setting_value",
+ "local_deep_research.web.services.settings_service.get_typed_setting_value",
return_value=5,
):
is_valid, error = validate_setting(mock_setting, 5)
diff --git a/tests/test_settings_service_no_import_cycle.py b/tests/test_settings_service_no_import_cycle.py
new file mode 100644
index 0000000000..8456894ff9
--- /dev/null
+++ b/tests/test_settings_service_no_import_cycle.py
@@ -0,0 +1,123 @@
+# allow: no-sut-import — imports the SUT inside isolated subprocess probes so import order is tested in a fresh interpreter (in-process imports would mask the cycle)
+"""Regression tests for import-order parity between the settings service and
+settings routes modules.
+
+The service module must be importable on its own without pulling in the routes
+module, and importing routes afterward must bind the same function/object
+identities regardless of import order. Each probe runs in a fresh subprocess
+(via sys.executable) so that module-level state from the test process cannot
+mask a cycle.
+"""
+
+import subprocess
+import sys
+import textwrap
+
+
+def _run_probe(script):
+ """Run an import probe in a fresh interpreter; return its stdout text.
+
+ The probe must exit zero and print key=value markers on stdout. Any
+ non-zero exit (including ImportError) is reported with full diagnostics.
+ """
+ result = subprocess.run(
+ [sys.executable, "-c", textwrap.dedent(script)],
+ capture_output=True,
+ text=True,
+ timeout=60,
+ check=False,
+ )
+ assert result.returncode == 0, (
+ "import probe exited with code {code}.\n"
+ "STDOUT:\n{stdout}\n"
+ "STDERR:\n{stderr}\n".format(
+ code=result.returncode,
+ stdout=result.stdout,
+ stderr=result.stderr,
+ )
+ )
+ return result.stdout
+
+
+def _parse_markers(stdout):
+ """Parse key=value lines from probe stdout into a dict."""
+ return dict(
+ line.split("=", 1)
+ for line in stdout.splitlines()
+ if "=" in line and not line.startswith(" ")
+ )
+
+
+def test_service_first_does_not_import_routes():
+ """Importing the service alone must not load the routes module.
+
+ After importing the service, routes must be absent from sys.modules; only
+ then do we import routes and assert both re-exported symbols are the very
+ same objects (identity, not equality).
+ """
+ stdout = _run_probe(
+ """
+ import sys
+
+ from local_deep_research.web.services import settings_service
+
+ routes_key = "local_deep_research.web.routes.settings_routes"
+ print("ROUTES_PRESENT=" + ("yes" if routes_key in sys.modules else "no"))
+
+ from local_deep_research.web.routes import settings_routes as routes
+
+ same_validate = (
+ routes.validate_setting is settings_service.validate_setting
+ )
+ same_dynamic = (
+ routes.DYNAMIC_SETTINGS is settings_service.DYNAMIC_SETTINGS
+ )
+ print("IDENTITY_VALIDATE=" + ("same" if same_validate else "different"))
+ print("IDENTITY_DYNAMIC=" + ("same" if same_dynamic else "different"))
+ """,
+ )
+ markers = _parse_markers(stdout)
+ assert markers.get("ROUTES_PRESENT") == "no", (
+ "routes module was imported as a side effect of importing the "
+ "service module.\nProbe stdout:\n" + stdout
+ )
+ assert markers.get("IDENTITY_VALIDATE") == "same", (
+ "validate_setting identity differs across import order.\n"
+ "Probe stdout:\n" + stdout
+ )
+ assert markers.get("IDENTITY_DYNAMIC") == "same", (
+ "DYNAMIC_SETTINGS identity differs across import order.\n"
+ "Probe stdout:\n" + stdout
+ )
+
+
+def test_routes_first_binds_same_identities():
+ """Importing routes first must still bind identical service objects.
+
+ Routes imports the service at module load; both re-exported symbols must be
+ the exact same objects as the ones in the service module.
+ """
+ stdout = _run_probe(
+ """
+ from local_deep_research.web.routes import settings_routes as routes
+ from local_deep_research.web.services import settings_service
+
+ same_validate = (
+ routes.validate_setting is settings_service.validate_setting
+ )
+ same_dynamic = (
+ routes.DYNAMIC_SETTINGS is settings_service.DYNAMIC_SETTINGS
+ )
+ print("IDENTITY_VALIDATE=" + ("same" if same_validate else "different"))
+ print("IDENTITY_DYNAMIC=" + ("same" if same_dynamic else "different"))
+ """,
+ )
+ markers = _parse_markers(stdout)
+ assert markers.get("IDENTITY_VALIDATE") == "same", (
+ "validate_setting identity differs when routes is imported first.\n"
+ "Probe stdout:\n" + stdout
+ )
+ assert markers.get("IDENTITY_DYNAMIC") == "same", (
+ "DYNAMIC_SETTINGS identity differs when routes is imported first.\n"
+ "Probe stdout:\n" + stdout
+ )
diff --git a/tests/web/routes/test_settings_routes_save_validation_coverage.py b/tests/web/routes/test_settings_routes_save_validation_coverage.py
index 374b21fac1..a8362e67fa 100644
--- a/tests/web/routes/test_settings_routes_save_validation_coverage.py
+++ b/tests/web/routes/test_settings_routes_save_validation_coverage.py
@@ -21,6 +21,7 @@ from ._settings_route_helpers import _create_test_app, _make_setting
# ---------------------------------------------------------------------------
MODULE = "local_deep_research.web.routes.settings_routes"
+SETTINGS_SERVICE_MODULE = "local_deep_research.web.services.settings_service"
DECORATOR_MODULE = "local_deep_research.web.utils.route_decorators"
SETTINGS_PREFIX = "/settings"
@@ -47,10 +48,11 @@ class TestValidateCheckboxNonBoolean:
setting = _make_setting(key="app.flag", ui_element="checkbox")
- # Patch get_typed_setting_value so that it returns a non-bool value,
- # exercising the ``not isinstance(value, bool)`` guard in validate_setting.
+ # Patch the service module: validate_setting resolves get_typed_setting_value
+ # there, not via the route alias.
with patch(
- f"{MODULE}.get_typed_setting_value", return_value="still-a-string"
+ f"{SETTINGS_SERVICE_MODULE}.get_typed_setting_value",
+ return_value="still-a-string",
):
is_valid, message = validate_setting(setting, "not_a_bool")
diff --git a/tests/web/routes/test_settings_validation_edge_cases.py b/tests/web/routes/test_settings_validation_edge_cases.py
index 1f72cf9a85..d14e649066 100644
--- a/tests/web/routes/test_settings_validation_edge_cases.py
+++ b/tests/web/routes/test_settings_validation_edge_cases.py
@@ -74,7 +74,7 @@ class TestValidateSettingMinMax:
"""
setting = _make_setting("slider", min_value=5)
with patch(
- "local_deep_research.web.routes.settings_routes.get_typed_setting_value",
+ "local_deep_research.web.services.settings_service.get_typed_setting_value",
return_value=2,
):
valid, msg = validate_setting(setting, 2)
@@ -118,7 +118,7 @@ class TestValidateSettingSelect:
# Patch get_typed_setting_value to pass through the value unchanged
with patch(
- "local_deep_research.web.routes.settings_routes.get_typed_setting_value",
+ "local_deep_research.web.services.settings_service.get_typed_setting_value",
return_value="b",
):
valid, msg = validate_setting(setting, "b")
diff --git a/tests/web/services/test_settings_service.py b/tests/web/services/test_settings_service.py
index 9dddb1d62d..e63a1aa586 100644
--- a/tests/web/services/test_settings_service.py
+++ b/tests/web/services/test_settings_service.py
@@ -200,30 +200,35 @@ class TestCreateOrUpdateSetting:
class TestValidateSetting:
"""Tests for validate_setting function."""
- def test_validate_setting_calls_routes_validate(self):
- """Test that validate_setting calls routes validate."""
+ def test_validate_setting_valid_text(self):
+ """Test that validate_setting accepts valid text values."""
mock_setting = Mock()
- mock_value = "test_value"
+ mock_setting.key = "some.text.setting"
+ mock_setting.ui_element = "text"
with patch(
- "local_deep_research.web.routes.settings_routes.validate_setting",
- return_value=(True, None),
+ "local_deep_research.web.services.settings_service.get_typed_setting_value",
+ return_value="test_value",
):
from local_deep_research.web.services.settings_service import (
validate_setting,
)
- result = validate_setting(mock_setting, mock_value)
+ result = validate_setting(mock_setting, "test_value")
assert result == (True, None)
- def test_validate_setting_invalid(self):
- """Test validation failure."""
+ def test_validate_setting_invalid_number(self):
+ """Test validation failure for number out of range."""
mock_setting = Mock()
+ mock_setting.key = "some.number.setting"
+ mock_setting.ui_element = "number"
+ mock_setting.min_value = 0
+ mock_setting.max_value = 100
with patch(
- "local_deep_research.web.routes.settings_routes.validate_setting",
- return_value=(False, "Value out of range"),
+ "local_deep_research.web.services.settings_service.get_typed_setting_value",
+ return_value=-1,
):
from local_deep_research.web.services.settings_service import (
validate_setting,
diff --git a/tests/web/services/test_settings_validation_parity.py b/tests/web/services/test_settings_validation_parity.py
new file mode 100644
index 0000000000..cb52ad9c5e
--- /dev/null
+++ b/tests/web/services/test_settings_validation_parity.py
@@ -0,0 +1,99 @@
+"""Parity tests for validate_setting argument handling.
+
+Pins two contracts:
+- converter metadata (setting.key, setting.ui_element) is normalized to str
+ before reaching get_typed_setting_value, while value/default/check_env are
+ passed through untouched;
+- setting.options is materialized via list() before iteration.
+"""
+
+from unittest.mock import Mock, patch
+
+
+def test_converter_metadata_is_stringified():
+ """key/ui_element reach the converter as str; value/default/check_env do not."""
+ from local_deep_research.web.services.settings_service import (
+ validate_setting,
+ )
+
+ class _StrSentinel:
+ def __init__(self, label):
+ self.label = label
+
+ def __str__(self):
+ return "str:" + self.label
+
+ key_sentinel = _StrSentinel("key")
+ ui_sentinel = _StrSentinel("ui")
+ value_sentinel = _StrSentinel("value")
+
+ captured = {}
+
+ def recorder(**kwargs):
+ captured.update(kwargs)
+ return "typed_value"
+
+ mock_setting = Mock()
+ mock_setting.key = key_sentinel
+ mock_setting.ui_element = ui_sentinel
+
+ with patch(
+ "local_deep_research.web.services.settings_service.get_typed_setting_value",
+ side_effect=recorder,
+ ):
+ is_valid, error = validate_setting(mock_setting, value_sentinel)
+
+ assert is_valid is True
+ assert error is None
+ assert captured["key"] == "str:key"
+ assert isinstance(captured["key"], str)
+ assert captured["ui_element"] == "str:ui"
+ assert isinstance(captured["ui_element"], str)
+ assert captured["value"] is value_sentinel
+ assert captured["default"] is None
+ assert captured["check_env"] is False
+
+
+def test_select_options_are_materialized_with_list():
+ """setting.options is passed through list() before being iterated."""
+ from local_deep_research.web.services.settings_service import (
+ validate_setting,
+ )
+
+ real_list = list
+ calls_on_spy = []
+
+ class _OptionsSpy:
+ def __iter__(self):
+ return iter([{"value": "a"}, {"value": "b"}])
+
+ options_spy = _OptionsSpy()
+
+ def tracking_list(iterable=()):
+ if iterable is options_spy:
+ calls_on_spy.append(iterable)
+ return real_list(iterable)
+
+ mock_setting = Mock()
+ mock_setting.key = "some.select.setting"
+ mock_setting.ui_element = "select"
+ mock_setting.options = options_spy
+ mock_setting.min_value = None
+ mock_setting.max_value = None
+
+ with (
+ patch(
+ "local_deep_research.web.services.settings_service.get_typed_setting_value",
+ return_value="a",
+ ),
+ patch(
+ "local_deep_research.web.services.settings_service.list",
+ tracking_list,
+ create=True,
+ ),
+ ):
+ is_valid, error = validate_setting(mock_setting, "a")
+
+ assert is_valid is True
+ assert error is None
+ assert len(calls_on_spy) == 1