~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
refactor: remove fallback LLM (FakeListChatModel) from all providers (#2717)
LearningCircuit9988f703188a
diff --git a/.github/workflows/docker-tests.yml b/.github/workflows/docker-tests.ymlindex 9e043f40f5..051050f047 100644--- a/.github/workflows/docker-tests.yml+++ b/.github/workflows/docker-tests.yml@@ -174,7 +174,6 @@ jobs:-v "$PWD":/app \-e CI=true \-e GITHUB_ACTIONS=true \- -e LDR_USE_FALLBACK_LLM=true \-e LDR_TESTING_WITH_MOCKS=true \-e DISABLE_RATE_LIMITING=true \-e PYTHONPATH=/app/src \@@ -517,7 +516,6 @@ jobs:-e CI=true \-e TEST_ENV=true \-e FLASK_ENV=testing \- -e LDR_USE_FALLBACK_LLM=true \-e DISABLE_RATE_LIMITING=true \-e SECRET_KEY=test-secret-key-for-ci \-e LDR_DATA_DIR=/data \@@ -563,7 +561,6 @@ jobs:run: |docker run --rm \-v "$PWD":/app \- -e LDR_USE_FALLBACK_LLM=true \-e CI=true \-e PUPPETEER_HEADLESS=true \-e LDR_DB_KDF_ITERATIONS=1000 \@@ -638,7 +635,6 @@ jobs:-e CI=true \-e TEST_ENV=true \-e FLASK_ENV=testing \- -e LDR_USE_FALLBACK_LLM=true \-e DISABLE_RATE_LIMITING=true \-e SECRET_KEY=test-secret-key-for-ci \-e LDR_DATA_DIR=/data \@@ -776,7 +772,6 @@ jobs:docker run --rm \-v "$PWD":/app \-e PYTHONPATH=/app \- -e LDR_USE_FALLBACK_LLM=true \-w /app \${{ env.TEST_IMAGE }} \sh -c "python -m pytest tests/test_llm/test_llm_integration.py -v -n auto"@@ -786,7 +781,6 @@ jobs:docker run --rm \-v "$PWD":/app \-e PYTHONPATH=/app \- -e LDR_USE_FALLBACK_LLM=true \-w /app \${{ env.TEST_IMAGE }} \sh -c "python -m pytest tests/test_llm/test_api_llm_integration.py -v -n auto"@@ -842,7 +836,6 @@ jobs:docker run --rm \-v "$PWD":/app \-e PYTHONPATH=/app \- -e LDR_USE_FALLBACK_LLM=true \-w /app \${{ env.TEST_IMAGE }} \sh -c "timeout 60s python examples/llm_integration/basic_custom_llm.py || true"@@ -852,7 +845,6 @@ jobs:docker run --rm \-v "$PWD":/app \-e PYTHONPATH=/app \- -e LDR_USE_FALLBACK_LLM=true \-w /app \${{ env.TEST_IMAGE }} \sh -c "timeout 60s python examples/llm_integration/mock_llm_example.py || true"@@ -862,7 +854,6 @@ jobs:docker run --rm \-v "$PWD":/app \-e PYTHONPATH=/app \- -e LDR_USE_FALLBACK_LLM=true \-w /app \${{ env.TEST_IMAGE }} \sh -c "timeout 60s python examples/llm_integration/switch_providers.py || true"@@ -872,7 +863,6 @@ jobs:docker run --rm \-v "$PWD":/app \-e PYTHONPATH=/app \- -e LDR_USE_FALLBACK_LLM=true \-w /app \${{ env.TEST_IMAGE }} \sh -c "timeout 60s python examples/llm_integration/custom_research_example.py || true"@@ -985,7 +975,6 @@ jobs:--cap-add SETUID \--cap-add SETGID \-e LDR_DATA_DIR=/data \- -e LDR_USE_FALLBACK_LLM=true \-e DISABLE_RATE_LIMITING=true \-e SECRET_KEY=test-secret-key-for-ci \ldr-proddiff --git a/.github/workflows/mcp-tests.yml b/.github/workflows/mcp-tests.ymlindex 1a150ec3fc..581ca2185f 100644--- a/.github/workflows/mcp-tests.yml+++ b/.github/workflows/mcp-tests.yml@@ -71,7 +71,6 @@ jobs:pdm run pytest tests/mcp/ -v --tb=short -n auto \--ignore=tests/mcp/test_mcp_strategy.pyenv:- LDR_USE_FALLBACK_LLM: "true"LDR_TESTING_WITH_MOCKS: "true"- name: Run MCP strategy tests@@ -79,7 +78,6 @@ jobs:run: |pdm run pytest tests/mcp/test_mcp_strategy.py -v --tb=short -n autoenv:- LDR_USE_FALLBACK_LLM: "true"LDR_TESTING_WITH_MOCKS: "true"- name: Skip noticediff --git a/.github/workflows/nuclei.yml b/.github/workflows/nuclei.ymlindex 8c6bf21a8b..db1a0a62cc 100644--- a/.github/workflows/nuclei.yml+++ b/.github/workflows/nuclei.yml@@ -52,7 +52,6 @@ jobs:- name: Start LDR server for testingrun: |export CI=true- export LDR_USE_FALLBACK_LLM=trueexport LDR_DB_KDF_ITERATIONS=1000export PYTHONPATH=$PWD/src:$PYTHONPATHpdm run python -m local_deep_research.web.app > server.log 2>&1 &diff --git a/.github/workflows/owasp-zap-scan.yml b/.github/workflows/owasp-zap-scan.ymlindex 7b1424e69b..e56d3cca49 100644--- a/.github/workflows/owasp-zap-scan.yml+++ b/.github/workflows/owasp-zap-scan.yml@@ -50,7 +50,6 @@ jobs:- name: Start LDR server for testingrun: |export CI=true- export LDR_USE_FALLBACK_LLM=trueexport LDR_DB_KDF_ITERATIONS=1000export PYTHONPATH=$PWD/src:$PYTHONPATHpdm run python -m local_deep_research.web.app > server.log 2>&1 &@@ -142,7 +141,6 @@ jobs:- name: Start LDR server for testingrun: |export CI=true- export LDR_USE_FALLBACK_LLM=trueexport LDR_DB_KDF_ITERATIONS=1000export PYTHONPATH=$PWD/src:$PYTHONPATHpdm run python -m local_deep_research.web.app > server.log 2>&1 &diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yamlindex 1ce4f8ed3b..f679225742 100644--- a/.pre-commit-config.yaml+++ b/.pre-commit-config.yaml@@ -208,9 +208,9 @@ repos:name: Check Golden Master Settings Syncentry: .pre-commit-hooks/check-golden-master-settings.pylanguage: script- files: ^(src/local_deep_research/defaults/.*\.json|src/local_deep_research/config/.*)$+ files: ^src/local_deep_research/defaults/.*\.json$pass_filenames: false- description: "Ensure golden master settings are updated when defaults or config change"+ description: "Ensure golden master settings are updated when defaults change"- id: recommend-docsname: Documentation Reminderentry: .pre-commit-hooks/recommend-docs.pydiff --git a/.pre-commit-hooks/check-golden-master-settings.py b/.pre-commit-hooks/check-golden-master-settings.pyindex 20d3c4553c..0e8edd1d38 100755--- a/.pre-commit-hooks/check-golden-master-settings.py+++ b/.pre-commit-hooks/check-golden-master-settings.py@@ -1,5 +1,5 @@#!/usr/bin/env python3-"""Check that golden master settings are updated when defaults change."""+"""Check that golden master settings are updated when default settings change."""import subprocessimport sys@@ -17,11 +17,8 @@ def main():staged_files = result.stdout.strip().splitlines()defaults_changed = any(- (- f.startswith("src/local_deep_research/defaults/")- and f.endswith(".json")- )- or f.startswith("src/local_deep_research/config/")+ f.startswith("src/local_deep_research/defaults/")+ and f.endswith(".json")for f in staged_files)@@ -32,16 +29,13 @@ def main():if golden_master in staged_files:return 0- print(- "ERROR: Default settings or config changed but golden master not updated!"- )+ print("ERROR: Default settings changed but golden master not updated!")print()print(" Staged files that affect settings:")for f in staged_files:- if (- f.startswith("src/local_deep_research/defaults/")- and f.endswith(".json")- ) or f.startswith("src/local_deep_research/config/"):+ if f.startswith("src/local_deep_research/defaults/") and f.endswith(+ ".json"+ ):print(f" - {f}")print()print(" To regenerate the golden master:")diff --git a/docs/CI_CD_INFRASTRUCTURE.md b/docs/CI_CD_INFRASTRUCTURE.mdindex 5e92b4ca2a..1be729a9ce 100644--- a/docs/CI_CD_INFRASTRUCTURE.md+++ b/docs/CI_CD_INFRASTRUCTURE.md@@ -262,7 +262,6 @@ docker run --rm -v "$PWD":/app -w /app ldr-test \| Variable | Purpose ||----------|---------|| `CI=true` | Indicates CI environment |-| `LDR_USE_FALLBACK_LLM=true` | Use mock LLM for tests || `LDR_TESTING_WITH_MOCKS=true` | Enable test mocks || `DISABLE_RATE_LIMITING=true` | Disable rate limits in tests |diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.mdindex 4d58160096..4bb543b529 100644--- a/docs/CONFIGURATION.md+++ b/docs/CONFIGURATION.md@@ -53,7 +53,6 @@ They are not available in the Web UI because they are needed to start the applic| `LDR_SECURITY_WEBSOCKET_ALLOWED_ORIGINS` | String | `None` | No | | Allowed origins for WebSocket/Socket.IO connections (comma-separated). Use '*' for all origins (default), empty for same-origin only. Example: 'https://example.com,https://app.example.com' | Security | || `LDR_SERVER_MAX_CONCURRENT_RESEARCH` | Integer | `10` | No | 1..1000 | Server-wide maximum concurrent research operations. Requires restart. | Server | LDR_MAX_GLOBAL_CONCURRENT || `LDR_TESTING_TEST_MODE` | Boolean | `False` | No | | Enable test mode (adds delays for testing concurrency) | Testing | |-| `LDR_TESTING_USE_FALLBACK_LLM` | Boolean | `False` | No | | Use mock LLM for testing (skips API calls and DB operations) | Testing | |## Settings Listdiff --git a/docs/developing.md b/docs/developing.mdindex a203488639..5f5baf5b18 100644--- a/docs/developing.md+++ b/docs/developing.md@@ -234,7 +234,7 @@ docker volume rm ldr_data**Cause:** Background threads don't have access to the Flask request context.-**Solution:** This is handled automatically by the application. If you encounter this during development, ensure your LLM settings are configured via the web UI settings page. For CI/testing environments, the `LDR_TESTING_USE_FALLBACK_LLM=true` environment variable enables a mock LLM fallback.+**Solution:** This is handled automatically by the application. If you encounter this during development, ensure your LLM settings are configured via the web UI settings page.### PDM Lockfile Out of Syncdiff --git a/scripts/dev/regenerate_golden_master.py b/scripts/dev/regenerate_golden_master.pyindex 8e399d8d03..f2366cd4fe 100755--- a/scripts/dev/regenerate_golden_master.py+++ b/scripts/dev/regenerate_golden_master.py@@ -30,7 +30,12 @@ def main() -> int:defaults = manager.default_settingscurrent = {key: dict(defaults[key]) for key in sorted(defaults.keys())}- output = json.dumps(current, indent=2, sort_keys=True, default=str) + "\n"+ output = (+ json.dumps(+ current, indent=2, sort_keys=True, default=str, ensure_ascii=False+ )+ + "\n"+ )GOLDEN_MASTER_PATH.write_text(output, encoding="utf-8")diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.pyindex c9f39e447c..09d50762b9 100644--- a/src/local_deep_research/config/llm_config.py+++ b/src/local_deep_research/config/llm_config.py@@ -1,8 +1,7 @@-import osfrom functools import cachefrom langchain_anthropic import ChatAnthropic-from langchain_core.language_models import BaseChatModel, FakeListChatModel+from langchain_core.language_models import BaseChatModelfrom langchain_ollama import ChatOllamafrom langchain_openai import ChatOpenAIfrom loguru import logger@@ -19,7 +18,7 @@ try:except ImportError:pass # Providers module not available yetfrom .thread_settings import (- get_llm_setting_from_snapshot as get_setting_from_snapshot,+ get_setting_from_snapshot,NoSettingsContextError,)@@ -353,75 +352,6 @@ def get_llm(settings_snapshot=settings_snapshot,)- # Check if we're in testing mode and should use fallback (but only when no API keys are configured)- # Skip fallback check if we're in test mode with mocks- if os.environ.get("LDR_USE_FALLBACK_LLM", "") and not os.environ.get(- "LDR_TESTING_WITH_MOCKS", ""- ):- # Only use fallback if the provider has no valid configuration- provider_has_config = False-- if (- (- provider == "openai"- and get_setting_from_snapshot(- "llm.openai.api_key",- default=None,- settings_snapshot=settings_snapshot,- )- )- or (- provider == "anthropic"- and get_setting_from_snapshot(- "llm.anthropic.api_key",- default=None,- settings_snapshot=settings_snapshot,- )- )- or (- provider == "openai_endpoint"- and get_setting_from_snapshot(- "llm.openai_endpoint.api_key",- settings_snapshot=settings_snapshot,- )- )- or (- provider == "ollama"- and is_ollama_available(settings_snapshot=settings_snapshot)- )- ):- provider_has_config = True- elif provider in ["vllm", "lmstudio", "llamacpp"]:- # These are local providers, check their availability- if (- (provider == "vllm" and is_vllm_available())- or (- provider == "lmstudio"- and is_lmstudio_available(- settings_snapshot=settings_snapshot- )- )- or (- provider == "llamacpp"- and is_llamacpp_available(- settings_snapshot=settings_snapshot- )- )- ):- provider_has_config = True-- if not provider_has_config:- logger.info(- "LDR_USE_FALLBACK_LLM is set and no valid provider config found, using fallback model"- )- return wrap_llm_without_think_tags(- get_fallback_model(temperature),- research_id=research_id,- provider="fallback",- research_context=research_context,- settings_snapshot=settings_snapshot,- )-# Validate providerif provider not in VALID_PROVIDERS:logger.error(f"Invalid provider in settings: {provider}")@@ -486,10 +416,9 @@ def get_llm()if not api_key:- logger.warning(- "Anthropic API key not found in settings. Falling back to default model."+ raise ValueError(+ "Anthropic API key not configured. Please set llm.anthropic.api_key in settings.")- return get_fallback_model(temperature)llm = ChatAnthropic(model=model_name, anthropic_api_key=api_key, **common_params@@ -508,10 +437,9 @@ def get_llm()if not api_key:- logger.warning(- "OpenAI API key not found in settings. Falling back to default model."+ raise ValueError(+ "OpenAI API key not configured. Please set llm.openai.api_key in settings.")- return get_fallback_model(temperature)# Build OpenAI-specific parametersopenai_params = {@@ -591,10 +519,9 @@ def get_llm()if not api_key:- logger.warning(- "OpenAI endpoint API key not found in settings. Falling back to default model."+ raise ValueError(+ "OpenAI endpoint API key not configured. Please set llm.openai_endpoint.api_key in settings.")- return get_fallback_model(temperature)# Get endpoint URL from settingsif openai_endpoint_url is None:@@ -621,10 +548,9 @@ def get_llm(elif provider == "vllm":if not is_vllm_available():- logger.warning(- "VLLM dependencies are not available. Falling back to default model."+ raise ValueError(+ "VLLM dependencies are not available. Please install torch, transformers, and vllm.")- return get_fallback_model(temperature)try:from langchain_community.llms import VLLM@@ -645,7 +571,7 @@ def get_llm()except Exception:logger.exception("Error loading VLLM model")- return get_fallback_model(temperature)+ raiseelif provider == "ollama":try:@@ -663,10 +589,9 @@ def get_llm(# Check if Ollama is available before trying to use itif not is_ollama_available(settings_snapshot=settings_snapshot):- logger.error(- f"Ollama not available at {base_url}. Falling back to dummy model."+ raise ValueError(+ f"Ollama is not available at {base_url}. Please ensure Ollama is running.")- return get_fallback_model(temperature)# Check if the requested model existstry:@@ -697,10 +622,11 @@ def get_llm()if model_name.lower() not in model_names:- logger.error(+ raise ValueError(f"Model '{model_name}' not found in Ollama. Available models: {', '.join(model_names[:5])}")- return get_fallback_model(temperature)+ except ValueError:+ raiseexcept Exception:logger.exception(f"Error checking for model '{model_name}' in Ollama"@@ -775,10 +701,10 @@ def get_llm()except Exception:logger.exception("Error creating or testing ChatOllama")- return get_fallback_model(temperature)+ raiseexcept Exception:logger.exception("Error in Ollama provider section")- return get_fallback_model(temperature)+ raiseelif provider == "lmstudio":# LM Studio supports OpenAI API format, so we can use ChatOpenAI directly@@ -915,23 +841,19 @@ def get_llm(settings_snapshot=settings_snapshot,)- else:- return wrap_llm_without_think_tags(- get_fallback_model(temperature),- research_id=research_id,- provider=provider,- research_context=research_context,- settings_snapshot=settings_snapshot,+ elif provider == "none":+ raise ValueError(+ "No LLM provider configured. Please set llm.provider in settings "+ "to a valid provider (e.g., 'ollama', 'openai', 'anthropic').")--def get_fallback_model(temperature=None):- """Create a dummy model for when no providers are available"""- return FakeListChatModel(- responses=[- "No language models are available. Please install Ollama or set up API keys."- ]- )+ else:+ # Provider validated above but not handled - this shouldn't happen+ # since VALID_PROVIDERS check above would catch unknown providers+ raise ValueError(+ f"Provider '{provider}' is valid but not implemented. "+ f"This is a bug - please report it."+ )def wrap_llm_without_think_tags(diff --git a/src/local_deep_research/config/thread_settings.py b/src/local_deep_research/config/thread_settings.pyindex f561774ea9..de845f7f78 100644--- a/src/local_deep_research/config/thread_settings.py+++ b/src/local_deep_research/config/thread_settings.py@@ -4,7 +4,6 @@ This module provides a single thread-local storage instance that can beshared across different modules to maintain settings context in threads."""-import osimport threadingfrom contextlib import contextmanager@@ -67,7 +66,6 @@ def get_setting_from_snapshot(default=None,username=None,settings_snapshot=None,- check_fallback_llm=False,):"""Get setting from context only - no database access from threads.@@ -76,7 +74,6 @@ def get_setting_from_snapshot(default: Default value if setting not foundusername: Username (unused, kept for backward compatibility)settings_snapshot: Optional settings snapshot dict- check_fallback_llm: Whether to check LDR_USE_FALLBACK_LLM env varReturns:Setting value or default@@ -127,20 +124,6 @@ def get_setting_from_snapshot(return value["value"]return value- # In CI/test environment with fallback LLM, return default values- # But skip this if we're in test mode with mocks- if (- check_fallback_llm- and os.environ.get("LDR_USE_FALLBACK_LLM", "")- and not os.environ.get("LDR_TESTING_WITH_MOCKS", "")- ):- from loguru import logger-- logger.debug(- f"Using default value for {key} in fallback LLM environment"- )- return default-# If a default was provided, return it instead of raising an exceptionif default is not None:from loguru import logger@@ -156,25 +139,11 @@ def get_setting_from_snapshot()-def get_llm_setting_from_snapshot(- key, default=None, username=None, settings_snapshot=None-):- """Get setting from snapshot with fallback LLM check enabled.-- Convenience wrapper used by LLM provider modules that always need- ``check_fallback_llm=True``.- """- return get_setting_from_snapshot(- key, default, username, settings_snapshot, check_fallback_llm=True- )--def get_bool_setting_from_snapshot(key,default=False,username=None,settings_snapshot=None,- check_fallback_llm=False,):"""Get a boolean setting from snapshot, handling string conversion.@@ -187,7 +156,6 @@ def get_bool_setting_from_snapshot(default: Default boolean value if setting not foundusername: Username (unused, kept for backward compatibility)settings_snapshot: Optional settings snapshot dict- check_fallback_llm: Whether to check LDR_USE_FALLBACK_LLM env varReturns:Boolean value of the setting@@ -197,7 +165,6 @@ def get_bool_setting_from_snapshot(default,username=username,settings_snapshot=settings_snapshot,- check_fallback_llm=check_fallback_llm,)return to_bool(value, default)diff --git a/src/local_deep_research/llm/providers/implementations/anthropic.py b/src/local_deep_research/llm/providers/implementations/anthropic.pyindex 5bf7672b3b..a8ee3fba11 100644--- a/src/local_deep_research/llm/providers/implementations/anthropic.py+++ b/src/local_deep_research/llm/providers/implementations/anthropic.py@@ -4,7 +4,7 @@ from langchain_anthropic import ChatAnthropicfrom loguru import loggerfrom ....config.thread_settings import (- get_llm_setting_from_snapshot as get_setting_from_snapshot,+ get_setting_from_snapshot,NoSettingsContextError,)from ...llm_registry import register_llmdiff --git a/src/local_deep_research/llm/providers/implementations/custom_openai_endpoint.py b/src/local_deep_research/llm/providers/implementations/custom_openai_endpoint.pyindex fac6f6cf3e..c6a249b8c5 100644--- a/src/local_deep_research/llm/providers/implementations/custom_openai_endpoint.py+++ b/src/local_deep_research/llm/providers/implementations/custom_openai_endpoint.py@@ -2,9 +2,7 @@from loguru import logger-from ....config.thread_settings import (- get_llm_setting_from_snapshot as get_setting_from_snapshot,-)+from ....config.thread_settings import get_setting_from_snapshotfrom ....utilities.url_utils import normalize_urlfrom ...llm_registry import register_llmfrom ..openai_base import OpenAICompatibleProviderdiff --git a/src/local_deep_research/llm/providers/implementations/ollama.py b/src/local_deep_research/llm/providers/implementations/ollama.pyindex 8b15ab712d..d1a32570e7 100644--- a/src/local_deep_research/llm/providers/implementations/ollama.py+++ b/src/local_deep_research/llm/providers/implementations/ollama.py@@ -4,9 +4,7 @@ import requestsfrom langchain_ollama import ChatOllamafrom loguru import logger-from ....config.thread_settings import (- get_llm_setting_from_snapshot as get_setting_from_snapshot,-)+from ....config.thread_settings import get_setting_from_snapshotfrom ....utilities.url_utils import normalize_urlfrom ...llm_registry import register_llmfrom ....security import safe_getdiff --git a/src/local_deep_research/llm/providers/implementations/openai.py b/src/local_deep_research/llm/providers/implementations/openai.pyindex f2f9467bae..3511ed083d 100644--- a/src/local_deep_research/llm/providers/implementations/openai.py+++ b/src/local_deep_research/llm/providers/implementations/openai.py@@ -4,7 +4,7 @@ from langchain_openai import ChatOpenAIfrom loguru import loggerfrom ....config.thread_settings import (- get_llm_setting_from_snapshot as get_setting_from_snapshot,+ get_setting_from_snapshot,NoSettingsContextError,)from ...llm_registry import register_llmdiff --git a/src/local_deep_research/llm/providers/openai_base.py b/src/local_deep_research/llm/providers/openai_base.pyindex 1be7c5e364..af21e61ca2 100644--- a/src/local_deep_research/llm/providers/openai_base.py+++ b/src/local_deep_research/llm/providers/openai_base.py@@ -4,7 +4,7 @@ from langchain_openai import ChatOpenAIfrom loguru import loggerfrom ...config.thread_settings import (- get_llm_setting_from_snapshot as get_setting_from_snapshot,+ get_setting_from_snapshot,NoSettingsContextError,)from ...utilities.url_utils import normalize_urldiff --git a/src/local_deep_research/settings/README.md b/src/local_deep_research/settings/README.mdindex ef0fa5afc0..6b9b773c37 100644--- a/src/local_deep_research/settings/README.md+++ b/src/local_deep_research/settings/README.md@@ -4,7 +4,7 @@```python# Use environment settings-from local_deep_research.settings.env_registry import is_test_mode, use_fallback_llm+from local_deep_research.settings.env_registry import is_test_modeif is_test_mode():# Running in test mode@@ -55,7 +55,6 @@ registry.register(MY_SETTING)### Testing- `LDR_TEST_MODE`: Enable test mode-- `LDR_USE_FALLBACK_LLM`: Use fallback LLM- `CI`: Running in CI### Bootstrap (needed before DB)diff --git a/src/local_deep_research/settings/env_definitions/testing.py b/src/local_deep_research/settings/env_definitions/testing.pyindex 5c85110c37..ca590269e1 100644--- a/src/local_deep_research/settings/env_definitions/testing.py+++ b/src/local_deep_research/settings/env_definitions/testing.py@@ -26,9 +26,4 @@ TESTING_SETTINGS = [description="Enable test mode (adds delays for testing concurrency)",default=False,),- BooleanSetting(- key="testing.use_fallback_llm",- description="Use mock LLM for testing (skips API calls and DB operations)",- default=False,- ),]diff --git a/src/local_deep_research/settings/env_registry.py b/src/local_deep_research/settings/env_registry.pyindex d1d5c41818..4a7b870f8e 100644--- a/src/local_deep_research/settings/env_registry.py+++ b/src/local_deep_research/settings/env_registry.py@@ -46,11 +46,6 @@ def is_test_mode() -> bool:return bool(registry.get("testing.test_mode", False))-def use_fallback_llm() -> bool:- """Quick check for fallback LLM mode."""- return bool(registry.get("testing.use_fallback_llm", False))--def is_ci_environment() -> bool:"""Quick check for CI environment."""# CI is now an external variable, read it dynamically@@ -104,7 +99,6 @@ __all__ = ["registry","get_env_setting","is_test_mode",- "use_fallback_llm","is_ci_environment","is_github_actions","is_rate_limiting_enabled",diff --git a/src/local_deep_research/utilities/db_utils.py b/src/local_deep_research/utilities/db_utils.pyindex 4538516951..0066a9263e 100644--- a/src/local_deep_research/utilities/db_utils.py+++ b/src/local_deep_research/utilities/db_utils.py@@ -11,8 +11,6 @@ from flask import (from loguru import loggerfrom sqlalchemy.orm import Session-from ..settings.env_registry import use_fallback_llm-from ..config.paths import get_data_directoryfrom ..database.encrypted_db import db_managerfrom .threading_utils import thread_specific_cache@@ -165,13 +163,6 @@ def get_setting_from_db_main_thread(The setting value."""- # In fallback LLM mode, always return default values without database access- if use_fallback_llm():- logger.debug(- f"Using default value for {key} in fallback LLM environment"- )- return default_value-# CRITICAL: Detect if we're in a background thread and raise an errorimport threadingdiff --git a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py b/src/local_deep_research/web_search_engines/rate_limiting/tracker.pyindex 5f90ead8cf..af0ac8698e 100644--- a/src/local_deep_research/web_search_engines/rate_limiting/tracker.py+++ b/src/local_deep_research/web_search_engines/rate_limiting/tracker.py@@ -16,7 +16,7 @@ from ...config.thread_settings import (get_setting_from_snapshot,get_settings_context,)-from ...settings.env_registry import is_ci_environment, use_fallback_llm+from ...settings.env_registry import is_ci_environmentfrom ...utilities.thread_context import get_search_context# Lazy imports to avoid database initialization in programmatic mode@@ -149,13 +149,6 @@ class AdaptiveRateLimitTracker:)return- # Skip database operations in fallback mode- if use_fallback_llm():- logger.debug(- "Skipping rate limit estimate loading in fallback mode"- )- return-# During initialization, we don't have user context yet# Mark that we need to load estimates when user context becomes availableself._estimates_loaded = False@@ -456,7 +449,7 @@ class AdaptiveRateLimitTracker:"confidence": min(len(attempts) / 20.0, 1.0),}- # Persist to database (skip in fallback mode)+ # Persist to databasesuccess_rate = len(successful_waits) / len(attempts) if attempts else 0# Skip database operations in programmatic mode@@ -464,7 +457,7 @@ class AdaptiveRateLimitTracker:logger.debug(f"Skipping estimate persistence in programmatic mode for {engine_type}")- elif not use_fallback_llm():+ else:# Try to get research context from search trackercontext = get_search_context()@@ -567,9 +560,9 @@ class AdaptiveRateLimitTracker:Returns:List of tuples with engine statistics"""- # Skip database operations in test/fallback mode- if use_fallback_llm() or is_ci_environment():- logger.debug("Skipping database stats in test/CI mode")+ # Skip database operations in CI mode+ if is_ci_environment():+ logger.debug("Skipping database stats in CI mode")return self._get_in_memory_stats(engine_type)# Skip database operations in programmatic mode@@ -645,10 +638,10 @@ class AdaptiveRateLimitTracker:)return- # Skip database operations in test/fallback mode- if use_fallback_llm() or is_ci_environment():+ # Skip database operations in CI mode+ if is_ci_environment():logger.debug(- f"Reset rate limit data for {engine_type} (memory only in test/CI mode)"+ f"Reset rate limit data for {engine_type} (memory only in CI mode)")return@@ -777,9 +770,9 @@ class AdaptiveRateLimitTracker:logger.debug("Skipping database cleanup in programmatic mode")return- # Skip database operations in test/fallback mode- if use_fallback_llm() or is_ci_environment():- logger.debug("Skipping database cleanup in test/CI mode")+ # Skip database operations in CI mode+ if is_ci_environment():+ logger.debug("Skipping database cleanup in CI mode")returntry:diff --git a/tests/api_tests/test_all_endpoints.py b/tests/api_tests/test_all_endpoints.pyindex 91f672b9ac..55bc1dc43d 100644--- a/tests/api_tests/test_all_endpoints.py+++ b/tests/api_tests/test_all_endpoints.py@@ -6,6 +6,7 @@ This ensures we have coverage for every single endpoint.import jsonimport time+import pytestfrom loguru import loggerdiff --git a/tests/api_tests/test_rest_api.py b/tests/api_tests/test_rest_api.pyindex a6b2082b05..794ebac4f6 100644--- a/tests/api_tests/test_rest_api.py+++ b/tests/api_tests/test_rest_api.py@@ -4,6 +4,7 @@ Tests programmatic access functionality with fast, simple requests."""import json+import pytest# Test timeout in secondsdiff --git a/tests/config/test_llm_config.py b/tests/config/test_llm_config.pyindex d7709fa48a..d61919a7e0 100644--- a/tests/config/test_llm_config.py+++ b/tests/config/test_llm_config.py@@ -5,7 +5,6 @@ from unittest.mock import MagicMock, patchfrom local_deep_research.config.llm_config import (VALID_PROVIDERS,- get_setting_from_snapshot,is_openai_available,is_anthropic_available,is_openai_endpoint_available,@@ -16,7 +15,6 @@ from local_deep_research.config.llm_config import (is_openrouter_available,get_available_providers,get_selected_llm_provider,- get_fallback_model,wrap_llm_without_think_tags,get_llm,)@@ -47,21 +45,6 @@ class TestValidProviders:assert isinstance(VALID_PROVIDERS, list)-class TestGetSettingFromSnapshot:- """Tests for get_setting_from_snapshot wrapper."""-- def test_enables_fallback_llm_check(self):- """Should enable check_fallback_llm via get_llm_setting_from_snapshot."""- with patch(- "local_deep_research.config.thread_settings.get_setting_from_snapshot"- ) as mock:- mock.return_value = "value"- get_setting_from_snapshot("key", "default")- mock.assert_called_with(- "key", "default", None, None, check_fallback_llm=True- )--class TestIsOpenaiAvailable:"""Tests for is_openai_available function (delegates to OpenAIProvider)."""@@ -367,23 +350,6 @@ class TestGetSelectedLlmProvider:)-class TestGetFallbackModel:- """Tests for get_fallback_model function."""-- def test_returns_fake_list_chat_model(self):- """Should return a FakeListChatModel."""- from langchain_core.language_models import FakeListChatModel-- result = get_fallback_model()- assert isinstance(result, FakeListChatModel)-- def test_has_helpful_message(self):- """Should have a helpful message about no providers."""- result = get_fallback_model()- assert len(result.responses) > 0- assert "No language models" in result.responses[0]--class TestWrapLlmWithoutThinkTags:"""Tests for wrap_llm_without_think_tags function."""@@ -585,9 +551,9 @@ class TestGetLlm:assert call_kwargs["model"] == "claude-3-sonnet"assert call_kwargs["anthropic_api_key"] == "sk-ant-test"- def test_anthropic_without_api_key_returns_fallback(self):- """Should return fallback model when anthropic API key not set."""- from langchain_core.language_models import FakeListChatModel+ def test_anthropic_without_api_key_raises_error(self):+ """Test that missing Anthropic API key raises ValueError."""+ import pytestwith patch("local_deep_research.config.llm_config.is_llm_registered",@@ -608,9 +574,10 @@ class TestGetLlm:"rate_limiting.llm_enabled": False,}.get(key, default)- result = get_llm(provider="anthropic")- # Returns FakeListChatModel directly (not wrapped) when no API key- assert isinstance(result, FakeListChatModel)+ with pytest.raises(+ ValueError, match="Anthropic API key not configured"+ ):+ get_llm(provider="anthropic")def test_openai_provider_creates_chat_openai(self):"""Should create ChatOpenAI when provider is openai."""@@ -649,9 +616,9 @@ class TestGetLlm:assert call_kwargs["model"] == "gpt-4"assert call_kwargs["api_key"] == "sk-test"- def test_openai_without_api_key_returns_fallback(self):- """Should return fallback model when openai API key not set."""- from langchain_core.language_models import FakeListChatModel+ def test_openai_without_api_key_raises_error(self):+ """Test that missing OpenAI API key raises ValueError."""+ import pytestwith patch("local_deep_research.config.llm_config.is_llm_registered",@@ -672,9 +639,10 @@ class TestGetLlm:"rate_limiting.llm_enabled": False,}.get(key, default)- result = get_llm(provider="openai")- # Returns FakeListChatModel directly (not wrapped) when no API key- assert isinstance(result, FakeListChatModel)+ with pytest.raises(+ ValueError, match="OpenAI API key not configured"+ ):+ get_llm(provider="openai")def test_openai_endpoint_creates_chat_openai(self):"""Should create ChatOpenAI with custom endpoint when provider is openai_endpoint."""@@ -841,32 +809,6 @@ class TestGetLlm:):get_llm(provider="bad_factory")- def test_none_provider_returns_fallback(self):- """Should return fallback model when provider is 'none'."""- from langchain_core.language_models import FakeListChatModel-- with patch(- "local_deep_research.config.llm_config.is_llm_registered",- return_value=False,- ):- with patch(- "local_deep_research.config.llm_config.get_setting_from_snapshot"- ) as mock_get:- mock_get.side_effect = lambda key, default=None, **kwargs: {- "llm.model": "test-model",- "llm.temperature": 0.7,- "llm.provider": "none",- "llm.local_context_window_size": 4096,- "llm.context_window_unrestricted": True,- "llm.supports_max_tokens": True,- "llm.max_tokens": 4096,- "rate_limiting.llm_enabled": False,- }.get(key, default)-- result = get_llm(provider="none")- assert hasattr(result, "base_llm")- assert isinstance(result.base_llm, FakeListChatModel)-def test_context_window_size_for_local_providers(self):"""Should use local context window size for local providers."""with patch(@@ -907,28 +849,34 @@ class TestGetLlm:"""Should accept research_context parameter."""research_context = {"existing": "value"}+ mock_llm = MagicMock()with patch("local_deep_research.config.llm_config.is_llm_registered",return_value=False,):- with patch(- "local_deep_research.config.llm_config.get_setting_from_snapshot"- ) as mock_get:+ with (+ patch(+ "local_deep_research.config.llm_config.get_setting_from_snapshot"+ ) as mock_get,+ patch(+ "local_deep_research.config.llm_config.ChatAnthropic",+ return_value=mock_llm,+ ),+ ):mock_get.side_effect = lambda key, default=None, **kwargs: {"llm.model": "test-model","llm.temperature": 0.7,- "llm.provider": "none", # Falls through to default- "llm.local_context_window_size": 4096,+ "llm.provider": "anthropic",+ "llm.anthropic.api_key": "test-key","llm.context_window_unrestricted": True,"llm.supports_max_tokens": True,"llm.max_tokens": 4096,"rate_limiting.llm_enabled": False,}.get(key, default)- # Should not fail when research_context is passedresult = get_llm(- provider="none", research_context=research_context+ provider="anthropic", research_context=research_context)assert hasattr(result, "base_llm")# Original key should still be therediff --git a/tests/config/test_llm_config_behavior.py b/tests/config/test_llm_config_behavior.pyindex a87e461e6f..d53c80e87f 100644--- a/tests/config/test_llm_config_behavior.py+++ b/tests/config/test_llm_config_behavior.py@@ -95,56 +95,42 @@ class TestModelAndProviderNameCleaning:"""Tests for model_name and provider name cleaning in get_llm().get_llm strips quotes, whitespace, and lowercases the provider name- before validation. Using provider='none' (valid, returns fallback).+ before validation."""def test_quoted_provider_name_cleaned(self):- """Surrounding quotes are stripped: \"'none'\" → 'none'."""+ """Surrounding quotes are stripped: \"'none'\" → 'none' (valid but unimplemented)."""+ import pytestfrom local_deep_research.config.llm_config import get_llm- result = get_llm(provider="'none'", settings_snapshot={})- assert result is not None+ # 'none' is valid but has no implementation, so it raises ValueError+ # The point is the quotes are stripped before validation+ with pytest.raises(ValueError, match="No LLM provider configured"):+ get_llm(provider="'none'", settings_snapshot={})def test_whitespace_provider_name_cleaned(self):"""Surrounding whitespace is stripped: ' none ' → 'none'."""+ import pytestfrom local_deep_research.config.llm_config import get_llm- result = get_llm(provider=" none ", settings_snapshot={})- assert result is not None+ with pytest.raises(ValueError, match="No LLM provider configured"):+ get_llm(provider=" none ", settings_snapshot={})def test_uppercase_provider_lowercased(self):"""Provider name is lowercased: 'NONE' → 'none'."""+ import pytestfrom local_deep_research.config.llm_config import get_llm- result = get_llm(provider="NONE", settings_snapshot={})- assert result is not None+ with pytest.raises(ValueError, match="No LLM provider configured"):+ get_llm(provider="NONE", settings_snapshot={})def test_combined_quotes_whitespace_case_cleaning(self):"""Combined cleaning: \" 'None' \" → 'none'."""+ import pytestfrom local_deep_research.config.llm_config import get_llm- result = get_llm(provider=" 'None' ", settings_snapshot={})- assert result is not None---class TestFallbackModel:- """Tests for get_fallback_model() function."""-- def test_returns_fake_list_chat_model(self):- from langchain_core.language_models import FakeListChatModel-- from local_deep_research.config.llm_config import get_fallback_model-- result = get_fallback_model()- assert isinstance(result, FakeListChatModel)-- def test_fallback_has_informative_response(self):- """Fallback model's response tells user no providers are available."""- from local_deep_research.config.llm_config import get_fallback_model-- result = get_fallback_model()- assert len(result.responses) > 0- assert "No language models" in result.responses[0]+ with pytest.raises(ValueError, match="No LLM provider configured"):+ get_llm(provider=" 'None' ", settings_snapshot={})class TestGetSelectedLlmProvider:diff --git a/tests/config/test_llm_config_coverage.py b/tests/config/test_llm_config_coverage.pyindex 2a964146df..62d3d5d4b7 100644--- a/tests/config/test_llm_config_coverage.py+++ b/tests/config/test_llm_config_coverage.py@@ -7,7 +7,6 @@ Focuses on gaps not covered by existing test files:- is_vllm_available() with mocked imports- get_available_providers() multi-provider and cache behaviour- wrap_llm_without_think_tags() context_limit injection, token counter, string responses-- get_fallback_model() temperature parameter- _get_context_window_for_provider() edge cases- get_selected_llm_provider() with snapshot parameter"""@@ -16,8 +15,6 @@ import sysfrom unittest.mock import MagicMock, patchimport pytest-from langchain_core.language_models import FakeListChatModel-# ---------------------------------------------------------------------------# Helpers@@ -758,49 +755,6 @@ class TestGetContextWindowForProvider:assert isinstance(result, int)-# ===================================================================-# get_fallback_model-# ===================================================================---class TestGetFallbackModel:- """Additional coverage for get_fallback_model()."""-- def test_returns_fake_list_chat_model(self):- from local_deep_research.config.llm_config import get_fallback_model-- model = get_fallback_model()- assert isinstance(model, FakeListChatModel)-- def test_temperature_param_accepted(self):- """temperature parameter is accepted (even though FakeListChatModel ignores it)."""- from local_deep_research.config.llm_config import get_fallback_model-- model = get_fallback_model(temperature=0.0)- assert isinstance(model, FakeListChatModel)-- def test_none_temperature_accepted(self):- from local_deep_research.config.llm_config import get_fallback_model-- model = get_fallback_model(temperature=None)- assert isinstance(model, FakeListChatModel)-- def test_response_text_mentions_ollama_or_api_keys(self):- from local_deep_research.config.llm_config import get_fallback_model-- model = get_fallback_model()- msg = model.responses[0]- assert "Ollama" in msg or "API keys" in msg-- def test_invocation_returns_ai_message(self):- from local_deep_research.config.llm_config import get_fallback_model-- model = get_fallback_model()- response = model.invoke("hello")- assert hasattr(response, "content")- assert "No language models" in response.content--# ===================================================================# wrap_llm_without_think_tags# ===================================================================diff --git a/tests/config/test_llm_config_deep_coverage.py b/tests/config/test_llm_config_deep_coverage.pyindex d7d243bf6d..878eea3061 100644--- a/tests/config/test_llm_config_deep_coverage.py+++ b/tests/config/test_llm_config_deep_coverage.py@@ -3,16 +3,14 @@Focuses on:- get_llm() with registered custom LLMs (callable factory and BaseChatModel instance)- get_llm() with invalid provider-- get_llm() with LDR_USE_FALLBACK_LLM env var- ProcessingLLMWrapper.close()- _get_context_window_for_provider() with None window_size from settings"""-import osfrom unittest.mock import MagicMock, patchimport pytest-from langchain_core.language_models import BaseChatModel, FakeListChatModel+from langchain_core.language_models import BaseChatModelMODULE = "local_deep_research.config.llm_config"@@ -190,43 +188,6 @@ class TestGetLlmInvalidProvider:get_llm(provider="bogus_provider", settings_snapshot={})-# ----------------------------------------------------------------------------# get_llm with fallback LLM env var-# ------------------------------------------------------------------------------class TestGetLlmFallbackEnvVar:- def test_fallback_used_when_no_config(self):- """LDR_USE_FALLBACK_LLM causes fallback when no valid provider config."""- with (- patch.dict(os.environ, {"LDR_USE_FALLBACK_LLM": "1"}, clear=False),- patch(f"{MODULE}.is_llm_registered", return_value=False),- patch(f"{MODULE}.get_setting_from_snapshot") as mock_setting,- patch(f"{MODULE}.wrap_llm_without_think_tags"),- patch(f"{MODULE}.get_fallback_model") as mock_fallback,- ):- mock_fallback.return_value = FakeListChatModel(- responses=["fallback"]- )- mock_setting.side_effect = (- lambda key, default=None, settings_snapshot=None: {- "llm.model": "gpt-4",- "llm.temperature": 0.7,- "llm.provider": "openai",- "llm.openai.api_key": None, # No key => uses fallback- "llm.supports_max_tokens": False,- "llm.context_window_unrestricted": True,- "rate_limiting.llm_enabled": False,- }.get(key, default)- )-- from local_deep_research.config.llm_config import get_llm-- get_llm(provider="openai", settings_snapshot={})-- mock_fallback.assert_called()--# ---------------------------------------------------------------------------# _get_context_window_for_provider edge cases# ---------------------------------------------------------------------------@@ -384,9 +345,7 @@ class TestGetLlmNameCleaning:from local_deep_research.config.llm_config import get_llm- # Should not raise InvalidProvider (OpenAI -> openai is valid)- try:+ # Should raise ValueError about API key (not about invalid provider),+ # proving that "OpenAI" was lowercased to "openai" successfully.+ with pytest.raises(ValueError, match="API key not configured"):get_llm(settings_snapshot={})- # If it returns a fallback model, that's fine- except ValueError as e:- pytest.fail(f"Provider case normalization failed: {e}")diff --git a/tests/config/test_llm_config_extended.py b/tests/config/test_llm_config_extended.pyindex 274551a8e1..0f6ccbc9b8 100644--- a/tests/config/test_llm_config_extended.py+++ b/tests/config/test_llm_config_extended.py@@ -3,7 +3,6 @@from unittest.mock import MagicMock, patchimport pytest-from langchain_core.language_models import FakeListChatModelfrom local_deep_research.config.llm_config import get_llm@@ -36,8 +35,8 @@ def _mock_get_setting(settings):class TestVLLMProvider:"""Tests for the VLLM provider path in get_llm."""- def test_unavailable_returns_fallback(self):- """When VLLM deps aren't installed, fallback model is returned."""+ def test_unavailable_raises_error(self):+ """Test that unavailable VLLM raises ValueError."""settings = _settings_dict({"llm.provider": "vllm"})with (@@ -54,8 +53,8 @@ class TestVLLMProvider:return_value=False,),):- result = get_llm(provider="vllm")- assert isinstance(result, FakeListChatModel)+ with pytest.raises(ValueError, match="VLLM dependencies"):+ get_llm(provider="vllm")def test_available_creates_instance(self):"""When VLLM is available, VLLM instance is created."""@@ -91,8 +90,8 @@ class TestVLLMProvider:mock_vllm_cls.assert_called_once()assert result is mock_vllm_instance- def test_exception_returns_fallback(self):- """Exception during VLLM creation returns fallback."""+ def test_exception_raises_error(self):+ """Exception during VLLM creation is propagated."""settings = _settings_dict({"llm.provider": "vllm"})with (@@ -117,8 +116,8 @@ class TestVLLMProvider:},),):- result = get_llm(provider="vllm")- assert isinstance(result, FakeListChatModel)+ with pytest.raises(RuntimeError, match="GPU error"):+ get_llm(provider="vllm")# ── LlamaCpp provider ──────────────────────────────────────────────@@ -368,8 +367,8 @@ class TestOllamaProvider:s.update(overrides)return s- def test_model_not_found_returns_fallback(self):- """Model not in Ollama model list returns fallback."""+ def test_model_not_found_raises_error(self):+ """Model not in Ollama model list raises ValueError."""settings = self._ollama_settings()mock_response = MagicMock()@@ -394,8 +393,8 @@ class TestOllamaProvider:return_value=mock_response,),):- result = get_llm(provider="ollama", model_name="test-model")- assert isinstance(result, FakeListChatModel)+ with pytest.raises(ValueError, match="test-model"):+ get_llm(provider="ollama", model_name="test-model")def test_model_found_creates_client(self):"""Model found in list creates ChatOllama."""diff --git a/tests/config/test_llm_config_fallback.py b/tests/config/test_llm_config_fallback.pydeleted file mode 100644index f7acbb82b0..0000000000--- a/tests/config/test_llm_config_fallback.py+++ /dev/null@@ -1,337 +0,0 @@-"""-Tests for LLM config fallback chain activation.--Tests cover:-- Fallback chain activation-- Custom LLM registration-"""--from unittest.mock import Mock-import pytest---class TestFallbackChainActivation:- """Tests for fallback chain activation."""-- def test_fallback_llm_env_var_true(self):- """Fallback LLM activated by env var."""- env_value = "true"-- use_fallback = bool(env_value)-- assert use_fallback-- def test_fallback_llm_env_var_false(self):- """Fallback LLM not activated when env var is empty."""- env_value = ""-- use_fallback = bool(env_value)-- assert not use_fallback-- def test_fallback_llm_env_var_missing(self):- """Fallback LLM not activated when env var is missing."""- env_value = None-- use_fallback = bool(env_value) if env_value else False-- assert not use_fallback-- def test_fallback_chain_missing_config_level_1(self):- """Missing API key triggers fallback."""- api_key = None- provider = "openai"-- if provider in ["openai", "anthropic"] and not api_key:- use_fallback = True- else:- use_fallback = False-- assert use_fallback-- def test_fallback_chain_missing_config_level_2(self):- """Missing endpoint URL triggers fallback."""- endpoint_url = None- provider = "openai_endpoint"-- if provider == "openai_endpoint" and not endpoint_url:- use_fallback = True- else:- use_fallback = False-- assert use_fallback-- def test_fallback_chain_all_providers_unavailable(self):- """All providers unavailable triggers fallback."""- available_providers = {}-- if not available_providers:- use_fallback = True- else:- use_fallback = False-- assert use_fallback-- def test_fallback_chain_provider_config_validation(self):- """Provider configuration is validated."""- config = {- "provider": "openai",- "api_key": None, # Missing- "model": "gpt-4",- }-- required_fields = ["provider", "api_key", "model"]- is_valid = all(config.get(field) for field in required_fields)-- assert not is_valid-- def test_fallback_chain_cascading_execution(self):- """Fallback cascades through providers."""- providers_tried = []- providers = ["openai", "anthropic", "ollama"]-- for provider in providers:- providers_tried.append(provider)- # Simulate failure- if provider == "ollama":- success = True- break- else:- success = False-- assert success- assert providers_tried == ["openai", "anthropic", "ollama"]-- def test_fallback_model_returns_fake_list_chat_model(self):- """Fallback model returns FakeListChatModel."""- from local_deep_research.config.llm_config import get_fallback_model-- model = get_fallback_model(temperature=0.7)-- assert model is not None- assert hasattr(model, "invoke")-- def test_fallback_model_message_content(self):- """Fallback model returns helpful message."""- from local_deep_research.config.llm_config import get_fallback_model-- model = get_fallback_model()-- # FakeListChatModel has responses attribute- assert hasattr(model, "responses")- assert len(model.responses) > 0- assert "No language models are available" in model.responses[0]-- def test_fallback_model_invocation(self):- """Fallback model can be invoked."""- from local_deep_research.config.llm_config import get_fallback_model-- model = get_fallback_model()- response = model.invoke("test query")-- assert response is not None-- def test_fallback_registration_cleanup(self):- """Fallback registration is cleaned up properly."""- registry = {"custom_provider": Mock()}-- # Cleanup- del registry["custom_provider"]-- assert "custom_provider" not in registry---class TestCustomLLMRegistration:- """Tests for custom LLM registration."""-- def test_custom_llm_factory_function_detection(self):- """Factory function is detected correctly."""-- def factory_func(model_name, temperature, settings_snapshot):- return Mock()-- is_callable = callable(factory_func)- is_instance = isinstance(factory_func, type)-- assert is_callable- assert not is_instance-- def test_custom_llm_instance_detection(self):- """LLM instance is detected correctly."""- mock_llm = Mock()-- callable(mock_llm) # Mock is callable- has_invoke = hasattr(mock_llm, "invoke")-- # Mock has invoke- assert has_invoke-- def test_custom_llm_bad_signature_error(self):- """Bad factory signature raises error."""-- def bad_factory(only_one_param):- return Mock()-- with pytest.raises(TypeError):- # Simulate calling with expected params- bad_factory(- model_name="test",- temperature=0.7,- settings_snapshot={},- )-- def test_custom_llm_returned_type_validation(self):- """Factory must return correct type."""-- def factory_func(model_name, temperature, settings_snapshot):- return "not a model" # Wrong type-- result = factory_func("test", 0.7, {})-- # Should be validated as not a model- is_valid = hasattr(result, "invoke")-- assert not is_valid-- def test_custom_llm_non_base_chat_model_error(self):- """Non-BaseChatModel raises error."""-- class NotAChatModel:- pass-- result = NotAChatModel()-- # Check if it would pass validation- from langchain_core.language_models import BaseChatModel-- is_valid = isinstance(result, BaseChatModel)-- assert not is_valid-- def test_custom_llm_registration_persistence(self):- """Custom LLM registration persists."""- registry = {}-- # Register- registry["custom"] = Mock()-- # Check persistence- assert "custom" in registry-- # Still there- assert registry.get("custom") is not None-- def test_custom_llm_override_existing(self):- """Custom LLM can override existing."""- registry = {"custom": Mock(name="original")}-- # Override- registry["custom"] = Mock(name="override")-- assert registry["custom"]._mock_name == "override"-- def test_custom_llm_thread_safety(self):- """Custom LLM registration is thread-safe."""- import threading-- registry = {}- lock = threading.Lock()-- def register(name, llm):- with lock:- registry[name] = llm-- threads = []- for i in range(10):- t = threading.Thread(target=register, args=(f"llm_{i}", Mock()))- threads.append(t)- t.start()-- for t in threads:- t.join()-- assert len(registry) == 10---class TestFallbackConditions:- """Tests for various fallback conditions."""-- def test_fallback_on_import_error(self):- """Import error triggers fallback."""- import_error = True-- if import_error:- use_fallback = True- else:- use_fallback = False-- assert use_fallback-- def test_fallback_on_initialization_error(self):- """Initialization error triggers fallback."""- init_error = True-- if init_error:- use_fallback = True- else:- use_fallback = False-- assert use_fallback-- def test_fallback_on_network_error(self):- """Network error triggers fallback."""- network_error = True-- if network_error:- use_fallback = True- else:- use_fallback = False-- assert use_fallback-- def test_fallback_on_authentication_error(self):- """Authentication error triggers fallback."""- auth_error = True- error_code = 401-- if auth_error or error_code in [401, 403]:- use_fallback = True- else:- use_fallback = False-- assert use_fallback---class TestFallbackMessages:- """Tests for fallback message generation."""-- def test_fallback_message_no_providers(self):- """No providers available message."""- available_providers = {}-- if not available_providers:- message = "No language models are available. Please install Ollama or set up API keys."- else:- message = "Model ready"-- assert "No language models" in message-- def test_fallback_message_provider_specific(self):- """Provider-specific fallback message."""- provider = "openai"- error = "API key missing"-- message = f"Failed to initialize {provider}: {error}"-- assert "openai" in message.lower()- assert "API key" in message-- def test_fallback_message_with_suggestions(self):- """Fallback message includes suggestions."""- message = "No language models are available. Please install Ollama or set up API keys."-- has_suggestion = (- "install Ollama" in message or "set up API keys" in message- )-- assert has_suggestiondiff --git a/tests/config/test_llm_config_missing_coverage.py b/tests/config/test_llm_config_missing_coverage.pyindex 3862500cff..052d5c2994 100644--- a/tests/config/test_llm_config_missing_coverage.py+++ b/tests/config/test_llm_config_missing_coverage.py@@ -2,10 +2,10 @@Tests for missing coverage gaps in local_deep_research/config/llm_config.py.Targets specific uncovered code paths:-- get_llm fallback env var logic (LDR_USE_FALLBACK_LLM, LDR_TESTING_WITH_MOCKS,+- get_llm env var logic (LDR_USE_FALLBACK_LLM, LDR_TESTING_WITH_MOCKS,provider_has_config skipping, vllm/lmstudio/llamacpp local checks)-- get_llm vllm import exception path-- get_llm ollama model-not-found, creation exception, enable_thinking true/false+- get_llm vllm import exception path (now raises instead of falling back)+- get_llm ollama model-not-found, creation exception (now raises), enable_thinking true/false- get_llm llamacpp no model path, invalid extension, directory with gguf suggestion- _get_context_window_for_provider cloud unrestricted=False, local None window- wrap_llm_without_think_tags context_limit injection, no-overwrite, model_name vs model@@ -15,7 +15,6 @@ import osfrom unittest.mock import MagicMock, patchimport pytest-from langchain_core.language_models import FakeListChatModelMODULE = "local_deep_research.config.llm_config"@@ -46,7 +45,8 @@ class TestGetLlmFallbackEnvVar:"""Tests for LDR_USE_FALLBACK_LLM / LDR_TESTING_WITH_MOCKS env var guard."""def test_fallback_env_var_skipped_when_testing_with_mocks(self):- """When LDR_TESTING_WITH_MOCKS is set, fallback env var is ignored."""+ """When LDR_TESTING_WITH_MOCKS is set, fallback env var is ignored;+ now raises ValueError since fallback model was removed."""settings = _settings_dict({"llm.provider": "none"})with (patch.dict(@@ -61,8 +61,8 @@ class TestGetLlmFallbackEnvVar:):from local_deep_research.config.llm_config import get_llm- result = get_llm(provider="none", settings_snapshot=settings)- assert result is not None+ with pytest.raises(ValueError):+ get_llm(provider="none", settings_snapshot=settings)def test_fallback_env_var_with_openai_config_skips_fallback(self):"""When provider has config (openai with api_key), fallback is NOT used."""@@ -92,8 +92,8 @@ class TestGetLlmFallbackEnvVar:mock_openai_cls.assert_called_once()assert result is mock_openai_instance- def test_fallback_env_var_no_config_returns_fallback(self):- """When provider has NO config, fallback model is returned."""+ def test_fallback_env_var_no_config_raises_error(self):+ """When provider has NO config, ValueError is raised (fallback model removed)."""settings = _settings_dict({"llm.provider": "openai", "llm.openai.api_key": None})@@ -105,13 +105,11 @@ class TestGetLlmFallbackEnvVar:f"{MODULE}.get_setting_from_snapshot",side_effect=_mock_get_setting(settings),),- patch(f"{MODULE}.wrap_llm_without_think_tags") as mock_wrap,):- mock_wrap.side_effect = lambda llm, **kw: llmfrom local_deep_research.config.llm_config import get_llm- result = get_llm(provider="openai", settings_snapshot=settings)- assert isinstance(result, FakeListChatModel)+ with pytest.raises(ValueError):+ get_llm(provider="openai", settings_snapshot=settings)def test_fallback_env_var_vllm_available_skips_fallback(self):"""When provider is vllm and available, fallback is skipped."""@@ -191,8 +189,8 @@ class TestGetLlmFallbackEnvVar:with pytest.raises(ValueError, match="model path not configured"):get_llm(provider="llamacpp", settings_snapshot=settings)- def test_fallback_env_var_vllm_unavailable_returns_fallback(self):- """When provider is vllm but NOT available, early fallback path is taken."""+ def test_fallback_env_var_vllm_unavailable_raises_error(self):+ """When provider is vllm but NOT available, ValueError is raised (fallback removed)."""settings = _settings_dict({"llm.provider": "vllm"})with (patch.dict(os.environ, {"LDR_USE_FALLBACK_LLM": "1"}, clear=False),@@ -203,20 +201,18 @@ class TestGetLlmFallbackEnvVar:side_effect=_mock_get_setting(settings),),patch(f"{MODULE}.is_vllm_available", return_value=False),- patch(f"{MODULE}.wrap_llm_without_think_tags") as mock_wrap,):- mock_wrap.side_effect = lambda llm, **kw: llmfrom local_deep_research.config.llm_config import get_llm- result = get_llm(provider="vllm", settings_snapshot=settings)- assert isinstance(result, FakeListChatModel)+ with pytest.raises(ValueError):+ get_llm(provider="vllm", settings_snapshot=settings)class TestGetLlmVllmImportException:"""Tests for the vllm provider import/creation exception path."""- def test_vllm_import_exception_returns_fallback(self):- """When VLLM class import raises, fallback is returned."""+ def test_vllm_import_exception_raises_error(self):+ """When VLLM class import raises, exception is propagated (fallback removed)."""settings = _settings_dict({"llm.provider": "vllm"})broken_module = MagicMock()type(broken_module).VLLM = property(@@ -235,8 +231,8 @@ class TestGetLlmVllmImportException:):from local_deep_research.config.llm_config import get_llm- result = get_llm(provider="vllm", settings_snapshot=settings)- assert isinstance(result, FakeListChatModel)+ with pytest.raises((ImportError, ValueError)):+ get_llm(provider="vllm", settings_snapshot=settings)class TestGetLlmOllamaEdgeCases:@@ -254,8 +250,8 @@ class TestGetLlmOllamaEdgeCases:s.update(overrides)return s- def test_ollama_model_not_found_returns_fallback(self):- """When model is not in the Ollama model list, fallback is returned."""+ def test_ollama_model_not_found_raises_error(self):+ """When model is not in the Ollama model list, ValueError is raised (fallback removed)."""settings = self._ollama_settings()mock_response = MagicMock()mock_response.status_code = 200@@ -273,15 +269,15 @@ class TestGetLlmOllamaEdgeCases:):from local_deep_research.config.llm_config import get_llm- result = get_llm(- provider="ollama",- model_name="nonexistent-model",- settings_snapshot=settings,- )- assert isinstance(result, FakeListChatModel)+ with pytest.raises(ValueError, match="not found in Ollama"):+ get_llm(+ provider="ollama",+ model_name="nonexistent-model",+ settings_snapshot=settings,+ )- def test_ollama_creation_exception_returns_fallback(self):- """When ChatOllama() raises, fallback is returned."""+ def test_ollama_creation_exception_raises_error(self):+ """When ChatOllama() raises, exception is propagated (fallback removed)."""settings = self._ollama_settings()mock_response = MagicMock()mock_response.status_code = 200@@ -301,12 +297,12 @@ class TestGetLlmOllamaEdgeCases:):from local_deep_research.config.llm_config import get_llm- result = get_llm(- provider="ollama",- model_name="test-model",- settings_snapshot=settings,- )- assert isinstance(result, FakeListChatModel)+ with pytest.raises(RuntimeError, match="failed to init"):+ get_llm(+ provider="ollama",+ model_name="test-model",+ settings_snapshot=settings,+ )def test_ollama_enable_thinking_true_sets_reasoning(self):"""When enable_thinking is True, reasoning=True is passed to ChatOllama."""diff --git a/tests/config/test_thread_settings.py b/tests/config/test_thread_settings.pyindex d330f6973c..98b49d14e6 100644--- a/tests/config/test_thread_settings.py+++ b/tests/config/test_thread_settings.py@@ -131,27 +131,6 @@ class TestGetSettingFromSnapshot:result = get_setting_from_snapshot("test.key")assert result == "extracted_value"- def test_returns_default_with_fallback_llm_env(- self, clean_thread_local, monkeypatch- ):- """Should return default when LDR_USE_FALLBACK_LLM is set."""- monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "true")- monkeypatch.delenv("LDR_TESTING_WITH_MOCKS", raising=False)- result = get_setting_from_snapshot(- "test.key", default="fallback_default", check_fallback_llm=True- )- assert result == "fallback_default"-- def test_ignores_fallback_when_testing_with_mocks(- self, clean_thread_local, monkeypatch- ):- """Should not use fallback when LDR_TESTING_WITH_MOCKS is set."""- monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "true")- monkeypatch.setenv("LDR_TESTING_WITH_MOCKS", "true")- # Should raise because no context and no default- with pytest.raises(NoSettingsContextError):- get_setting_from_snapshot("test.key", check_fallback_llm=True)-def test_raises_when_no_context_and_no_default(self, clean_thread_local):"""Should raise NoSettingsContextError when no context and no default."""with pytest.raises(NoSettingsContextError) as exc_info:diff --git a/tests/config/test_thread_settings_child_keys.py b/tests/config/test_thread_settings_child_keys.pyindex 8d8aa486b6..f975a9a185 100644--- a/tests/config/test_thread_settings_child_keys.py+++ b/tests/config/test_thread_settings_child_keys.py@@ -8,7 +8,6 @@ Tests cover:- Multiple child keys- NoSettingsContextError when no default and no match- Default returned when key missing-- Interaction with check_fallback_llm"""import pytest@@ -192,42 +191,3 @@ class TestGetSettingFromSnapshotDefaults:"key", default="fallback", settings_snapshot=None)assert result == "fallback"---class TestGetSettingFromSnapshotFallbackLlm:- """Tests for check_fallback_llm behavior."""-- def test_fallback_llm_env_returns_default(self, monkeypatch):- """With LDR_USE_FALLBACK_LLM set, returns default."""- monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "1")- monkeypatch.delenv("LDR_TESTING_WITH_MOCKS", raising=False)-- from local_deep_research.config.thread_settings import (- get_setting_from_snapshot,- )-- result = get_setting_from_snapshot(- "missing",- default="fallback_val",- settings_snapshot={"other": "x"},- check_fallback_llm=True,- )- assert result == "fallback_val"-- def test_testing_with_mocks_skips_fallback(self, monkeypatch):- """With both LDR_USE_FALLBACK_LLM and LDR_TESTING_WITH_MOCKS, doesn't use fallback path."""- monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "1")- monkeypatch.setenv("LDR_TESTING_WITH_MOCKS", "1")-- from local_deep_research.config.thread_settings import (- get_setting_from_snapshot,- )-- # Should not short-circuit to fallback — should return default via normal path- result = get_setting_from_snapshot(- "missing",- default="normal_default",- settings_snapshot={"other": "x"},- check_fallback_llm=True,- )- assert result == "normal_default"diff --git a/tests/config/test_thread_settings_extended.py b/tests/config/test_thread_settings_extended.pyindex 74720a374e..f830a7a4fb 100644--- a/tests/config/test_thread_settings_extended.py+++ b/tests/config/test_thread_settings_extended.py@@ -1,8 +1,7 @@"""Extended tests for the thread_settings module.Covers thread-context management, get_setting_from_snapshot logic,-get_llm_setting_from_snapshot delegation, and get_bool_setting_from_snapshot-boolean conversion.+and get_bool_setting_from_snapshot boolean conversion."""import threading@@ -14,7 +13,6 @@ from local_deep_research.config.thread_settings import (NoSettingsContextError,clear_settings_context,get_bool_setting_from_snapshot,- get_llm_setting_from_snapshot,get_setting_from_snapshot,get_settings_context,set_settings_context,@@ -280,107 +278,6 @@ class TestGetSettingFromSnapshotDefaults:get_setting_from_snapshot("missing", default=None)-class TestGetSettingFromSnapshotFallbackLLM:- """Tests for check_fallback_llm behaviour."""-- def test_fallback_llm_env_returns_default(- self, clean_thread_local, monkeypatch- ):- """When LDR_USE_FALLBACK_LLM is set and check_fallback_llm=True,- the default is returned."""- monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "1")- monkeypatch.delenv("LDR_TESTING_WITH_MOCKS", raising=False)- result = get_setting_from_snapshot(- "llm.key", default="fb_default", check_fallback_llm=True- )- assert result == "fb_default"-- def test_fallback_llm_env_returns_none_default(- self, clean_thread_local, monkeypatch- ):- """Even None default is returned when fallback LLM env is set."""- monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "yes")- monkeypatch.delenv("LDR_TESTING_WITH_MOCKS", raising=False)- result = get_setting_from_snapshot(- "llm.key", default=None, check_fallback_llm=True- )- assert result is None-- def test_testing_with_mocks_skips_fallback(- self, clean_thread_local, monkeypatch- ):- """When LDR_TESTING_WITH_MOCKS is also set, the fallback path is- skipped."""- monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "1")- monkeypatch.setenv("LDR_TESTING_WITH_MOCKS", "1")- # No context and no default -> should raise- with pytest.raises(NoSettingsContextError):- get_setting_from_snapshot("llm.key", check_fallback_llm=True)-- def test_check_fallback_false_ignores_env(- self, clean_thread_local, monkeypatch- ):- """When check_fallback_llm=False, the env var is irrelevant."""- monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "1")- monkeypatch.delenv("LDR_TESTING_WITH_MOCKS", raising=False)- # check_fallback_llm defaults to False, so default path runs instead- result = get_setting_from_snapshot("key", default="normal_default")- assert result == "normal_default"-- def test_snapshot_value_takes_precedence_over_fallback(- self, clean_thread_local, monkeypatch- ):- """Even with fallback env set, a snapshot hit returns the snapshot value."""- monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "1")- monkeypatch.delenv("LDR_TESTING_WITH_MOCKS", raising=False)- snapshot = {"key": "snap_val"}- result = get_setting_from_snapshot(- "key",- default="fb_default",- settings_snapshot=snapshot,- check_fallback_llm=True,- )- assert result == "snap_val"---# ----------------------------------------------------------------------------# get_llm_setting_from_snapshot-# ------------------------------------------------------------------------------class TestGetLlmSettingFromSnapshot:- """Tests for the get_llm_setting_from_snapshot convenience wrapper."""-- def test_delegates_with_check_fallback_llm_true(self, clean_thread_local):- """Should call get_setting_from_snapshot with check_fallback_llm=True."""- with patch(- "local_deep_research.config.thread_settings.get_setting_from_snapshot"- ) as mock_gs:- mock_gs.return_value = "result"- result = get_llm_setting_from_snapshot(- "llm.model",- default="gpt-4",- username="user1",- settings_snapshot={"llm.model": "gpt-3.5"},- )- mock_gs.assert_called_once_with(- "llm.model",- "gpt-4",- "user1",- {"llm.model": "gpt-3.5"},- check_fallback_llm=True,- )- assert result == "result"-- def test_returns_expected_value_from_snapshot(self, clean_thread_local):- """End-to-end: returns value from snapshot dict."""- snapshot = {"llm.model": "claude-3"}- result = get_llm_setting_from_snapshot(- "llm.model", settings_snapshot=snapshot- )- assert result == "claude-3"--# ---------------------------------------------------------------------------# get_bool_setting_from_snapshot# ---------------------------------------------------------------------------@@ -460,17 +357,3 @@ class TestGetBoolSettingFromSnapshot:get_bool_setting_from_snapshot("flag", settings_snapshot=snapshot)is False)-- def test_check_fallback_llm_passed_through(- self, clean_thread_local, monkeypatch- ):- """The check_fallback_llm flag is forwarded to get_setting_from_snapshot."""- monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "1")- monkeypatch.delenv("LDR_TESTING_WITH_MOCKS", raising=False)- result = get_bool_setting_from_snapshot(- "missing_key",- default=True,- check_fallback_llm=True,- )- # Fallback path returns the default (True), then to_bool(True, True) -> True- assert result is Truediff --git a/tests/config/test_thread_settings_high_value.py b/tests/config/test_thread_settings_high_value.pyindex ab68ad8a26..28d78c1a90 100644--- a/tests/config/test_thread_settings_high_value.py+++ b/tests/config/test_thread_settings_high_value.py@@ -1,14 +1,12 @@"""High-value tests for config/thread_settings.py pure logic."""-import osimport unittest-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMockfrom local_deep_research.config.thread_settings import (NoSettingsContextError,clear_settings_context,get_bool_setting_from_snapshot,- get_llm_setting_from_snapshot,get_setting_from_snapshot,get_settings_context,set_settings_context,@@ -114,25 +112,6 @@ class TestGetSettingFromSnapshot(unittest.TestCase):with self.assertRaises(NoSettingsContextError):get_setting_from_snapshot("missing")- @patch.dict(- os.environ, {"LDR_USE_FALLBACK_LLM": "1", "LDR_TESTING_WITH_MOCKS": ""}- )- def test_fallback_llm_returns_default(self):- clear_settings_context()- result = get_setting_from_snapshot(- "key", default="fb_default", check_fallback_llm=True- )- assert result == "fb_default"-- @patch.dict(- os.environ, {"LDR_USE_FALLBACK_LLM": "1", "LDR_TESTING_WITH_MOCKS": "1"}- )- def test_fallback_llm_skipped_with_mocks(self):- clear_settings_context()- # With mocks set, fallback LLM check is skipped — no default means raises- with self.assertRaises(NoSettingsContextError):- get_setting_from_snapshot("key", check_fallback_llm=True)-def test_snapshot_takes_priority_over_context(self):ctx = MagicMock()ctx.get_setting.return_value = "from_context"@@ -183,25 +162,17 @@ class TestGetBoolSettingFromSnapshot(unittest.TestCase):assert result is True-class TestGetLlmSettingFromSnapshot(unittest.TestCase):+class TestGetSettingFromSnapshotExtra(unittest.TestCase):def tearDown(self):clear_settings_context()def test_basic_retrieval(self):snapshot = {"llm_key": "model_name"}- result = get_llm_setting_from_snapshot(+ result = get_setting_from_snapshot("llm_key", settings_snapshot=snapshot)assert result == "model_name"- @patch.dict(- os.environ, {"LDR_USE_FALLBACK_LLM": "1", "LDR_TESTING_WITH_MOCKS": ""}- )- def test_fallback_llm_enabled(self):- clear_settings_context()- result = get_llm_setting_from_snapshot("key", default="default_model")- assert result == "default_model"-if __name__ == "__main__":unittest.main()diff --git a/tests/conftest.py b/tests/conftest.pyindex b88891d633..c0746262b9 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -153,9 +153,8 @@ def pytest_configure(config):"""Configure pytest with custom markers."""config.addinivalue_line("markers",- "requires_llm: mark test as requiring a real LLM (not fallback)",+ "requires_llm: mark test as requiring a real LLM (skipped when LDR_TESTING_WITH_MOCKS=true)",)-# In CI, LDR_TESTING_WITH_MOCKS is set via Docker environment variables# For local testing, set it here if not already setif not os.environ.get("LDR_TESTING_WITH_MOCKS"):@@ -163,13 +162,9 @@ def pytest_configure(config):@pytest.fixture(autouse=True)-def skip_if_using_fallback_llm(request):- """Skip tests marked with @pytest.mark.requires_llm when no real LLM is available."""+def skip_if_no_real_llm(request):+ """Skip tests marked with @pytest.mark.requires_llm when running with mocks."""if request.node.get_closest_marker("requires_llm"):- # Skip if using fallback LLM- if os.environ.get("LDR_USE_FALLBACK_LLM", ""):- pytest.skip("Test requires real LLM but using fallback")- # Skip if running with mocks (default for CI and normal test runs)if os.environ.get("LDR_TESTING_WITH_MOCKS", "").lower() == "true":pytest.skip("Test requires real LLM but running with mocks")@@ -219,10 +214,8 @@ def app(temp_data_dir, monkeypatch):# Override data directorymonkeypatch.setenv("LDR_DATA_DIR", str(temp_data_dir))- # Use fallback LLM for tests# Note: PYTEST_CURRENT_TEST is automatically set by pytest, which# app_factory.py checks to disable secure cookies for testing- monkeypatch.setenv("LDR_USE_FALLBACK_LLM", "1")# Create app with testing configapp, _ = create_app()diff --git a/tests/feature_tests/test_custom_context.py b/tests/feature_tests/test_custom_context.pyindex 39aa9fea4a..ee0b9c57c0 100644--- a/tests/feature_tests/test_custom_context.py+++ b/tests/feature_tests/test_custom_context.py@@ -34,7 +34,6 @@ def patch_db_setting():default=None,username=None,settings_snapshot=None,- check_fallback_llm=False,) -> Any:"""Override specific settings for testing.diff --git a/tests/llm_providers/implementations/test_lmstudio_provider.py b/tests/llm_providers/implementations/test_lmstudio_provider.pyindex c248c2dad8..b799fef2d2 100644--- a/tests/llm_providers/implementations/test_lmstudio_provider.py+++ b/tests/llm_providers/implementations/test_lmstudio_provider.py@@ -14,9 +14,8 @@ def _make_setting_side_effect(url_value):"""Create a side_effect function that returns url_value for llm.lmstudio.urland default for everything else.- Uses *args, **kwargs to handle variable call patterns from both- get_setting_from_snapshot and get_llm_setting_from_snapshot (which delegates- to get_setting_from_snapshot with extra positional args).+ Uses *args, **kwargs to handle variable call patterns from+ get_setting_from_snapshot."""def _setting_side_effect(*args, **kwargs):diff --git a/tests/run_all_tests.py b/tests/run_all_tests.pyindex c2afb04302..abef0b0532 100755--- a/tests/run_all_tests.py+++ b/tests/run_all_tests.py@@ -389,9 +389,6 @@ class TestRunner:)self.log(f"Python path: {sys.executable}")self.log(f"Working directory: {os.getcwd()}")- self.log(- f"LDR_USE_FALLBACK_LLM: {os.environ.get('LDR_USE_FALLBACK_LLM')}"- )return self.run_command(pytest_args,diff --git a/tests/search_engines/test_rate_limiter.py b/tests/search_engines/test_rate_limiter.pyindex fdd04b0302..c40b661bd4 100644--- a/tests/search_engines/test_rate_limiter.py+++ b/tests/search_engines/test_rate_limiter.py@@ -129,12 +129,8 @@ class TestAdaptiveRateLimitTrackerEnabled:mock_get.side_effect = NoSettingsContextError()- with patch(- "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",- return_value=False,- ):- tracker = AdaptiveRateLimitTracker(programmatic_mode=False)- assert tracker.enabled is True+ tracker = AdaptiveRateLimitTracker(programmatic_mode=False)+ assert tracker.enabled is Truedef test_disabled_by_default_in_programmatic_mode(self):"""Disabled by default in programmatic mode."""@@ -199,25 +195,22 @@ class TestAdaptiveRateLimitTrackerDatabaseSkip:# Should not attempt to get database importsassert tracker._estimates_loaded is True- def test_load_estimates_skipped_in_fallback_mode(self):- """_load_estimates skips database in fallback mode."""+ def test_load_estimates_deferred_in_non_programmatic_mode(self):+ """_load_estimates defers loading in non-programmatic mode."""with patch(- "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",- return_value=True,- ):- with patch(- "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"- ) as mock_get:- from local_deep_research.config.thread_settings import (- NoSettingsContextError,- )+ "local_deep_research.web_search_engines.rate_limiting.tracker.get_setting_from_snapshot"+ ) as mock_get:+ from local_deep_research.config.thread_settings import (+ NoSettingsContextError,+ )- mock_get.side_effect = NoSettingsContextError()+ mock_get.side_effect = NoSettingsContextError()- tracker = AdaptiveRateLimitTracker(programmatic_mode=False)+ tracker = AdaptiveRateLimitTracker(programmatic_mode=False)- # Should skip loading- assert tracker.current_estimates == {}+ # Non-programmatic defers loading until user context is available+ assert tracker._estimates_loaded is False+ assert tracker.current_estimates == {}class TestRateLimitTrackerConstants:diff --git a/tests/settings/env_vars/test_env_auto_generation.py b/tests/settings/env_vars/test_env_auto_generation.pyindex d33eb654d3..37081b6f35 100644--- a/tests/settings/env_vars/test_env_auto_generation.py+++ b/tests/settings/env_vars/test_env_auto_generation.py@@ -174,7 +174,6 @@ class TestBackwardCompatibility:# These are the env vars that existing code might depend onexpected_mappings = [("testing.test_mode", "LDR_TESTING_TEST_MODE"),- ("testing.use_fallback_llm", "LDR_TESTING_USE_FALLBACK_LLM"),("bootstrap.encryption_key", "LDR_BOOTSTRAP_ENCRYPTION_KEY"),("bootstrap.database_url", "LDR_BOOTSTRAP_DATABASE_URL"),("bootstrap.data_dir", "LDR_BOOTSTRAP_DATA_DIR"),diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.jsonindex 92e8b2d998..990c0da056 100644--- a/tests/settings/golden_master_settings.json+++ b/tests/settings/golden_master_settings.json@@ -296,11 +296,11 @@"value": "rose"},{- "label": "Ros\u00e9 Pine",+ "label": "Rosé Pine","value": "rose-pine"},{- "label": "Ros\u00e9 Pine Dawn",+ "label": "Rosé Pine Dawn","value": "rose-pine-dawn"},{@@ -641,7 +641,7 @@},"focused_iteration.knowledge_summary_limit": {"category": "focused_iteration",- "description": "Limits the number of top search results included in the knowledge summary shown to the LLM during question generation. Set to 10 to show only the top 10 results, reducing token usage. Set to 0 for unlimited. Note: This only affects question generation prompts \u2014 final answer synthesis always uses all results.",+ "description": "Limits the number of top search results included in the knowledge summary shown to the LLM during question generation. Set to 10 to show only the top 10 results, reducing token usage. Set to 0 for unlimited. Note: This only affects question generation prompts — final answer synthesis always uses all results.","editable": true,"max_value": 100,"min_value": 0,@@ -669,7 +669,7 @@},"focused_iteration.prompt_knowledge_truncate": {"category": "focused_iteration",- "description": "Maximum characters of accumulated knowledge to include in the LLM prompt for follow-up question generation. Applied after 'Results Shown for Question Generation' selects the top N results \u2014 this further truncates that combined text to a character limit. Set to 0 for unlimited.",+ "description": "Maximum characters of accumulated knowledge to include in the LLM prompt for follow-up question generation. Applied after 'Results Shown for Question Generation' selects the top N results — this further truncates that combined text to a character limit. Set to 0 for unlimited.","editable": true,"max_value": 10000,"min_value": 0,@@ -683,7 +683,7 @@},"focused_iteration.question_generator": {"category": "focused_iteration",- "description": "Algorithm for generating follow-up search queries. 'browsecomp' (default): Systematically extracts and combines entities (names, dates, locations) for predictable, focused searches. 'flexible': Allows the LLM more freedom to explore diverse search strategies \u2014 less rigid but may be less consistent.",+ "description": "Algorithm for generating follow-up search queries. 'browsecomp' (default): Systematically extracts and combines entities (names, dates, locations) for predictable, focused searches. 'flexible': Allows the LLM more freedom to explore diverse search strategies — less rigid but may be less consistent.","editable": true,"max_value": null,"min_value": null,@@ -755,7 +755,7 @@},"general.knowledge_accumulation_context_limit": {"category": null,- "description": "Maximum character count for accumulated knowledge context. Reserved for future use \u2014 not currently enforced at runtime.",+ "description": "Maximum character count for accumulated knowledge context. Reserved for future use — not currently enforced at runtime.","editable": true,"max_value": null,"min_value": null,@@ -1321,7 +1321,7 @@},"news.scheduler.enabled": {"category": "news_scheduler",- "description": "Enable the background scheduler that automatically runs news subscriptions on their configured intervals. When disabled, no automatic subscription processing occurs \u2014 subscriptions must be refreshed manually.",+ "description": "Enable the background scheduler that automatically runs news subscriptions on their configured intervals. When disabled, no automatic subscription processing occurs — subscriptions must be refreshed manually.","editable": true,"max_value": null,"min_value": null,@@ -3277,7 +3277,7 @@},"search.engine.web.github.requires_api_key": {"category": "github",- "description": "Whether GitHub requires a personal access token. Optional but recommended for higher rate limits (10\u219230 req/min).",+ "description": "Whether GitHub requires a personal access token. Optional but recommended for higher rate limits (10→30 req/min).","editable": true,"max_value": null,"min_value": null,@@ -4608,7 +4608,7 @@},"search.engine.web.parallel.default_params.allow_local_engines": {"category": "parallel",- "description": "\u26a0\ufe0f PRIVACY WARNING: Allow local/private document engines in parallel search. This may expose personal data from your documents to web search queries and LLMs. Only enable if you understand the privacy implications.",+ "description": "⚠️ PRIVACY WARNING: Allow local/private document engines in parallel search. This may expose personal data from your documents to web search queries and LLMs. Only enable if you understand the privacy implications.","editable": true,"max_value": null,"min_value": null,diff --git a/tests/settings/test_env_definitions_behavior.py b/tests/settings/test_env_definitions_behavior.pyindex e311f1eec7..ee1092c407 100644--- a/tests/settings/test_env_definitions_behavior.py+++ b/tests/settings/test_env_definitions_behavior.py@@ -534,15 +534,6 @@ class TestTestingSettings:keys = [s.key for s in TESTING_SETTINGS]assert "testing.test_mode" in keys- def test_has_fallback_llm_setting(self):- """Has use_fallback_llm setting."""- from local_deep_research.settings.env_definitions.testing import (- TESTING_SETTINGS,- )-- keys = [s.key for s in TESTING_SETTINGS]- assert "testing.use_fallback_llm" in keys-def test_ci_constant_is_bool(self):"""CI constant is a boolean."""from local_deep_research.settings.env_definitions.testing import CIdiff --git a/tests/settings/test_env_registry_behavior.py b/tests/settings/test_env_registry_behavior.pyindex 22e31df39f..39a52f0504 100644--- a/tests/settings/test_env_registry_behavior.py+++ b/tests/settings/test_env_registry_behavior.py@@ -2,7 +2,7 @@Behavioral tests for settings/env_registry module.Tests convenience functions for CI detection, test mode,-fallback LLM, and rate limiting.+and rate limiting."""import os@@ -72,24 +72,6 @@ class TestIsTestMode:is_test_mode()-class TestUseFallbackLlm:- """Tests for use_fallback_llm function."""-- def test_returns_bool(self):- """Returns a boolean."""- from local_deep_research.settings.env_registry import use_fallback_llm-- result = use_fallback_llm()- assert isinstance(result, bool)-- def test_callable_without_args(self):- """Callable without arguments."""- from local_deep_research.settings.env_registry import use_fallback_llm-- # Should not raise- use_fallback_llm()--class TestIsCiEnvironment:"""Tests for is_ci_environment function."""diff --git a/tests/settings/test_env_registry_extended.py b/tests/settings/test_env_registry_extended.pyindex f4b6ff4f55..a0ce72f937 100644--- a/tests/settings/test_env_registry_extended.py+++ b/tests/settings/test_env_registry_extended.py@@ -7,7 +7,6 @@ Tests cover:- is_ci_environment function- is_github_actions function- is_rate_limiting_enabled function-- use_fallback_llm function"""import os@@ -17,7 +16,6 @@ from local_deep_research.settings.env_registry import (registry,get_env_setting,is_test_mode,- use_fallback_llm,is_ci_environment,is_github_actions,is_rate_limiting_enabled,@@ -211,42 +209,6 @@ class TestIsGithubActionsFunction:assert is_github_actions() is False-class TestUseFallbackLlmFunction:- """Tests for use_fallback_llm convenience function."""-- @pytest.fixture(autouse=True)- def clean_env(self):- """Clean environment before each test."""- original_env = {- k: v for k, v in os.environ.items() if k.startswith("LDR_")- }- for key in list(os.environ.keys()):- if key.startswith("LDR_"):- os.environ.pop(key, None)- yield- for key in list(os.environ.keys()):- if key.startswith("LDR_"):- os.environ.pop(key, None)- for key, value in original_env.items():- os.environ[key] = value-- def test_use_fallback_llm_returns_env_value_true(self):- """Test use_fallback_llm returns True when set."""- os.environ["LDR_TESTING_USE_FALLBACK_LLM"] = "true"-- assert use_fallback_llm() is True-- def test_use_fallback_llm_returns_false_by_default(self):- """Test use_fallback_llm returns False by default."""- assert use_fallback_llm() is False-- def test_use_fallback_llm_returns_false_when_false(self):- """Test use_fallback_llm returns False when explicitly set to false."""- os.environ["LDR_TESTING_USE_FALLBACK_LLM"] = "false"-- assert use_fallback_llm() is False--class TestIsRateLimitingEnabledFunction:"""Tests for is_rate_limiting_enabled convenience function."""@@ -298,10 +260,9 @@ class TestRegistryGlobalInstance:"""Test that registry has testing category registered."""settings = registry.get_category_settings("testing")- assert len(settings) >= 2+ assert len(settings) >= 1keys = [s.key for s in settings]assert "testing.test_mode" in keys- assert "testing.use_fallback_llm" in keysdef test_registry_has_bootstrap_category(self):"""Test that registry has bootstrap category registered."""@@ -334,4 +295,3 @@ class TestRegistryGlobalInstance:testing_vars = registry.get_testing_vars()assert "LDR_TESTING_TEST_MODE" in testing_vars- assert "LDR_TESTING_USE_FALLBACK_LLM" in testing_varsdiff --git a/tests/settings/test_env_settings.py b/tests/settings/test_env_settings.pyindex 625ca28b0a..13a1cf7200 100644--- a/tests/settings/test_env_settings.py+++ b/tests/settings/test_env_settings.py@@ -8,7 +8,6 @@ from local_deep_research.settings.env_registry import (registry,get_env_setting,is_test_mode,- use_fallback_llm,is_ci_environment,)from local_deep_research.settings.manager import SettingsManager@@ -46,7 +45,6 @@ class TestEnvRegistry:all_settings = registry.list_all_settings()assert len(all_settings) > 0, "Registry should have settings"assert "testing.test_mode" in all_settings- assert "testing.use_fallback_llm" in all_settingsassert "bootstrap.encryption_key" in all_settingsassert "db_config.cache_size_mb" in all_settings@@ -78,20 +76,6 @@ class TestEnvRegistry:os.environ["LDR_TESTING_TEST_MODE"] = valueassert not is_test_mode(), f"'{value}' should be False"- def test_fallback_llm_setting(self):- """Test fallback LLM setting with defaults."""- # Test default value when not set- assert not use_fallback_llm()-- os.environ["LDR_TESTING_USE_FALLBACK_LLM"] = "1"- assert use_fallback_llm()-- os.environ["LDR_TESTING_USE_FALLBACK_LLM"] = "yes"- assert use_fallback_llm()-- os.environ.pop("LDR_TESTING_USE_FALLBACK_LLM")- assert not use_fallback_llm()-def test_ci_environment(self):"""Test CI environment detection."""assert not is_ci_environment()@@ -188,23 +172,12 @@ class TestSettingsManagerIntegration:test_mode = sm.get_setting("testing.test_mode")assert test_mode- # Test with default when env var not set- result = sm.get_setting("testing.use_fallback_llm", default=True)- assert (- not result- ) # Env setting default (False) overrides our param default-- os.environ["LDR_TESTING_USE_FALLBACK_LLM"] = "false"- result = sm.get_setting("testing.use_fallback_llm", default=True)- assert not result # Env var overrides default-def test_is_env_only_setting(self):"""Test checking if a setting is env-only."""sm = SettingsManager(db_session=None)# These should be env-onlyassert sm.is_env_only_setting("testing.test_mode")- assert sm.is_env_only_setting("testing.use_fallback_llm")assert sm.is_env_only_setting("bootstrap.encryption_key")assert sm.is_env_only_setting("db_config.cache_size_mb")@@ -243,7 +216,6 @@ class TestSettingsManagerIntegration:# Testing vars are in ALL_ENV_ONLY_VARS but not specifically bootstrap# They are allowed by the pre-commit hook but not considered bootstrap varsassert not sm.is_bootstrap_env_var("LDR_TESTING_TEST_MODE")- assert not sm.is_bootstrap_env_var("LDR_TESTING_USE_FALLBACK_LLM")# Non-existent varassert not sm.is_bootstrap_env_var("RANDOM_VAR")@@ -258,10 +230,6 @@ class TestEnvVarMapping:assert (registry.get_env_var("testing.test_mode") == "LDR_TESTING_TEST_MODE")- assert (- registry.get_env_var("testing.use_fallback_llm")- == "LDR_TESTING_USE_FALLBACK_LLM"- )assert (registry.get_env_var("bootstrap.encryption_key")== "LDR_BOOTSTRAP_ENCRYPTION_KEY"@@ -281,7 +249,6 @@ class TestEnvVarMapping:# Should include key variablesassert "LDR_TESTING_TEST_MODE" in all_env_vars- assert "LDR_TESTING_USE_FALLBACK_LLM" in all_env_varsassert "LDR_BOOTSTRAP_ENCRYPTION_KEY" in all_env_vars# CI and TESTING are external vars, not in registry anymore@@ -289,12 +256,8 @@ class TestEnvVarMapping:"""Test getting category-specific environment variables."""# Testing varstesting_vars = registry.get_testing_vars()- assert (- len(testing_vars) >= 2- ) # We only have test_mode and use_fallback_llm now+ assert len(testing_vars) >= 1assert "LDR_TESTING_TEST_MODE" in testing_vars- assert "LDR_TESTING_USE_FALLBACK_LLM" in testing_vars- # CI and TESTING are now external vars, not in the registry# Bootstrap vars (includes db_config)bootstrap_vars = registry.get_bootstrap_vars()diff --git a/tests/settings/test_settings_defaults_integrity.py b/tests/settings/test_settings_defaults_integrity.pyindex 79c5acf9d5..f9435cf0bd 100644--- a/tests/settings/test_settings_defaults_integrity.py+++ b/tests/settings/test_settings_defaults_integrity.py@@ -567,7 +567,14 @@ class TestSettingsDefaultsIntegrity:current[key] = settingcurrent_json = (- json.dumps(current, indent=2, sort_keys=True, default=str) + "\n"+ json.dumps(+ current,+ indent=2,+ sort_keys=True,+ default=str,+ ensure_ascii=False,+ )+ + "\n")if not GOLDEN_MASTER_PATH.exists():diff --git a/tests/strategies/test_iterative_reasoning.py b/tests/strategies/test_iterative_reasoning.pyindex aaa41929c8..a5e296096d 100755--- a/tests/strategies/test_iterative_reasoning.py+++ b/tests/strategies/test_iterative_reasoning.py@@ -143,7 +143,6 @@ def test_research_query():print(f"\nAnswer preview: {results.get('current_knowledge', '')[:300]}...")def demonstrate_knowledge_building():"""Show how knowledge builds up over iterations."""diff --git a/tests/test_api_key_configuration.py b/tests/test_api_key_configuration.pyindex 109b85cdfd..39ada2a4ab 100644--- a/tests/test_api_key_configuration.py+++ b/tests/test_api_key_configuration.py@@ -3,7 +3,6 @@ Tests for API key configuration and LLM execution.Tests that API keys can be set and used properly for different LLM providers."""-import osimport pytestfrom unittest.mock import Mock, patch@@ -16,12 +15,6 @@ from local_deep_research.config.llm_config import (from local_deep_research.llm import clear_llm_registryfrom local_deep_research.settings import SettingsManager-# Skip all tests in this module when using fallback LLM-pytestmark = pytest.mark.skipif(- os.environ.get("LDR_USE_FALLBACK_LLM", "") == "true",- reason="These tests require real LLM providers, not fallback",-)-@pytest.fixture(autouse=True)def _clear_provider_registry():@@ -257,28 +250,6 @@ class TestAPIKeyConfiguration:== "https://openrouter.ai/api/v1")- def test_missing_api_key_fallback(self):- """Test that missing API key falls back to fallback model."""- settings_snapshot = self._get_base_settings()- settings_snapshot.update(- {- "llm.provider": "openai",- "llm.model": "gpt-4",- "llm.temperature": 0.7,- "llm.openai.api_key": "", # No API key- }- )-- with patch(- "local_deep_research.config.llm_config.get_fallback_model"- ) as mock_fallback:- mock_fallback.return_value = Mock()-- get_llm(settings_snapshot=settings_snapshot)-- # Should have fallen back to fallback model- mock_fallback.assert_called_once()-def test_research_with_api_configured_llm(self, settings_snapshot_with_openai_endpoint):diff --git a/tests/test_ci_config.py b/tests/test_ci_config.pyindex 1f68850e67..ee0aa23771 100644--- a/tests/test_ci_config.py+++ b/tests/test_ci_config.py@@ -7,7 +7,6 @@ import os# Set environment variables for CI testingos.environ["LDR_TESTING_MODE"] = "true"-os.environ["LDR_USE_FALLBACK_LLM"] = "true"# Disable all external LLM providersos.environ["LDR_DISABLE_OLLAMA"] = "true"diff --git a/tests/test_llm/run_llm_tests.sh b/tests/test_llm/run_llm_tests.shindex 67a0a9b9af..1651c993b6 100755--- a/tests/test_llm/run_llm_tests.sh+++ b/tests/test_llm/run_llm_tests.sh@@ -7,7 +7,6 @@ echo "============================="# Set up environmentPYTHONPATH="${PYTHONPATH}:$(pwd)"export PYTHONPATH-export LDR_USE_FALLBACK_LLM=true# Run registry testsecho -e "\n1. Running LLM Registry Tests..."diff --git a/tests/test_llm/test_llm_integration.py b/tests/test_llm/test_llm_integration.pyindex fb8672ada9..b998a48b99 100644--- a/tests/test_llm/test_llm_integration.py+++ b/tests/test_llm/test_llm_integration.py@@ -134,31 +134,6 @@ def test_get_llm_with_factory_function(full_settings_snapshot):assert factory_calls[0]["temperature"] == 0.3-def test_get_llm_falls_back_to_builtin(full_settings_snapshot):- """Test that get_llm falls back to built-in providers when custom not found."""- # Don't register any custom LLM-- # Mock the built-in provider check- with patch(- "local_deep_research.config.llm_config.is_ollama_available",- return_value=False,- ):- with patch(- "local_deep_research.config.llm_config.get_fallback_model"- ) as mock_fallback:- mock_fallback.return_value = TestLLM(response_text="Fallback")-- # Try to get Ollama (which is not available)- get_llm(- provider="ollama",- model_name="llama2",- settings_snapshot=full_settings_snapshot,- )-- # Should fall back- assert mock_fallback.called--def test_api_integration_with_custom_llm():"""Test that API functions work with custom LLMs."""from local_deep_research.api import quick_summary@@ -267,9 +242,6 @@ def test_invalid_provider_after_checking_registry("""Test that invalid provider error is raised for non-existent providers."""# Don't register anything- # Ensure LDR_USE_FALLBACK_LLM is not set for this test- monkeypatch.delenv("LDR_USE_FALLBACK_LLM", raising=False)-with pytest.raises(ValueError, match="Invalid provider: fake_provider"):get_llm(provider="fake_provider", settings_snapshot=full_settings_snapshotdiff --git a/tests/test_llm_provider_integration.py b/tests/test_llm_provider_integration.pyindex bd0bd4a664..44097b5c13 100644--- a/tests/test_llm_provider_integration.py+++ b/tests/test_llm_provider_integration.py@@ -3,17 +3,10 @@ Integration tests for LLM provider configuration and execution.Tests the full flow from API key configuration to research execution."""-import osimport pytestfrom unittest.mock import Mock, patchfrom local_deep_research.settings import SettingsManager-# Skip all tests in this module when using fallback LLM-pytestmark = pytest.mark.skipif(- os.environ.get("LDR_USE_FALLBACK_LLM", "") == "true",- reason="These tests require real LLM providers, not fallback",-)-class TestLLMProviderIntegration:"""Test complete LLM provider integration scenarios."""@@ -336,6 +329,7 @@ class TestLLMProviderIntegration:is False)+ @pytest.mark.requires_llmdef test_custom_model_configuration(self, mock_session):"""Test configuring custom models with API endpoints."""with patch.object(diff --git a/tests/test_openai_api_key_usage.py b/tests/test_openai_api_key_usage.pyindex 82e81ebdaf..66becf86c0 100644--- a/tests/test_openai_api_key_usage.py+++ b/tests/test_openai_api_key_usage.py@@ -13,46 +13,39 @@ import osfrom local_deep_research.config.llm_config import get_llm-# Skip all tests in this module when using fallback LLM-pytestmark = pytest.mark.skipif(- os.environ.get("LDR_USE_FALLBACK_LLM", "") == "true",- reason="These tests require real LLM providers, not fallback",-)-class TestOpenAIAPIKeyUsage:"""Test OpenAI API key configuration and usage throughout the system."""@pytest.fixturedef openai_settings_snapshot(self):- """Create settings snapshot with OpenAI configuration."""+ """Create settings snapshot with OpenAI configuration.++ Uses simplified format (raw values) to bypass get_typed_setting_value+ type coercion in get_setting_from_snapshot().+ """return {- "llm.provider": {"value": "openai", "type": "str"},- "llm.model": {"value": "gpt-3.5-turbo", "type": "str"},- "llm.temperature": {"value": 0.7, "type": "float"},- "llm.openai.api_key": {- "value": "sk-test-1234567890abcdef",- "type": "str",- },- "llm.openai.api_base": {"value": None, "type": "str"},- "llm.openai.organization": {"value": None, "type": "str"},- "llm.streaming": {"value": None, "type": "bool"},- "llm.max_retries": {"value": None, "type": "int"},- "llm.request_timeout": {"value": None, "type": "int"},- "llm.context_window_unrestricted": {"value": False, "type": "bool"},- "llm.context_window_size": {"value": 128000, "type": "int"},- "llm.supports_max_tokens": {"value": True, "type": "bool"},- "llm.max_tokens": {"value": 100000, "type": "int"},- "llm.provider.openai.context_window": {- "value": 4096,- "type": "int",- },- "research.iterations": {"value": 2, "type": "int"},- "research.questions_per_iteration": {"value": 3, "type": "int"},- "research.search_engines": {"value": ["wikipedia"], "type": "list"},- "research.local_context": {"value": 2000, "type": "int"},- "research.web_context": {"value": 2000, "type": "int"},- "rate_limiting.llm_enabled": {"value": False, "type": "bool"},+ "llm.provider": "openai",+ "llm.model": "gpt-3.5-turbo",+ "llm.temperature": 0.7,+ "llm.openai.api_key": "sk-test-1234567890abcdef",+ "llm.openai.api_base": None,+ "llm.openai.organization": None,+ "llm.streaming": None,+ "llm.max_retries": None,+ "llm.request_timeout": None,+ "llm.context_window_unrestricted": False,+ "llm.context_window_size": 128000,+ "llm.supports_max_tokens": True,+ "llm.max_tokens": 100000,+ "llm.provider.openai.context_window": 4096,+ "research.iterations": 2,+ "research.questions_per_iteration": 3,+ "research.search_engines": ["wikipedia"],+ "research.local_context": 2000,+ "research.web_context": 2000,+ "rate_limiting.llm_enabled": False,}def test_openai_api_key_in_llm_config(self, openai_settings_snapshot):@@ -87,7 +80,7 @@ class TestOpenAIAPIKeyUsage:"""Test fallback to environment variable if API key not in settings."""# Modify settings to have no API keysettings_no_key = openai_settings_snapshot.copy()- settings_no_key["llm.openai.api_key"] = {"value": None, "type": "str"}+ settings_no_key["llm.openai.api_key"] = None# Set LDR-prefixed environment variablewith patch.dict(@@ -135,14 +128,10 @@ class TestOpenAIAPIKeyUsage:"""Test OpenAI with custom API endpoint (e.g., Azure OpenAI)."""# Add custom endpoint to settingscustom_settings = openai_settings_snapshot.copy()- custom_settings["llm.openai.api_base"] = {- "value": "https://custom-openai.azure.com",- "type": "str",- }- custom_settings["llm.openai.api_key"] = {- "value": "custom-azure-key",- "type": "str",- }+ custom_settings["llm.openai.api_base"] = (+ "https://custom-openai.azure.com"+ )+ custom_settings["llm.openai.api_key"] = "custom-azure-key"with patch("local_deep_research.config.llm_config.ChatOpenAI"@@ -185,7 +174,7 @@ class TestOpenAIAPIKeyUsage:for model in models_to_test:settings = openai_settings_snapshot.copy()- settings["llm.model"] = {"value": model, "type": "str"}+ settings["llm.model"] = modelwith patch("local_deep_research.config.llm_config.ChatOpenAI"@@ -202,7 +191,7 @@ class TestOpenAIAPIKeyUsage:"""Test OpenAI streaming configuration."""# Add streaming settingstreaming_settings = openai_settings_snapshot.copy()- streaming_settings["llm.streaming"] = {"value": True, "type": "bool"}+ streaming_settings["llm.streaming"] = Truewith patch("local_deep_research.config.llm_config.ChatOpenAI"@@ -219,8 +208,8 @@ class TestOpenAIAPIKeyUsage:"""Test OpenAI retry and timeout configuration."""# Add retry settingsretry_settings = openai_settings_snapshot.copy()- retry_settings["llm.max_retries"] = {"value": 3, "type": "int"}- retry_settings["llm.request_timeout"] = {"value": 60, "type": "int"}+ retry_settings["llm.max_retries"] = 3+ retry_settings["llm.request_timeout"] = 60with patch("local_deep_research.config.llm_config.ChatOpenAI"@@ -239,10 +228,7 @@ class TestOpenAIAPIKeyUsage:"""Test OpenAI organization ID configuration."""# Add organization IDorg_settings = openai_settings_snapshot.copy()- org_settings["llm.openai.organization"] = {- "value": "org-test123",- "type": "str",- }+ org_settings["llm.openai.organization"] = "org-test123"with patch("local_deep_research.config.llm_config.ChatOpenAI"@@ -262,13 +248,10 @@ class TestOpenAIAPIKeyUsage:"""Full integration test verifying all OpenAI configuration parameters."""# Test full OpenAI configurationfull_settings = openai_settings_snapshot.copy()- full_settings["llm.streaming"] = {"value": True, "type": "bool"}- full_settings["llm.max_retries"] = {"value": 5, "type": "int"}- full_settings["llm.request_timeout"] = {"value": 120, "type": "int"}- full_settings["llm.openai.organization"] = {- "value": "org-123",- "type": "str",- }+ full_settings["llm.streaming"] = True+ full_settings["llm.max_retries"] = 5+ full_settings["llm.request_timeout"] = 120+ full_settings["llm.openai.organization"] = "org-123"with patch("local_deep_research.config.llm_config.ChatOpenAI"diff --git a/tests/test_search_system.py b/tests/test_search_system.pyindex 6f3cc35a3d..0b6f9ffa97 100644--- a/tests/test_search_system.py+++ b/tests/test_search_system.py@@ -1,4 +1,3 @@-import osimport sysfrom pathlib import Pathfrom unittest.mock import Mock@@ -8,12 +7,6 @@ import pytest# Handle import paths for testingsys.path.append(str(Path(__file__).parent.parent))-# Skip all tests in this module when using fallback LLM-pytestmark = pytest.mark.skipif(- os.environ.get("LDR_USE_FALLBACK_LLM", "") == "true",- reason="These tests require real LLM providers, not fallback",-)-@pytest.fixturedef mock_llm():@@ -50,6 +43,7 @@ def mock_strategy():return mockdef test_progress_callback_forwarding(monkeypatch, mock_search, mock_llm):"""Test that progress callbacks are properly forwarded to the strategy."""# Create a mock strategy class and instance@@ -319,6 +313,7 @@ def test_set_progress_callback(monkeypatch):assert system.strategy.progress_callback == mock_callbackdef test_analyze_topic(monkeypatch):"""Test analyzing a topic."""# Set up mock LLM and searchdiff --git a/tests/ui_tests/test_direct_mode.js b/tests/ui_tests/test_direct_mode.jsindex da8521eae7..2ae9e3aa88 100644--- a/tests/ui_tests/test_direct_mode.js+++ b/tests/ui_tests/test_direct_mode.js@@ -23,7 +23,7 @@ async function submitResearchBatch(page, queries) {// NOTE: We use setupDefaultModel() instead of hardcoding a model name because:// 1. In CI, no real OLLAMA models are available (0 models filtered)// 2. model_helper.js sets both #model and #model_hidden inputs correctly- // 3. The fallback LLM (LDR_USE_FALLBACK_LLM=true) needs proper model config+ // 3. The test environment needs proper model config// Without this, research submission fails with "no model selected"try {await setupDefaultModel(page);diff --git a/tests/unit/test_boolean_settings.py b/tests/unit/test_boolean_settings.pyindex 75489132df..ed644526c2 100644--- a/tests/unit/test_boolean_settings.py+++ b/tests/unit/test_boolean_settings.py@@ -420,17 +420,6 @@ class TestGetBoolSettingFromSnapshot:)assert result is True- def test_check_fallback_llm_parameter(self):- """Test that check_fallback_llm parameter is accepted."""- snapshot = {"test.setting": "yes"}- # Should not raise an error- result = get_bool_setting_from_snapshot(- "test.setting",- settings_snapshot=snapshot,- check_fallback_llm=True,- )- assert result is True-class TestSettingsManagerGetBoolSetting:"""Test the get_bool_setting() method on SettingsManager."""diff --git a/tests/utilities/test_db_utils.py b/tests/utilities/test_db_utils.pyindex e9769f9149..2ad4b0c610 100644--- a/tests/utilities/test_db_utils.py+++ b/tests/utilities/test_db_utils.py@@ -249,22 +249,6 @@ class TestNoDbSettings:class TestGetSettingFromDbMainThread:"""Tests for get_setting_from_db_main_thread function."""- def test_returns_default_in_fallback_mode(self):- """Should return default value when in fallback LLM mode."""- from local_deep_research.utilities.db_utils import (- get_setting_from_db_main_thread,- )-- with patch(- "local_deep_research.utilities.db_utils.use_fallback_llm",- return_value=True,- ):- result = get_setting_from_db_main_thread(- "test.key", default_value="default"- )-- assert result == "default"-def test_raises_error_from_background_thread(self):"""Should raise error when called from background thread."""from local_deep_research.utilities.db_utils import (@@ -275,11 +259,7 @@ class TestGetSettingFromDbMainThread:def background_task():try:- with patch(- "local_deep_research.utilities.db_utils.use_fallback_llm",- return_value=False,- ):- get_setting_from_db_main_thread("test.key")+ get_setting_from_db_main_thread("test.key")except RuntimeError:error_raised[0] = True@@ -298,27 +278,23 @@ class TestGetSettingFromDbMainThread:)with patch(- "local_deep_research.utilities.db_utils.use_fallback_llm",- return_value=False,+ "local_deep_research.utilities.db_utils.has_app_context",+ return_value=True,):+ # Simulate get_user_db_session returning Nonewith patch(- "local_deep_research.utilities.db_utils.has_app_context",- return_value=True,- ):- # Simulate get_user_db_session returning None- with patch(- "local_deep_research.database.session_context.get_user_db_session"- ) as mock_context:- mock_cm = MagicMock()- mock_cm.__enter__ = Mock(return_value=None)- mock_cm.__exit__ = Mock(return_value=None)- mock_context.return_value = mock_cm+ "local_deep_research.database.session_context.get_user_db_session"+ ) as mock_context:+ mock_cm = MagicMock()+ mock_cm.__enter__ = Mock(return_value=None)+ mock_cm.__exit__ = Mock(return_value=None)+ mock_context.return_value = mock_cm- result = get_setting_from_db_main_thread(- "test.key", default_value="fallback"- )+ result = get_setting_from_db_main_thread(+ "test.key", default_value="fallback"+ )- assert result == "fallback"+ assert result == "fallback"def test_returns_default_on_exception(self):"""Should return default value on exception."""@@ -327,23 +303,19 @@ class TestGetSettingFromDbMainThread:)with patch(- "local_deep_research.utilities.db_utils.use_fallback_llm",- return_value=False,+ "local_deep_research.utilities.db_utils.has_app_context",+ return_value=True,):+ # Force an exception in the outer try blockwith patch(- "local_deep_research.utilities.db_utils.has_app_context",- return_value=True,+ "local_deep_research.database.session_context.get_user_db_session",+ side_effect=Exception("DB error"),):- # Force an exception in the outer try block- with patch(- "local_deep_research.database.session_context.get_user_db_session",- side_effect=Exception("DB error"),- ):- result = get_setting_from_db_main_thread(- "test.key", default_value="fallback"- )+ result = get_setting_from_db_main_thread(+ "test.key", default_value="fallback"+ )- assert result == "fallback"+ assert result == "fallback"class TestDataDir:diff --git a/tests/web_search_engines/rate_limiting/test_tracker.py b/tests/web_search_engines/rate_limiting/test_tracker.pyindex 9b238837b4..b962c0a382 100644--- a/tests/web_search_engines/rate_limiting/test_tracker.py+++ b/tests/web_search_engines/rate_limiting/test_tracker.py@@ -303,8 +303,8 @@ class TestLoadEstimates:assert tracker._estimates_loaded is True- def test_fallback_mode_skips_loading(self):- """Test that fallback mode skips database loading."""+ def test_ci_mode_skips_loading(self):+ """Test that CI mode skips database loading."""from local_deep_research.config.thread_settings import (NoSettingsContextError,)@@ -318,17 +318,16 @@ class TestLoadEstimates:"local_deep_research.web_search_engines.rate_limiting.tracker.logger"):with patch(- "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm"- ) as mock_fallback:- mock_fallback.return_value = True-+ "local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",+ return_value=True,+ ):from local_deep_research.web_search_engines.rate_limiting.tracker import (AdaptiveRateLimitTracker,)tracker = AdaptiveRateLimitTracker(programmatic_mode=False)- # Should mark as not loaded since fallback mode+ # Should mark as not loaded since CI modeassert tracker._estimates_loaded is Falsediff --git a/tests/web_search_engines/rate_limiting/test_tracker_coverage.py b/tests/web_search_engines/rate_limiting/test_tracker_coverage.pyindex 489c0143cc..5f75b7b8c6 100644--- a/tests/web_search_engines/rate_limiting/test_tracker_coverage.py+++ b/tests/web_search_engines/rate_limiting/test_tracker_coverage.py@@ -17,14 +17,13 @@ def _make_tracker(programmatic_mode=False, **overrides):with patch(f"{MODULE}.get_setting_from_snapshot") as mock_gs:mock_gs.side_effect = NoSettingsContextError("test")with patch(f"{MODULE}.logger"):- with patch(f"{MODULE}.use_fallback_llm", return_value=False):- from local_deep_research.web_search_engines.rate_limiting.tracker import (- AdaptiveRateLimitTracker,- )+ from local_deep_research.web_search_engines.rate_limiting.tracker import (+ AdaptiveRateLimitTracker,+ )- tracker = AdaptiveRateLimitTracker(- programmatic_mode=programmatic_mode, **overrides- )+ tracker = AdaptiveRateLimitTracker(+ programmatic_mode=programmatic_mode, **overrides+ )return tracker@@ -187,8 +186,7 @@ class TestUpdateEstimateDB:)return tracker- @patch(f"{MODULE}.use_fallback_llm", return_value=False)- def test_persists_new_estimate_to_db(self, _fb):+ def test_persists_new_estimate_to_db(self):"""Creates new estimate when none exists in DB."""tracker = self._tw()ms = MagicMock()@@ -214,8 +212,7 @@ class TestUpdateEstimateDB:tracker._update_estimate("Eng")ms.add.assert_called_once()- @patch(f"{MODULE}.use_fallback_llm", return_value=False)- def test_updates_existing_estimate_in_db(self, _fb):+ def test_updates_existing_estimate_in_db(self):"""Updates existing estimate in place."""tracker = self._tw()existing = MagicMock()@@ -245,8 +242,7 @@ class TestUpdateEstimateDB:assert existing.base_wait_seconds is not Nonems.add.assert_not_called()- @patch(f"{MODULE}.use_fallback_llm", return_value=False)- def test_no_user_context_skips_db(self, _fb):+ def test_no_user_context_skips_db(self):"""No search context skips DB persistence."""tracker = self._tw()with patch(f"{MODULE}.get_search_context", return_value=None):@@ -255,8 +251,7 @@ class TestUpdateEstimateDB:tracker._update_estimate("Eng")assert "Eng" in tracker.current_estimates- @patch(f"{MODULE}.use_fallback_llm", return_value=False)- def test_db_exception_logs_but_doesnt_crash(self, _fb):+ def test_db_exception_logs_but_doesnt_crash(self):"""DB write exception is caught, not propagated."""tracker = self._tw()imports = {@@ -284,13 +279,12 @@ class TestUpdateEstimateDB:class TestGetStatsDB:"""Tests for get_stats real DB query path."""- @patch(f"{MODULE}.use_fallback_llm", return_value=False)@patch(f"{MODULE}.is_ci_environment", return_value=False)@patch(f"{MODULE}.get_search_context",return_value={"username": "u", "user_password": "p"},)- def test_full_db_query_returns_estimates(self, _ctx, _ci, _fb):+ def test_full_db_query_returns_estimates(self, _ctx, _ci):"""Full DB path queries all estimates."""tracker = _make_tracker(programmatic_mode=False)est = MagicMock(@@ -316,13 +310,12 @@ class TestGetStatsDB:assert len(result) == 1assert result[0][0] == "TE"- @patch(f"{MODULE}.use_fallback_llm", return_value=False)@patch(f"{MODULE}.is_ci_environment", return_value=False)@patch(f"{MODULE}.get_search_context",return_value={"username": "u", "user_password": "p"},)- def test_db_query_with_engine_filter(self, _ctx, _ci, _fb):+ def test_db_query_with_engine_filter(self, _ctx, _ci):"""DB path uses filter_by when engine_type is specified."""tracker = _make_tracker(programmatic_mode=False)est = MagicMock(@@ -348,13 +341,12 @@ class TestGetStatsDB:assert len(result) == 1assert result[0][0] == "G"- @patch(f"{MODULE}.use_fallback_llm", return_value=False)@patch(f"{MODULE}.is_ci_environment", return_value=False)@patch(f"{MODULE}.get_search_context",return_value={"username": "u", "user_password": "p"},)- def test_db_exception_falls_back_to_in_memory(self, _ctx, _ci, _fb):+ def test_db_exception_falls_back_to_in_memory(self, _ctx, _ci):"""DB exception falls back to in-memory stats."""tracker = _make_tracker(programmatic_mode=False)tracker.current_estimates["Eng"] = {@@ -376,10 +368,9 @@ class TestGetStatsDB:assert len(result) == 1assert result[0][0] == "Eng"- @patch(f"{MODULE}.use_fallback_llm", return_value=False)@patch(f"{MODULE}.is_ci_environment", return_value=False)@patch(f"{MODULE}.get_search_context", return_value=None)- def test_no_context_falls_back_to_in_memory(self, _ctx, _ci, _fb):+ def test_no_context_falls_back_to_in_memory(self, _ctx, _ci):"""No search context falls back to in-memory stats."""tracker = _make_tracker(programmatic_mode=False)tracker.current_estimates["Eng"] = {@@ -396,13 +387,12 @@ class TestGetStatsDB:class TestResetEngineDB:"""Tests for reset_engine DB delete path."""- @patch(f"{MODULE}.use_fallback_llm", return_value=False)@patch(f"{MODULE}.is_ci_environment", return_value=False)@patch(f"{MODULE}.get_search_context",return_value={"username": "u", "user_password": "p"},)- def test_deletes_from_db(self, _ctx, _ci, _fb):+ def test_deletes_from_db(self, _ctx, _ci):"""Deletes from DB and commits."""tracker = _make_tracker(programmatic_mode=False)tracker.recent_attempts["Eng"] = deque(@@ -431,13 +421,12 @@ class TestResetEngineDB:assert "Eng" not in tracker.current_estimatesms.commit.assert_called_once()- @patch(f"{MODULE}.use_fallback_llm", return_value=False)@patch(f"{MODULE}.is_ci_environment", return_value=False)@patch(f"{MODULE}.get_search_context",return_value={"username": "u", "user_password": "p"},)- def test_db_exception_clears_memory_only(self, _ctx, _ci, _fb):+ def test_db_exception_clears_memory_only(self, _ctx, _ci):"""DB exception during reset still clears memory."""tracker = _make_tracker(programmatic_mode=False)tracker.recent_attempts["Eng"] = deque(@@ -475,13 +464,12 @@ class TestCleanupOldDataDB:mock_rla.timestamp = mock_tsreturn mock_rla- @patch(f"{MODULE}.use_fallback_llm", return_value=False)@patch(f"{MODULE}.is_ci_environment", return_value=False)@patch(f"{MODULE}.get_search_context",return_value={"username": "u", "user_password": "p"},)- def test_full_cleanup_deletes_old_rows(self, _ctx, _ci, _fb):+ def test_full_cleanup_deletes_old_rows(self, _ctx, _ci):"""Deletes old attempts from DB and commits."""tracker = _make_tracker(programmatic_mode=False)mq = MagicMock()@@ -500,13 +488,12 @@ class TestCleanupOldDataDB:mq.delete.assert_called_once()ms.commit.assert_called_once()- @patch(f"{MODULE}.use_fallback_llm", return_value=False)@patch(f"{MODULE}.is_ci_environment", return_value=False)@patch(f"{MODULE}.get_search_context",return_value={"username": "u", "user_password": "p"},)- def test_no_old_data_still_commits(self, _ctx, _ci, _fb):+ def test_no_old_data_still_commits(self, _ctx, _ci):"""When no old data exists, still commits."""tracker = _make_tracker(programmatic_mode=False)mq = MagicMock()@@ -524,13 +511,12 @@ class TestCleanupOldDataDB:tracker.cleanup_old_data(days=7)ms.commit.assert_called_once()- @patch(f"{MODULE}.use_fallback_llm", return_value=False)@patch(f"{MODULE}.is_ci_environment", return_value=False)@patch(f"{MODULE}.get_search_context",return_value={"username": "u", "user_password": "p"},)- def test_db_exception_does_not_propagate(self, _ctx, _ci, _fb):+ def test_db_exception_does_not_propagate(self, _ctx, _ci):"""DB exception during cleanup is caught."""tracker = _make_tracker(programmatic_mode=False)mock_writer = MagicMock()@@ -554,9 +540,8 @@ class TestGetTrackerFactory:with patch(f"{MODULE}.get_setting_from_snapshot") as gs:gs.side_effect = NoSettingsContextError("test")with patch(f"{MODULE}.logger"):- with patch(f"{MODULE}.use_fallback_llm", return_value=False):- result1 = mod.get_tracker()- result2 = mod.get_tracker()+ result1 = mod.get_tracker()+ result2 = mod.get_tracker()assert isinstance(result1, mod.AdaptiveRateLimitTracker)assert isinstance(result2, mod.AdaptiveRateLimitTracker)assert result1 is not result2@@ -605,46 +590,42 @@ class TestInitNoneSettings:"""None memory_window uses default 100."""with patch(f"{MODULE}.get_setting_from_snapshot", return_value=None):with patch(f"{MODULE}.logger"):- with patch(f"{MODULE}.use_fallback_llm", return_value=False):- from local_deep_research.web_search_engines.rate_limiting.tracker import (- AdaptiveRateLimitTracker,- )+ from local_deep_research.web_search_engines.rate_limiting.tracker import (+ AdaptiveRateLimitTracker,+ )- t = AdaptiveRateLimitTracker(programmatic_mode=True)+ t = AdaptiveRateLimitTracker(programmatic_mode=True)assert t.memory_window == 100def test_none_exploration_rate_uses_default(self):"""None exploration_rate uses default 0.1."""with patch(f"{MODULE}.get_setting_from_snapshot", return_value=None):with patch(f"{MODULE}.logger"):- with patch(f"{MODULE}.use_fallback_llm", return_value=False):- from local_deep_research.web_search_engines.rate_limiting.tracker import (- AdaptiveRateLimitTracker,- )+ from local_deep_research.web_search_engines.rate_limiting.tracker import (+ AdaptiveRateLimitTracker,+ )- t = AdaptiveRateLimitTracker(programmatic_mode=True)+ t = AdaptiveRateLimitTracker(programmatic_mode=True)assert t.exploration_rate == 0.1def test_none_learning_rate_uses_default(self):"""None learning_rate uses default 0.3."""with patch(f"{MODULE}.get_setting_from_snapshot", return_value=None):with patch(f"{MODULE}.logger"):- with patch(f"{MODULE}.use_fallback_llm", return_value=False):- from local_deep_research.web_search_engines.rate_limiting.tracker import (- AdaptiveRateLimitTracker,- )+ from local_deep_research.web_search_engines.rate_limiting.tracker import (+ AdaptiveRateLimitTracker,+ )- t = AdaptiveRateLimitTracker(programmatic_mode=True)+ t = AdaptiveRateLimitTracker(programmatic_mode=True)assert t.learning_rate == 0.3def test_none_decay_per_day_uses_default(self):"""None decay_per_day uses default 0.95."""with patch(f"{MODULE}.get_setting_from_snapshot", return_value=None):with patch(f"{MODULE}.logger"):- with patch(f"{MODULE}.use_fallback_llm", return_value=False):- from local_deep_research.web_search_engines.rate_limiting.tracker import (- AdaptiveRateLimitTracker,- )+ from local_deep_research.web_search_engines.rate_limiting.tracker import (+ AdaptiveRateLimitTracker,+ )- t = AdaptiveRateLimitTracker(programmatic_mode=True)+ t = AdaptiveRateLimitTracker(programmatic_mode=True)assert t.decay_per_day == 0.95diff --git a/tests/web_search_engines/rate_limiting/test_tracker_quality_stats.py b/tests/web_search_engines/rate_limiting/test_tracker_quality_stats.pyindex 6a782c8001..8137fe7dc4 100644--- a/tests/web_search_engines/rate_limiting/test_tracker_quality_stats.py+++ b/tests/web_search_engines/rate_limiting/test_tracker_quality_stats.py@@ -342,20 +342,16 @@ class TestGetStatsProgrammaticMode:"""Tests for get_stats() in programmatic mode (line 556-558).In the current code, programmatic_mode hits `return stats` at line 558- but `stats` is only defined in the CI/fallback branch above (line 534).+ but `stats` is only defined in the CI branch above (line 534).This is a real bug: NameError when programmatic_mode=True and- use_fallback_llm()/is_ci_environment() are False.+ is_ci_environment() is False."""- @patch(- "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",- return_value=True,- )@patch("local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",return_value=True,)- def test_get_stats_ci_mode_empty(self, _mock_ci, _mock_fb):+ def test_get_stats_ci_mode_empty(self, _mock_ci):"""In CI mode with no estimates, returns empty list."""tracker = _make_tracker()@@ -363,15 +359,11 @@ class TestGetStatsProgrammaticMode:assert result == []- @patch(- "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",- return_value=True,- )@patch("local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",return_value=True,)- def test_get_stats_ci_mode_with_estimates(self, _mock_ci, _mock_fb):+ def test_get_stats_ci_mode_with_estimates(self, _mock_ci):"""In CI mode with estimates, returns in-memory stats."""tracker = _make_tracker()tracker.current_estimates["google"] = {@@ -395,15 +387,11 @@ class TestGetStatsProgrammaticMode:assert attempts == 1assert confidence == 0.8- @patch(- "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",- return_value=True,- )@patch("local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",return_value=True,)- def test_get_stats_ci_mode_filter_by_engine(self, _mock_ci, _mock_fb):+ def test_get_stats_ci_mode_filter_by_engine(self, _mock_ci):"""In CI mode, engine_type filter returns only matching engine."""tracker = _make_tracker()tracker.current_estimates["google"] = {@@ -422,15 +410,11 @@ class TestGetStatsProgrammaticMode:assert len(result) == 1assert result[0][0] == "google"- @patch(- "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",- return_value=True,- )@patch("local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",return_value=True,)- def test_get_stats_ci_mode_nonexistent_engine(self, _mock_ci, _mock_fb):+ def test_get_stats_ci_mode_nonexistent_engine(self, _mock_ci):"""In CI mode, filtering by nonexistent engine returns empty."""tracker = _make_tracker()tracker.current_estimates["google"] = {@@ -443,15 +427,11 @@ class TestGetStatsProgrammaticMode:assert result == []- @patch(- "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",- return_value=True,- )@patch("local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",return_value=True,)- def test_get_stats_ci_mode_missing_confidence(self, _mock_ci, _mock_fb):+ def test_get_stats_ci_mode_missing_confidence(self, _mock_ci):"""In CI mode, missing confidence key defaults to 0.0."""tracker = _make_tracker()tracker.current_estimates["google"] = {@@ -468,15 +448,11 @@ class TestGetStatsProgrammaticMode:confidence = result[0][6]assert confidence == 0.0- @patch(- "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",- return_value=True,- )@patch("local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",return_value=True,)- def test_get_stats_ci_mode_no_recent_attempts(self, _mock_ci, _mock_fb):+ def test_get_stats_ci_mode_no_recent_attempts(self, _mock_ci):"""In CI mode, engine with estimate but no recent_attempts key."""tracker = _make_tracker()tracker.current_estimates["google"] = {@@ -492,16 +468,12 @@ class TestGetStatsProgrammaticMode:attempts_count = result[0][5]assert attempts_count == 0- @patch(- "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",- return_value=False,- )@patch("local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",return_value=False,)def test_get_stats_programmatic_mode_returns_in_memory_stats(- self, _mock_ci, _mock_fb+ self, _mock_ci):"""programmatic_mode=True + non-CI returns in-memory stats."""tracker = _make_tracker()@@ -547,15 +519,11 @@ class TestCleanupOldData:tracker.cleanup_old_data(days=1)tracker.cleanup_old_data(days=365)- @patch(- "local_deep_research.web_search_engines.rate_limiting.tracker.use_fallback_llm",- return_value=True,- )@patch("local_deep_research.web_search_engines.rate_limiting.tracker.is_ci_environment",return_value=True,)- def test_ci_mode_returns_early(self, _mock_ci, _mock_fb):+ def test_ci_mode_returns_early(self, _mock_ci):"""In CI/fallback mode, cleanup does nothing."""tracker = _make_tracker(programmatic_mode=False)diff --git a/tests/web_search_engines/test_rate_limiting_tracker_coverage.py b/tests/web_search_engines/test_rate_limiting_tracker_coverage.pyindex c6b050a919..78de5d2ad3 100644--- a/tests/web_search_engines/test_rate_limiting_tracker_coverage.py+++ b/tests/web_search_engines/test_rate_limiting_tracker_coverage.py@@ -7,15 +7,15 @@ test_tracker_quality_stats.py).Covers:- _get_db_imports: import failure path-- _load_estimates: non-programmatic, non-fallback deferred loading+- _load_estimates: non-programmatic deferred loading- _ensure_estimates_loaded: no db_imports, no context, exception handling- get_wait_time: no-context non-programmatic warning path- _update_estimate: empty failed_waits default, single success median edge- record_outcome: error_type parameter, thread-safety under concurrent writes- apply_rate_limit: sleep with positive wait, sleep skipped for zero-- get_stats: DB exception fallback, programmatic mode-- reset_engine: CI/fallback mode, DB exception path-- cleanup_old_data: CI/fallback mode+- get_stats: DB exception, programmatic mode, CI mode+- reset_engine: CI mode, DB exception path+- cleanup_old_data: CI mode- get_tracker: singleton creation and caching- Thread safety: concurrent record_outcome calls- Edge cases: zero base, very small/large wait times, boundary values@@ -117,31 +117,17 @@ class TestGetDbImportsFailure:class TestLoadEstimatesNonProgrammatic:"""Tests for _load_estimates in non-programmatic mode."""- def test_non_programmatic_non_fallback_defers_loading(self):- """Non-programmatic, non-fallback mode defers loading."""+ def test_non_programmatic_defers_loading(self):+ """Non-programmatic mode defers loading."""with patch(f"{MODULE}.get_setting_from_snapshot") as mock_gs:mock_gs.side_effect = NoSettingsContextError("test")with patch(f"{MODULE}.logger"):- with patch(f"{MODULE}.use_fallback_llm", return_value=False):- from local_deep_research.web_search_engines.rate_limiting.tracker import (- AdaptiveRateLimitTracker,- )-- tracker = AdaptiveRateLimitTracker(programmatic_mode=False)- assert tracker._estimates_loaded is False-- def test_fallback_mode_skips_and_leaves_unloaded(self):- """Fallback mode skips loading and leaves _estimates_loaded False."""- with patch(f"{MODULE}.get_setting_from_snapshot") as mock_gs:- mock_gs.side_effect = NoSettingsContextError("test")- with patch(f"{MODULE}.logger"):- with patch(f"{MODULE}.use_fallback_llm", return_value=True):- from local_deep_research.web_search_engines.rate_limiting.tracker import (- AdaptiveRateLimitTracker,- )+ from local_deep_research.web_search_engines.rate_limiting.tracker import (+ AdaptiveRateLimitTracker,+ )- tracker = AdaptiveRateLimitTracker(programmatic_mode=False)- assert tracker._estimates_loaded is False+ tracker = AdaptiveRateLimitTracker(programmatic_mode=False)+ assert tracker._estimates_loaded is False# ── _ensure_estimates_loaded ────────────────────────────────────────@@ -686,9 +672,8 @@ class TestRecordOutcomeDetailed:class TestGetStatsDetailed:"""Detailed tests for get_stats."""- @patch(f"{MODULE}.use_fallback_llm", return_value=False)@patch(f"{MODULE}.is_ci_environment", return_value=False)- def test_programmatic_mode_returns_in_memory(self, _ci, _fb):+ def test_programmatic_mode_returns_in_memory(self, _ci):"""Programmatic mode returns in-memory stats without DB access."""tracker = _make_tracker()tracker.current_estimates["google"] = {@@ -707,9 +692,8 @@ class TestGetStatsDetailed:assert result[0][0] == "google"assert result[0][1] == 1.5- @patch(f"{MODULE}.use_fallback_llm", return_value=False)@patch(f"{MODULE}.is_ci_environment", return_value=False)- def test_programmatic_mode_with_engine_filter(self, _ci, _fb):+ def test_programmatic_mode_with_engine_filter(self, _ci):"""Programmatic mode filters by engine_type."""tracker = _make_tracker()tracker.current_estimates["google"] = {@@ -730,26 +714,8 @@ class TestGetStatsDetailed:assert len(result) == 1assert result[0][0] == "bing"- @patch(f"{MODULE}.use_fallback_llm", return_value=True)- @patch(f"{MODULE}.is_ci_environment", return_value=False)- def test_fallback_mode_returns_in_memory(self, _ci, _fb):- """Fallback LLM mode returns in-memory stats."""- tracker = _make_tracker()- tracker.programmatic_mode = False- tracker.current_estimates["eng"] = {- "base": 1.0,- "min": 0.1,- "max": 3.0,- "confidence": 0.5,- }-- result = tracker.get_stats()-- assert len(result) == 1-- @patch(f"{MODULE}.use_fallback_llm", return_value=False)@patch(f"{MODULE}.is_ci_environment", return_value=True)- def test_ci_mode_returns_in_memory(self, _ci, _fb):+ def test_ci_mode_returns_in_memory(self, _ci):"""CI mode returns in-memory stats."""tracker = _make_tracker()tracker.programmatic_mode = False@@ -870,27 +836,8 @@ class TestGetInMemoryStats:class TestResetEngineDetailed:"""Detailed tests for reset_engine."""- @patch(f"{MODULE}.use_fallback_llm", return_value=True)- @patch(f"{MODULE}.is_ci_environment", return_value=False)- def test_fallback_mode_clears_memory_only(self, _ci, _fb):- """Fallback mode clears memory without touching DB."""- tracker = _make_tracker()- tracker.programmatic_mode = False- tracker.current_estimates["Eng"] = {- "base": 1.0,- "min": 0.5,- "max": 2.0,- }- tracker.recent_attempts["Eng"] = deque([{"s": 1}], maxlen=100)-- tracker.reset_engine("Eng")-- assert "Eng" not in tracker.current_estimates- assert "Eng" not in tracker.recent_attempts-- @patch(f"{MODULE}.use_fallback_llm", return_value=False)@patch(f"{MODULE}.is_ci_environment", return_value=True)- def test_ci_mode_clears_memory_only(self, _ci, _fb):+ def test_ci_mode_clears_memory_only(self, _ci):"""CI mode clears memory without touching DB."""tracker = _make_tracker()tracker.programmatic_mode = False@@ -916,17 +863,8 @@ class TestCleanupOldDataDetailed:tracker = _make_tracker()tracker.cleanup_old_data(days=7)- @patch(f"{MODULE}.use_fallback_llm", return_value=True)- @patch(f"{MODULE}.is_ci_environment", return_value=False)- def test_fallback_mode_no_op(self, _ci, _fb):- """Fallback mode returns early without error."""- tracker = _make_tracker()- tracker.programmatic_mode = False- tracker.cleanup_old_data(days=7)-- @patch(f"{MODULE}.use_fallback_llm", return_value=False)@patch(f"{MODULE}.is_ci_environment", return_value=True)- def test_ci_mode_no_op(self, _ci, _fb):+ def test_ci_mode_no_op(self, _ci):"""CI mode returns early without error."""tracker = _make_tracker()tracker.programmatic_mode = False@@ -951,14 +889,13 @@ class TestGetTracker:with patch(f"{MODULE}.get_setting_from_snapshot") as mock_gs:mock_gs.side_effect = NoSettingsContextError("test")with patch(f"{MODULE}.logger"):- with patch(f"{MODULE}.use_fallback_llm", return_value=True):- t1 = mod.get_tracker()- t2 = mod.get_tracker()- assert t1 is not None- assert isinstance(t1, mod.AdaptiveRateLimitTracker)- assert t2 is not None- assert isinstance(t2, mod.AdaptiveRateLimitTracker)- assert t1 is not t2+ t1 = mod.get_tracker()+ t2 = mod.get_tracker()+ assert t1 is not None+ assert isinstance(t1, mod.AdaptiveRateLimitTracker)+ assert t2 is not None+ assert isinstance(t2, mod.AdaptiveRateLimitTracker)+ assert t1 is not t2# ── Thread safety ───────────────────────────────────────────────────@@ -1161,13 +1098,12 @@ class TestInitWithSettings:with patch(f"{MODULE}.get_setting_from_snapshot") as mock_gs:mock_gs.side_effect = NoSettingsContextError("test")with patch(f"{MODULE}.logger"):- with patch(f"{MODULE}.use_fallback_llm", return_value=True):- from local_deep_research.web_search_engines.rate_limiting.tracker import (- AdaptiveRateLimitTracker,- )+ from local_deep_research.web_search_engines.rate_limiting.tracker import (+ AdaptiveRateLimitTracker,+ )- tracker = AdaptiveRateLimitTracker(programmatic_mode=False)- assert tracker.enabled is True+ tracker = AdaptiveRateLimitTracker(programmatic_mode=False)+ assert tracker.enabled is True# ── _get_quality_status boundary conditions ─────────────────────────