Skip to content

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

fix(settings): fail on invalid configured values (#7288)

LearningCircuitd9958910c485
diff --git a/changelog.d/+settings-read-consistency.breaking.md b/changelog.d/+settings-read-consistency.breaking.md
new file mode 100644
index 0000000000..0e235d9a56
--- /dev/null
+++ b/changelog.d/+settings-read-consistency.breaking.md
@@ -0,0 +1 @@
+Invalid configured settings now stop the operation instead of being replaced. Managed settings reads and effective snapshots raise `SettingsValueError` when the selected value cannot be converted to its declared type or the type is unsupported; an invalid `LDR_*` override no longer falls back to the saved value or a default. A bulk settings save preserves its previous stored values and returns the setting diagnostic when an invalid environment override prevents preparing the response. An override for a key with no declared type and no saved row, such as `LDR_APP_API_RATE_LIMIT` or `LDR_APP_ENABLE_API`, is still returned unconverted. Because an effective snapshot validates every entry, one invalid setting can fail an endpoint or run that reads other settings. The settings and search-engine list APIs and research start then return an error naming the setting key, its source and the reason, never the value, which the settings page and the research form display. A route that does not handle the error itself answers with the same diagnostic, as a page for a browser request or as JSON for an API request; the main page shows it instead of signing the user out, and the news subscription egress check refuses the subscription with it instead of being skipped. The `/api/v1` research endpoints refuse with a 503 whose `reason` is `invalid_setting`, and `allow_default_settings` does not bypass it. Creating a custom setting through `PUT /settings/api/{key}` or the bulk settings save, or a write that would turn a text setting into an invalid number, now fails with a 400 naming the key when the type is unsupported or the value cannot be converted, and `/settings/api/ui_elements` lists only the supported types. The defaults reconciliation that runs after an upgrade keeps an invalid saved value and logs a warning naming the key, where it previously replaced the value with the default. Non-empty environment overrides for boolean settings accept only `true`, `1`, `yes`, `on`, `enabled` and `false`, `0`, `no`, `off`, `disabled`, and other values raise; previously a database-backed setting treated `disabled` and any other unrecognized value as on. `llm.request_timeout` below 1 second and `llm.max_retries` outside 0-5 raise instead of being clamped, and a malformed timeout no longer uses the default. Check deployment overrides and saved settings before upgrading, as the upgrade guide describes. Missing optional settings keep their documented defaults, and the raw export still returns stored values for repair. Configuration errors propagate through provider, search, indexing and scheduler startup callers; in-memory reads honor namespaces and environment-only keys consistently, and a failed in-memory import preserves the live configuration.
diff --git a/changelog.d/5339.bugfix.md b/changelog.d/5339.bugfix.md
index 015d2ffbba..b23c8014e2 100644
--- a/changelog.d/5339.bugfix.md
+++ b/changelog.d/5339.bugfix.md
@@ -1 +1 @@
-LLM clients and the Ollama and OpenAI embedding clients now use an explicit per-operation HTTP timeout. `llm.request_timeout` defaults to 1800 seconds, clamps values below 1 second, and has no upper limit; malformed or non-finite values use the default. It bounds connect, write, pool, and response-read operations individually. A peer that keeps sending data can exceed this value even for a non-streaming response, so this is not a total-response deadline. OpenAI-compatible and Ollama clients cap connection attempts at 5 seconds; Anthropic inference uses its configured scalar timeout for connecting too. `llm.max_retries` defaults to 2 and is clamped to 0-5 for OpenAI-compatible and Anthropic SDKs. Each retry has its own operation timeouts, and SDK backoff or server-directed delays add to elapsed time. OpenAI-compatible, Anthropic, and OpenAI embedding model discovery use a 30-second operation budget with SDK retries disabled; Google and Ollama retain their 10- and 5-second discovery limits. Timeout errors name the setting and environment variable, and say that connection attempts are bounded at most at 5 seconds so raising the setting above that will not help an unreachable endpoint. Configured Ollama authentication headers now reach both the synchronous and the asynchronous HTTP client, for chat and for embeddings alike. `ChatOpenAI` receives the bound as a hashable `(connect, read, write, pool)` tuple rather than a `Timeout` object, which is what keeps `langchain_openai`'s shared httpx client cache in effect; every other client, including OpenAI embeddings and the OpenAI-compatible discovery clients, is built fresh per instance or per call and takes the SDK's own `Timeout` object; that shared async client stays bound to the event loop that built it (see issue #6293), so synchronous entry points continue to use synchronous `invoke`. On asynchronous streams `langchain_openai` applies its own 120-second `stream_chunk_timeout` between chunks, which fires before this setting. A non-streaming request receives nothing until generation finishes, so there the bound is in effect a cap on a single generation: a local model slow enough to exceed it needs a value above the 1800-second default, which has no upper limit.
+LLM clients and the Ollama and OpenAI embedding clients now use an explicit per-operation HTTP timeout. `llm.request_timeout` defaults to 1800 seconds and has no upper limit. It bounds connect, write, pool, and response-read operations individually. A peer that keeps sending data can exceed this value even for a non-streaming response, so this is not a total-response deadline. OpenAI-compatible and Ollama clients cap connection attempts at 5 seconds; Anthropic inference uses its configured scalar timeout for connecting too. `llm.max_retries` defaults to 2 and applies to OpenAI-compatible and Anthropic SDKs. Each retry has its own operation timeouts, and SDK backoff or server-directed delays add to elapsed time. OpenAI-compatible, Anthropic, and OpenAI embedding model discovery use a 30-second operation budget with SDK retries disabled; Google and Ollama retain their 10- and 5-second discovery limits. Timeout errors name the setting and environment variable, and say that connection attempts are bounded at most at 5 seconds so raising the setting above that will not help an unreachable endpoint. Configured Ollama authentication headers now reach both the synchronous and the asynchronous HTTP client, for chat and for embeddings alike. `ChatOpenAI` receives the bound as a hashable `(connect, read, write, pool)` tuple rather than a `Timeout` object, which is what keeps `langchain_openai`'s shared httpx client cache in effect; every other client, including OpenAI embeddings and the OpenAI-compatible discovery clients, is built fresh per instance or per call and takes the SDK's own `Timeout` object; that shared async client stays bound to the event loop that built it (see issue #6293), so synchronous entry points continue to use synchronous `invoke`. On asynchronous streams `langchain_openai` applies its own 120-second `stream_chunk_timeout` between chunks, which fires before this setting. A non-streaming request receives nothing until generation finishes, so there the bound is in effect a cap on a single generation: a local model slow enough to exceed it needs a value above the 1800-second default, which has no upper limit.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index f06fc08079..0aa90185a4 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -141,7 +141,7 @@ They are not available in the Web UI because they are needed to start the applic
| `llm.lmstudio.api_key` | `LDR_LLM_LMSTUDIO_API_KEY` | `` | Optional API key for LM Studio if you've enabled authentication. Leave empty for the default no-auth setup. | LLM |
| `llm.lmstudio.url` | `LDR_LLM_LMSTUDIO_URL` | `http://localhost:1234/v1` | HTTP endpoint URL where LM Studio is running locally. Include the full path (e.g., http://localhost:1234/v1 for OpenAI-compatible API format). | LLM |
| `llm.local_context_window_size` | `LDR_LLM_LOCAL_CONTEXT_WINDOW_SIZE` | `20480` | Context window size in tokens for local LLMs (Ollama, LlamaCpp, LM Studio). The default of 20480 tokens fits on systems with limited VRAM while still leaving room for the synthesis prompt. If your synthesis prompts get truncated, increase this; if you run out of VRAM, reduce it and switch to the source-based strategy. | LLM |
-| `llm.max_retries` | `LDR_LLM_MAX_RETRIES` | `2` | Maximum provider SDK retries per failed inference or embedding request. Applies to OpenAI-compatible and Anthropic SDKs; the Ollama client does not retry. Values outside 0-5 are clamped. Each retry starts another request with its own per-operation timeouts; SDK backoff or server-requested retry delays can further extend elapsed time. This setting does not impose a total request deadline. Model discovery SDK retries are disabled. | LLM |
+| `llm.max_retries` | `LDR_LLM_MAX_RETRIES` | `2` | Maximum provider SDK retries per failed inference or embedding request. Applies to OpenAI-compatible and Anthropic SDKs; the Ollama client does not retry. Configured values must be finite numbers within 0-5; invalid values raise a settings error instead of being replaced. An absent or unset optional value uses the default. Each retry starts another request with its own per-operation timeouts; SDK backoff or server-requested retry delays can further extend elapsed time. This setting does not impose a total request deadline. Model discovery SDK retries are disabled. | LLM |
| `llm.max_tokens` | `LDR_LLM_MAX_TOKENS` | `30000` | Maximum tokens in model responses. Automatically capped at 80% of the context window size to leave room for prompt tokens. | LLM |
| `llm.model` | `LDR_LLM_MODEL` | `` | The language model to use. Available models depend on the selected provider (e.g., 'gpt-4o' for OpenAI, 'gemma:7b' for Ollama). You can type any model name supported by your provider. | LLM |
| `llm.ollama.api_key` | `LDR_LLM_OLLAMA_API_KEY` | `` | Optional API key for Ollama if you've put it behind a proxy that requires authentication. Leave empty for the default no-auth setup. | LLM |
@@ -155,7 +155,7 @@ They are not available in the Web UI because they are needed to start the applic
| `llm.orcarouter.api_key` | `LDR_LLM_ORCAROUTER_API_KEY` | `null` | API key to use for the OrcaRouter provider. | LLM |
| `llm.provider` | `LDR_LLM_PROVIDER` | `ollama` | The LLM service provider. Choose local providers (Ollama, LM Studio, LlamaCpp) for free on-device inference, or cloud APIs (OpenAI, Anthropic, Google, OpenRouter) for hosted models. | LLM |
| `llm.qwen.api_key` | `LDR_LLM_QWEN_API_KEY` | `null` | API key to use for the QwenCloud provider. | LLM |
-| `llm.request_timeout` | `LDR_LLM_REQUEST_TIMEOUT` | `1800` | Per-operation HTTP timeout in seconds for LLM inference and embedding requests, applied to every supported provider. It bounds each connect, write and wait for the next response chunk individually; it is not a cap on the total duration of a response. A peer that keeps sending data can exceed this value, including for a non-streaming response. Connecting is separately capped at 5 seconds for OpenAI-compatible and Ollama clients; Anthropic inference uses this value for connecting too. There is no upper limit; values below 1 second are clamped to 1, and non-numeric or non-finite values use the default. Model discovery is unaffected: OpenAI-compatible providers and Anthropic use 30 seconds, while Google and Ollama retain provider-specific limits of 10 and 5 seconds, respectively. | LLM |
+| `llm.request_timeout` | `LDR_LLM_REQUEST_TIMEOUT` | `1800` | Per-operation HTTP timeout in seconds for LLM inference and embedding requests, applied to every supported provider. It bounds each connect, write and wait for the next response chunk individually; it is not a cap on the total duration of a response. A peer that keeps sending data can exceed this value, including for a non-streaming response. Connecting is separately capped at 5 seconds for OpenAI-compatible and Ollama clients; Anthropic inference uses this value for connecting too. There is no upper limit. Configured values must be finite numbers of at least 1 second; invalid values raise a settings error instead of being replaced. An absent or unset optional value uses the default. Model discovery is unaffected: OpenAI-compatible providers and Anthropic use 30 seconds, while Google and Ollama retain provider-specific limits of 10 and 5 seconds, respectively. | LLM |
| `llm.requesty.api_key` | `LDR_LLM_REQUESTY_API_KEY` | `null` | API key to use for the Requesty provider. | LLM |
| `llm.require_local_endpoint` | `LDR_LLM_REQUIRE_LOCAL_ENDPOINT` | `false` | When enabled, the LLM provider's resolved endpoint must be on a local network (loopback, RFC1918, link-local). Cloud-only providers (OpenAI, Anthropic, Google, OpenRouter) are blocked. Independent of egress_scope. | LLM |
| `llm.supports_max_tokens` | `LDR_LLM_SUPPORTS_MAX_TOKENS` | `true` | Feature flag for max_tokens parameter. Disable if your LLM API returns errors when max_tokens is set. When disabled, the parameter is not passed to the API. | LLM |
diff --git a/docs/deployment/unraid.md b/docs/deployment/unraid.md
index 911807aa38..fca5596e52 100644
--- a/docs/deployment/unraid.md
+++ b/docs/deployment/unraid.md
@@ -174,7 +174,7 @@ Configure these based on your setup:
> **Important:** Unraid templates create all environment variables even when fields are left blank. Empty values (`""`) are treated as **not set** — they will not override or lock anything. Only non-empty values act as overrides. This means leaving a field blank in the Unraid template is safe and equivalent to not having the variable at all.
>
-> **Security note:** Setting an API key variable to an empty string does **not** block or clear it. If a key is already stored in the database, it will still be used even when the env var is empty. To explicitly block a key, set it to any non-empty invalid value (e.g., `DISABLED`).
+> **Security note:** Setting an API key variable to an empty string does **not** block or clear it. If a key is already stored in the database, it will still be used even when the env var is empty. To explicitly block a stored API key, set its variable to a non-empty placeholder that is not a working key (e.g., `DISABLED`); API keys are plain-text settings, so this raises no settings error. Do not use placeholders for typed settings such as numbers, checkboxes or JSON: a value that cannot be converted raises a settings error.
**Recommendation:** Configure these via the WebUI Settings page instead of environment variables for easier management.
diff --git a/docs/deployment/upgrading.md b/docs/deployment/upgrading.md
index f7ac21841e..453e67887c 100644
--- a/docs/deployment/upgrading.md
+++ b/docs/deployment/upgrading.md
@@ -65,6 +65,40 @@ See the [configuration reference](../CONFIGURATION.md).
bucket and a few failed logins lock everyone out. Without
`TRUST_PROXY_HEADERS`, such a proxy's `X-Forwarded-For` is ignored too.
+### Invalid configured settings
+
+Managed settings reads and research snapshots now fail when a configured
+value cannot be converted to its declared type, or when the setting's type
+metadata is unsupported. An invalid environment override no longer falls
+back to a saved value or default. Missing optional settings still use their
+documented defaults. A variable for a key with no declared setting type, such
+as `LDR_APP_API_RATE_LIMIT`, is still read as the raw string.
+
+Check deployment overrides and saved settings on a restored test copy before
+upgrading production. For example, `LDR_LLM_TEMPERATURE` must contain a number;
+correct an invalid override in the deployment configuration, or remove it to
+use the saved value or default, then restart the application. The selected
+saved value must also be valid. See the [configuration reference](../CONFIGURATION.md)
+for setting names and supported values.
+
+A settings validation error identifies the setting key, its source and a
+diagnostic reason without including the configured value. The settings page,
+the main page and the research form display it, the settings and
+search-engine list APIs return it, the `/api/v1` research endpoints return
+it in a 503 response whose `reason` is `invalid_setting`, and the server log
+records it. Use those details to locate the setting. If invalid saved values
+or type metadata prevent the settings page from opening, retain the backup
+and request a targeted repair using those diagnostics. Startup does not
+repair every malformed setting: migration `0031` handles only its
+allowlisted legacy cases, and the defaults reconciliation after an upgrade
+keeps an invalid saved value, logging a warning that names the key, rather
+than replacing it with the default.
+
+If an invalid environment override prevents a bulk settings save from
+preparing its updated settings response, the save preserves the previous
+stored values and returns the setting diagnostic. Correct the override
+before retrying the save.
+
## Upgrade and verify
Install the selected release and start one application process against the
diff --git a/docs/docker-compose-guide.md b/docs/docker-compose-guide.md
index 7fbc9705e4..c6a994e190 100644
--- a/docs/docker-compose-guide.md
+++ b/docs/docker-compose-guide.md
@@ -54,7 +54,7 @@ Most settings can be configured through the web UI at http://localhost:5000/sett
> **⚠️ Warning:** Setting environment variables causes a hard override—the setting becomes read-only in the UI and cannot be changed until the environment variable is removed. For settings you may want to adjust later, use the web UI instead. Environment variables are best suited for deployment-specific values like `LDR_DATA_DIR` or API keys.
>
-> **Note:** Empty environment variables (e.g., `LDR_LLM_PROVIDER=` or `LDR_LLM_PROVIDER=""`) are treated as **not set** — they will not override anything and the setting remains editable in the UI. This prevents Docker Compose templates with blank fields from accidentally locking settings. Only non-empty values act as overrides. Setting an API key to an empty string does **not** block or clear it — if a key exists in the database, it will still be used. To explicitly block a key, set it to any non-empty invalid value (e.g., `DISABLED`).
+> **Note:** Empty environment variables (e.g., `LDR_LLM_PROVIDER=` or `LDR_LLM_PROVIDER=""`) are treated as **not set** — they will not override anything and the setting remains editable in the UI. This prevents Docker Compose templates with blank fields from accidentally locking settings. Only non-empty values act as overrides. Setting an API key to an empty string does **not** block or clear it — if a key exists in the database, it will still be used. To explicitly block a stored API key, set its variable to a non-empty placeholder that is not a working key (e.g., `DISABLED`); API keys are plain-text settings, so this raises no settings error. Do not use placeholders for typed settings such as numbers, checkboxes or JSON: a value that cannot be converted raises a settings error.
| Variable | Description |
|----------|-------------|
diff --git a/docs/env_configuration.md b/docs/env_configuration.md
index c4ec8a6de2..91412f6fa1 100644
--- a/docs/env_configuration.md
+++ b/docs/env_configuration.md
@@ -26,12 +26,42 @@ For example:
> **Important:** Environment variables **override** UI settings and lock them — the setting becomes read-only in the UI until the environment variable is removed. For settings you may want to adjust later, use the Web UI instead.
>
-> **Note on empty values:** Empty environment variables (e.g., `LDR_LLM_PROVIDER=""`) are treated as **not set** — they will not override anything and the setting remains editable in the UI. This is by design: deployment tools like Unraid and Docker Compose templates often create all environment variables even when fields are left blank. Only non-empty values act as overrides. To remove an override, delete the environment variable entirely rather than setting it to an empty string. To explicitly block a setting, set it to any non-empty invalid value (e.g., `DISABLED`).
+> **Note on empty values:** Empty environment variables (e.g., `LDR_LLM_PROVIDER=""`) are treated as **not set** — they will not override anything and the setting remains editable in the UI. This is by design: deployment tools like Unraid and Docker Compose templates often create all environment variables even when fields are left blank. Only non-empty values act as overrides. To remove an override, delete the environment variable entirely rather than setting it to an empty string.
>
> **Per-run overrides:** When starting research via the API or web UI, explicit per-run parameters (`max_results`, `time_period`, `iterations`, `questions_per_iteration`, `strategy`) take precedence over both database settings **and** environment variable overrides for that specific run. Environment variables still lock the stored setting and UI; the per-run exception applies only to the explicit request payload, not to persisted configuration.
For the complete list of all settings, their environment variable names, and default values, see [CONFIGURATION.md](CONFIGURATION.md).
+### Invalid setting values
+
+Settings-manager reads and effective snapshots raise `SettingsValueError` when
+the selected value cannot be converted or its setting type is unsupported.
+For example, `LDR_SEARCH_ITERATIONS=invalid` stops the operation instead of
+using the saved iteration count or a default. Correct or remove the invalid
+override before retrying. An invalid stored value also fails when it is the
+selected value; a valid environment override still takes precedence. A
+variable for a key with no declared setting type and no saved row, such as
+`LDR_APP_API_RATE_LIMIT` or `LDR_APP_ENABLE_API`, has nothing to be validated
+against: it is read as the raw string, and the code that uses it parses it.
+
+Numeric values must be finite numbers, not booleans. Environment overrides
+for boolean settings accept `true`, `1`, `yes`, `on`, `enabled` and their false counterparts
+`false`, `0`, `no`, `off`, `disabled`, ignoring case and surrounding whitespace.
+JSON environment overrides must contain valid JSON. Errors identify the
+setting and source without including the configured value.
+
+Absent optional settings still use their documented defaults. Empty overrides
+for database-backed settings retain the unset behavior described above.
+Environment-only integer settings also treat empty or whitespace-only values
+as unset, including the trusted-proxy count. Other malformed integer values
+still raise a settings error on managed reads. Environment-only boolean
+settings differ: an empty or whitespace-only value reads as false, not as
+unset, so `LDR_NEWS_SCHEDULER_ENABLED=""` disables a default-on setting.
+The raw export API (`include_environment_overrides=False`) preserves stored
+values and metadata so invalid configuration can be inspected and repaired.
+A screen or API endpoint that loads a full effective snapshot will fail if any
+entry in that snapshot is invalid, even when the requested field is different.
+
## Getting Variables Into LDR (and Making Them Persistent)
**LDR's own code never loads a `.env` file into its settings** — it reads
@@ -112,7 +142,7 @@ or rename the stray `.env`, or move the virtualenv out from under it.
API keys are best set using environment variables for security. Only the `LDR_` prefixed version is needed.
-> **Security note:** Setting an API key variable to an empty string (e.g., `LDR_LLM_OPENAI_API_KEY=""`) does **not** block or clear the key — it is treated as unset, and the key remains editable in the UI. If a key is already stored in the database, it will still be used. To explicitly block a key, set it to any non-empty invalid value (e.g., `DISABLED`).
+> **Security note:** Setting an API key variable to an empty string (e.g., `LDR_LLM_OPENAI_API_KEY=""`) does **not** block or clear the key — it is treated as unset, and the key remains editable in the UI. If a key is already stored in the database, it will still be used. To explicitly block a stored API key, set its variable to a non-empty placeholder that is not a working key (e.g., `DISABLED`). API keys are plain-text settings, so the placeholder replaces the stored key without a settings error. This does not work for typed settings such as numbers, checkboxes or JSON: a value that cannot be converted raises a settings error (see [Invalid setting values](#invalid-setting-values)).
```bash
# LLM API keys
diff --git a/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py b/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py
index 100266bf13..8a12722c65 100644
--- a/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py
+++ b/src/local_deep_research/advanced_search_system/filters/cross_engine_filter.py
@@ -6,6 +6,7 @@ from typing import Dict, List
from loguru import logger
+from ...settings.exceptions import SettingsValueError
from ...utilities.json_utils import extract_json, get_llm_response_text
from .base_filter import BaseFilter
from ...utilities.llm_utils import invoke_llm_sync
@@ -51,6 +52,8 @@ class CrossEngineFilter(BaseFilter):
max_results = int(max_results)
else:
max_results = 100
+ except SettingsValueError:
+ raise
except (NoSettingsContextError, TypeError, ValueError):
max_results = 100
self.max_results = max_results
@@ -66,6 +69,8 @@ class CrossEngineFilter(BaseFilter):
settings_snapshot=settings_snapshot,
)
)
+ except SettingsValueError:
+ raise
except (NoSettingsContextError, TypeError, ValueError):
self.max_context_items = 30
diff --git a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
index 88d085eb8f..5a1e938268 100644
--- a/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
+++ b/src/local_deep_research/advanced_search_system/filters/journal_reputation_filter.py
@@ -51,6 +51,7 @@ from ...journal_quality.db import get_db as get_journal_data_manager
from ...journal_quality.scoring import normalize_name
from ...security.egress.policy import PolicyDeniedError
from ...security.log_sanitizer import strip_control_chars
+from ...settings.exceptions import SettingsValueError
from ...utilities.json_utils import get_llm_response_text
from ...utilities.llm_utils import get_model_identifier
from ...utilities.resource_utils import safe_close
@@ -441,6 +442,8 @@ class JournalReputationFilter(BaseFilter):
f"threshold={filt._JournalReputationFilter__threshold}"
)
return filt
+ except SettingsValueError:
+ raise
except PolicyDeniedError:
# The egress policy refused the LLM the filter needs. This
# must propagate so the user sees a clear policy refusal —
@@ -448,12 +451,8 @@ class JournalReputationFilter(BaseFilter):
# through under ``llm.require_local_endpoint=True``.
raise
except Exception:
- # Any other failure — settings read, filter init — returns
- # None rather than silently defaulting to enabled. A separate
- # silent ``except Exception: enabled = True`` branch used to
- # wrap only the settings read, which hid legitimate
- # configuration errors; per CLAUDE.md, fallbacks have to be
- # explicit, not default-on.
+ # Non-configuration startup failures may leave the optional
+ # filter unavailable. Invalid configured values propagate above.
logger.exception(
f"Failed to configure journal filter for {engine_name}; "
"results will not be journal-quality filtered for this engine"
diff --git a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
index f05aff326a..b90a2011ed 100644
--- a/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
+++ b/src/local_deep_research/advanced_search_system/tools/fetch/__init__.py
@@ -39,6 +39,7 @@ from local_deep_research.security import (
redact_url_for_log,
sanitize_error_for_agent,
)
+from local_deep_research.settings.exceptions import SettingsValueError
from local_deep_research.utilities.type_utils import unwrap_setting
from local_deep_research.utilities.llm_utils import invoke_llm_sync
@@ -84,15 +85,18 @@ def _read_max_fetches_setting(
Retained as a fallback for direct callers of ``build_fetch_tool`` outside
``LangGraphAgentStrategy`` (which passes ``max_fetches`` explicitly).
- Returns the configured non-negative integer limit, or default if missing/invalid.
- Negative values fall back to default, and values above 50 are clamped to 50.
- 0 means unlimited fetches.
+ Returns the configured non-negative integer limit, or default if it is
+ missing or an untyped value is not a usable limit. Negative values fall
+ back to default, and values above 50 are clamped to 50. 0 means unlimited
+ fetches.
Typed number rows use the canonical accessor's float conversion (fractional
strings truncate) and environment priority. A non-empty
- ``LDR_SEARCH_FETCH_MAX_PER_TOPIC`` overrides such a row; an unparseable
- environment value falls back to the snapshot. A negative or non-finite
- resulting limit falls back to the caller's default.
+ ``LDR_SEARCH_FETCH_MAX_PER_TOPIC`` overrides such a row. A typed row or an
+ override that is not a finite number (a boolean included), or a row whose
+ type is unsupported, propagates SettingsValueError instead of selecting
+ another limit. A negative resulting limit falls back to the caller's
+ default.
Raw values and sparse legacy rows retain snapshot-only int() coercion.
An absent exact key keeps the caller's default even with an environment or
@@ -124,6 +128,8 @@ def _read_max_fetches_setting(
val = get_setting_from_snapshot(
key, default=None, settings_snapshot=lookup_snapshot
)
+ except SettingsValueError:
+ raise
except Exception:
return default
if val is None:
@@ -149,8 +155,9 @@ def _read_content_max_length_setting(
extraction (``summary_focus`` / ``summary_focus_query``).
Returns the configured length clamped to
- [CONTENT_MAX_LENGTH_MIN, CONTENT_MAX_LENGTH_MAX], or default if
- missing/invalid/non-positive.
+ [CONTENT_MAX_LENGTH_MIN, CONTENT_MAX_LENGTH_MAX]. Missing, non-positive,
+ or unconvertible untyped legacy values retain the default. Invalid managed
+ settings propagate SettingsValueError instead of selecting another limit.
"""
if not settings_snapshot:
return default
@@ -164,6 +171,8 @@ def _read_content_max_length_setting(
default=None,
settings_snapshot=settings_snapshot,
)
+ except SettingsValueError:
+ raise
except Exception:
return default
if val is None:
diff --git a/src/local_deep_research/api/settings_utils.py b/src/local_deep_research/api/settings_utils.py
index cc60e2568d..d13120633d 100644
--- a/src/local_deep_research/api/settings_utils.py
+++ b/src/local_deep_research/api/settings_utils.py
@@ -12,10 +12,15 @@ from loguru import logger
from ..settings import SettingsManager
from ..settings.base import ISettingsManager
+from ..settings.env_registry import registry as env_registry
+from ..settings.exceptions import SettingsValueError
from ..settings.manager import (
- UI_ELEMENT_TO_SETTING_TYPE,
+ UI_ELEMENT_TO_SETTING_TYPE as UI_ELEMENT_TO_SETTING_TYPE,
validate_imported_setting_value,
check_env_setting,
+ get_typed_setting_value,
+ is_operator_only_setting,
+ is_valid_setting_key,
)
from ..utilities.type_utils import to_bool, unwrap_setting
@@ -35,48 +40,26 @@ class InMemorySettingsManager(ISettingsManager):
self._settings = {}
self._load_defaults()
- def _get_typed_value(self, setting_data: dict[str, Any], value: Any) -> Any:
- """
- Convert a value to the appropriate type based on the setting's ui_element.
-
- Args:
- setting_data: The setting metadata containing ui_element
- value: The value to convert
-
- Returns:
- The typed value, or the original value if conversion fails
- """
- if value is None:
- return None
-
- ui_element = setting_data.get("ui_element", "text")
- setting_type = UI_ELEMENT_TO_SETTING_TYPE.get(ui_element)
-
- if setting_type is None:
- logger.warning(
- f"Unknown ui_element type: {ui_element}, returning value as-is"
- )
- return value
-
- try:
- return setting_type(value)
- except (ValueError, TypeError):
- # NEVER interpolate the VALUE here. This is the in-memory twin
- # of ``settings/manager.py``'s ``get_typed_setting_value``,
- # reached by the programmatic API and the MCP server, and a
- # settings value is a plausible secret carrier (an API key, or
- # a JSON container with one nested inside). The declared
- # ui_element and the value's type name identify the bad row
- # without disclosing it — the same fix applied to the DB
- # manager's converter in #6201.
- logger.warning(
- "Failed to convert a {} value for ui_element {} to type {} "
- "(value omitted)",
- type(value).__name__,
- ui_element,
- setting_type,
+ def _get_typed_value(
+ self,
+ setting_data: dict[str, Any],
+ value: Any,
+ *,
+ key: str | None = None,
+ ) -> Any:
+ """Validate a stored value without applying environment overrides."""
+ if not isinstance(setting_data, dict):
+ raise SettingsValueError(
+ key or "<in-memory>",
+ source="value",
+ reason="invalid setting metadata",
)
- return value
+ return get_typed_setting_value(
+ key if key is not None else setting_data.get("key", "<in-memory>"),
+ value,
+ setting_data.get("ui_element", "text"),
+ check_env=False,
+ )
def _load_defaults(self):
"""Load default settings from the JSON file."""
@@ -114,26 +97,93 @@ class InMemorySettingsManager(ISettingsManager):
except Exception:
logger.warning("Failed to load search engine configs")
+ def _read_setting_value(
+ self,
+ key: str,
+ setting_data: dict[str, Any],
+ default: Any = None,
+ check_env: bool = True,
+ ) -> Any:
+ """Read the selected value or report invalid configuration."""
+ if not isinstance(setting_data, dict):
+ raise SettingsValueError(
+ key, source="value", reason="invalid setting metadata"
+ )
+ ui_element = setting_data.get("ui_element", "text")
+ return get_typed_setting_value(
+ key,
+ setting_data.get("value"),
+ ui_element,
+ default=default,
+ check_env=check_env,
+ )
+
def get_setting(
self, key: str, default: Any = None, check_env: bool = True
) -> Any:
- """Get a setting value."""
+ """Read a typed value, or a namespace when no exact entry exists.
+
+ An environment override for a key with no entry and no declared
+ type is returned as the raw string, as ``SettingsManager`` does.
+ """
+ if not isinstance(key, str) or not key:
+ return default
+
+ if env_registry.is_env_only(key):
+ return env_registry.get_strict(key, default, check_env=check_env)
+
if key in self._settings:
setting_data = self._settings[key]
- if check_env:
- env_value = check_env_setting(key)
- if env_value is not None:
- return self._get_typed_value(setting_data, env_value)
- value = setting_data.get("value", default)
- # Ensure the value has the correct type
- return self._get_typed_value(setting_data, value)
+ return self._read_setting_value(
+ key, setting_data, default=default, check_env=check_env
+ )
+
+ # Preserve exact-entry precedence and the DB reader's scalar-only
+ # treatment of operator-owned paths. Malformed legacy children do
+ # not turn a missing leaf into a namespace.
+ if not is_operator_only_setting(key):
+ children = {
+ child.removeprefix(f"{key}."): self._read_setting_value(
+ child, data, default=default, check_env=check_env
+ )
+ for child, data in self._settings.items()
+ if is_valid_setting_key(child) and child.startswith(f"{key}.")
+ }
+ if children:
+ return children
+
+ if check_env:
+ env_value = check_env_setting(key)
+ if env_value is not None:
+ metadata = self._base_manager.default_settings.get(key)
+ if isinstance(metadata, dict):
+ return get_typed_setting_value(
+ key,
+ None,
+ metadata.get("ui_element", "text"),
+ default=default,
+ )
+ # Same as SettingsManager.get_setting: with no declared type
+ # there is nothing to validate against, so the override is
+ # returned unconverted. Typed keys still raise above.
+ logger.warning(
+ "Setting '{}' has env var override but is not in "
+ "defaults — returning raw string without type "
+ "conversion. Add this setting to a defaults JSON "
+ "file with a ui_element type to enable proper "
+ "type conversion.",
+ key,
+ )
+ return env_value
return default
def set_setting(self, key: str, value: Any, commit: bool = True) -> bool:
"""Set a setting value (in memory only)."""
if key in self._settings:
# Validate and convert the value to the correct type
- typed_value = self._get_typed_value(self._settings[key], value)
+ typed_value = self._get_typed_value(
+ self._settings[key], value, key=key
+ )
self._settings[key]["value"] = typed_value
return True
return False
@@ -144,20 +194,18 @@ class InMemorySettingsManager(ISettingsManager):
include_environment_overrides: bool = True,
strict: bool = False,
) -> dict[str, Any]:
- """Get all settings with metadata."""
+ """Validate effective settings, or return raw storage for repair.
+
+ Effective reads validate stored values without changing their saved
+ representation. Only active environment overrides replace values.
+ Raw exports skip validation and preserve the stored metadata.
+ """
result = copy.deepcopy(self._settings)
if include_environment_overrides:
for key, setting_data in result.items():
- if (
- not isinstance(setting_data, dict)
- or "value" not in setting_data
- ):
- continue
- env_value = check_env_setting(key)
- if env_value is not None:
- setting_data["value"] = self._get_typed_value(
- setting_data, env_value
- )
+ value = self._read_setting_value(key, setting_data)
+ if check_env_setting(key) is not None:
+ setting_data["value"] = value
setting_data["editable"] = False
return result
@@ -196,9 +244,9 @@ class InMemorySettingsManager(ISettingsManager):
"""Create or update a setting (in memory only)."""
if isinstance(setting, dict) and "key" in setting:
key = setting["key"]
- # If the setting has a value, ensure it has the correct type
+ # Validate metadata even when an optional value is absent.
+ typed_value = self._get_typed_value(setting, setting.get("value"))
if "value" in setting:
- typed_value = self._get_typed_value(setting, setting["value"])
setting = setting.copy() # Don't modify the original
setting["value"] = typed_value
self._settings[key] = setting
@@ -248,6 +296,9 @@ class InMemorySettingsManager(ISettingsManager):
) -> None:
"""Import settings from a dictionary.
+ Conversion failures leave the live settings unchanged. Values that
+ fail schema validation retain the existing skip-and-preserve policy.
+
``override_locked`` is accepted to satisfy the ``ISettingsManager``
contract (#5738) and otherwise ignored: the in-memory store has no
settings lock, so there is nothing for it to override.
@@ -257,6 +308,10 @@ class InMemorySettingsManager(ISettingsManager):
# docstring for the trusted-vs-untrusted rationale (values retained
# from existing in-memory state are trusted here, not validated).
defaults_for_import = self._base_manager.default_settings
+ # Rows are replaced, not mutated, during import. Stage those
+ # replacements so a later conversion error cannot expose a partial
+ # import or leave live settings cleared by delete_extra.
+ pending_settings = self._settings.copy()
# Under `delete_extra=True`, entries cleared below must still be
# restorable for keys whose imported value is rejected by
# validation — mirroring the DB manager, where a rejected key keeps
@@ -276,11 +331,10 @@ class InMemorySettingsManager(ISettingsManager):
if preserve_environment_locked
else {}
)
- self._settings.clear()
- self._settings.update(preserved)
+ pending_settings = preserved
for key, value in settings_data.items():
- existing_setting = self._settings.get(key)
+ existing_setting = pending_settings.get(key)
preserve_value = (
preserve_environment_locked
and check_env_setting(key) is not None
@@ -291,12 +345,16 @@ class InMemorySettingsManager(ISettingsManager):
# A bare-scalar import carries no metadata to merge; keep
# the stored env-locked entry untouched.
continue
- if overwrite or key not in self._settings or preserve_value:
+ if overwrite or key not in pending_settings or preserve_value:
# Ensure proper type handling for imported settings
setting_values = (
value.copy() if isinstance(value, dict) else value
)
- if isinstance(value, dict) and "value" in value:
+ if (
+ isinstance(value, dict)
+ and "value" in value
+ and not preserve_value
+ ):
default_meta = defaults_for_import.get(key)
if (
default_meta is not None
@@ -316,15 +374,19 @@ class InMemorySettingsManager(ISettingsManager):
key,
)
if prior_settings is not None and key in prior_settings:
- self._settings[key] = prior_settings[key]
+ pending_settings[key] = prior_settings[key]
continue
- typed_value = self._get_typed_value(value, value["value"])
+ typed_value = self._get_typed_value(
+ value, value["value"], key=key
+ )
setting_values["value"] = typed_value
if preserve_value:
setting_values["value"] = copy.deepcopy(
existing_setting["value"]
)
- self._settings[key] = setting_values
+ pending_settings[key] = setting_values
+
+ self._settings = pending_settings
def get_default_settings_snapshot() -> dict[str, Any]:
diff --git a/src/local_deep_research/benchmarks/web_api/benchmark_service.py b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
index c7f8eb6db6..b2c90c0240 100644
--- a/src/local_deep_research/benchmarks/web_api/benchmark_service.py
+++ b/src/local_deep_research/benchmarks/web_api/benchmark_service.py
@@ -13,6 +13,7 @@ from sqlalchemy.exc import SQLAlchemyError
from ...api.research_functions import quick_summary
from ...exceptions import ResearchTerminatedException
+from ...settings.exceptions import SettingsValueError
from ...settings.manager import SnapshotSettingsContext
from ...web.services.research_service import _global_research_semaphore
from ...database.models.benchmark import (
@@ -345,6 +346,9 @@ class BenchmarkService:
settings_manager = SettingsManager(session)
try:
settings_snapshot = settings_manager.get_all_settings()
+ except SettingsValueError:
+ # Invalid configuration cannot run with an empty snapshot.
+ raise
except (SQLAlchemyError, LookupError, ValueError):
# Use logger.exception so the traceback goes to stderr
# without splatting `repr(exc)` into the message body —
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index a6e42d4b1b..1651cc62ea 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -10,6 +10,7 @@ from loguru import logger
from ..llm import get_llm_from_registry, is_llm_registered
from ..security.log_sanitizer import sanitize_for_log, scrub_error
from ..security.secure_logging import log_exception_type
+from ..settings.exceptions import SettingsValueError
from ..utilities.search_utilities import remove_think_tags
# Import providers module to trigger auto-discovery. get_llm() has no
@@ -769,6 +770,8 @@ class ProcessingLLMWrapper:
settings_snapshot=snapshot,
):
return True
+ except SettingsValueError:
+ raise
except Exception:
logger.debug(
"stream_usage setting lookup failed; "
diff --git a/src/local_deep_research/config/thread_settings.py b/src/local_deep_research/config/thread_settings.py
index a0d442a471..2ce38fd934 100644
--- a/src/local_deep_research/config/thread_settings.py
+++ b/src/local_deep_research/config/thread_settings.py
@@ -133,7 +133,7 @@ def get_setting_from_snapshot(
# Handle both full format {"value": x} and simplified format (just x)
if isinstance(v, dict) and "value" in v:
v = get_typed_setting_value(
- child, v["value"], v.get("ui_element", "text")
+ full_key, v["value"], v.get("ui_element", "text")
)
# else: v is already the raw value from simplified snapshot
if value is _NOT_FOUND:
diff --git a/src/local_deep_research/defaults/default_settings.json b/src/local_deep_research/defaults/default_settings.json
index 77ae7558a7..72d1729881 100644
--- a/src/local_deep_research/defaults/default_settings.json
+++ b/src/local_deep_research/defaults/default_settings.json
@@ -539,7 +539,7 @@
},
"llm.request_timeout": {
"category": "llm_parameters",
- "description": "Per-operation HTTP timeout in seconds for LLM inference and embedding requests, applied to every supported provider. It bounds each connect, write and wait for the next response chunk individually; it is not a cap on the total duration of a response. A peer that keeps sending data can exceed this value, including for a non-streaming response. Connecting is separately capped at 5 seconds for OpenAI-compatible and Ollama clients; Anthropic inference uses this value for connecting too. There is no upper limit; values below 1 second are clamped to 1, and non-numeric or non-finite values use the default. Model discovery is unaffected: OpenAI-compatible providers and Anthropic use 30 seconds, while Google and Ollama retain provider-specific limits of 10 and 5 seconds, respectively.",
+ "description": "Per-operation HTTP timeout in seconds for LLM inference and embedding requests, applied to every supported provider. It bounds each connect, write and wait for the next response chunk individually; it is not a cap on the total duration of a response. A peer that keeps sending data can exceed this value, including for a non-streaming response. Connecting is separately capped at 5 seconds for OpenAI-compatible and Ollama clients; Anthropic inference uses this value for connecting too. There is no upper limit. Configured values must be finite numbers of at least 1 second; invalid values raise a settings error instead of being replaced. An absent or unset optional value uses the default. Model discovery is unaffected: OpenAI-compatible providers and Anthropic use 30 seconds, while Google and Ollama retain provider-specific limits of 10 and 5 seconds, respectively.",
"editable": true,
"max_value": null,
"min_value": 1,
@@ -553,7 +553,7 @@
},
"llm.max_retries": {
"category": "llm_parameters",
- "description": "Maximum provider SDK retries per failed inference or embedding request. Applies to OpenAI-compatible and Anthropic SDKs; the Ollama client does not retry. Values outside 0-5 are clamped. Each retry starts another request with its own per-operation timeouts; SDK backoff or server-requested retry delays can further extend elapsed time. This setting does not impose a total request deadline. Model discovery SDK retries are disabled.",
+ "description": "Maximum provider SDK retries per failed inference or embedding request. Applies to OpenAI-compatible and Anthropic SDKs; the Ollama client does not retry. Configured values must be finite numbers within 0-5; invalid values raise a settings error instead of being replaced. An absent or unset optional value uses the default. Each retry starts another request with its own per-operation timeouts; SDK backoff or server-requested retry delays can further extend elapsed time. This setting does not impose a total request deadline. Model discovery SDK retries are disabled.",
"editable": true,
"max_value": 5,
"min_value": 0,
diff --git a/src/local_deep_research/embeddings/providers/implementations/openai.py b/src/local_deep_research/embeddings/providers/implementations/openai.py
index 64ae0339d4..261dc30789 100644
--- a/src/local_deep_research/embeddings/providers/implementations/openai.py
+++ b/src/local_deep_research/embeddings/providers/implementations/openai.py
@@ -11,6 +11,7 @@ from ....config.thread_settings import get_setting_from_snapshot
from ....security.log_sanitizer import redact_secrets
from ....security.ssrf_validator import assert_base_url_safe
from ....security.url_redaction import redact_url_credentials
+from ....settings.exceptions import SettingsValueError
from ....utilities.url_utils import normalize_url
from ..base import BaseEmbeddingProvider, Exposure
@@ -325,6 +326,8 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
settings_snapshot=settings_snapshot,
)
return bool(base_url and str(base_url).strip())
+ except SettingsValueError:
+ raise
except Exception as e:
# Drop exc_info — the traceback would render the exception's
# cause chain, which may embed the api_key value if a
@@ -428,6 +431,8 @@ class OpenAIEmbeddingsProvider(BaseEmbeddingProvider):
)
return models
+ except SettingsValueError:
+ raise
except Exception as e:
if http_client is not None and not client_entered:
try:
diff --git a/src/local_deep_research/llm/providers/_helpers.py b/src/local_deep_research/llm/providers/_helpers.py
index cc93f58383..510a550068 100644
--- a/src/local_deep_research/llm/providers/_helpers.py
+++ b/src/local_deep_research/llm/providers/_helpers.py
@@ -9,7 +9,7 @@ LLM construction logic — no per-provider drift.
import math
from typing import Any, Final
-from ...security.secure_logging import logger
+from ...settings.exceptions import SettingsValueError
DEFAULT_LOCAL_CONTEXT_WINDOW_SIZE = 8192
@@ -133,12 +133,7 @@ def compute_max_tokens(
def _get_setting_value(settings_snapshot, key: str, default: Any) -> Any:
- """Read ``key`` from the snapshot, degrading to ``default``.
-
- Every other setting reader on the LLM-construction path degrades to a
- default rather than raising; this one must too. A bad value here would
- otherwise take down every LLM construction in the process.
- """
+ """Read an optional setting; invalid configured values must propagate."""
from ...config.thread_settings import (
get_setting_from_snapshot,
NoSettingsContextError,
@@ -148,23 +143,11 @@ def _get_setting_value(settings_snapshot, key: str, default: Any) -> Any:
return get_setting_from_snapshot(
key, default, settings_snapshot=settings_snapshot
)
- except (NoSettingsContextError, OverflowError):
- # Full-format number entries are coerced by the settings reader
- # before _clamp_number runs. An oversized integer can overflow there.
+ except NoSettingsContextError:
return default
-def _raw_snapshot_value(settings_snapshot, key: str) -> Any:
- """Return the pre-coercion snapshot value for ``key`` (or ``None``)."""
- if not settings_snapshot:
- return None
- raw = settings_snapshot.get(key)
- if isinstance(raw, dict):
- return raw.get("value")
- return raw
-
-
-def _clamp_number(
+def _validate_number(
key: str,
value: Any,
*,
@@ -172,50 +155,39 @@ def _clamp_number(
minimum: float,
maximum: float | None,
) -> float:
- """Coerce ``value`` to a finite float inside ``[minimum, maximum]``.
+ """Validate ``value`` as a finite float inside ``[minimum, maximum]``.
``maximum=None`` means no upper bound; the value is still required to be
finite, so ``inf`` cannot pass as 'no timeout'.
- Unusable shapes fall back to ``default`` and out-of-range numbers are
- clamped — never raised. An operator typo in a single numeric field
- must not be a self-inflicted outage of every LLM call.
+ Only an unset value uses ``default``. Invalid configured values raise
+ without including the value or a parser exception in the error.
"""
if value is None:
return float(default)
if isinstance(value, bool):
- logger.warning(
- "Setting {} is a boolean, which is not a valid number; using {}.",
- key,
- default,
+ raise SettingsValueError(
+ key, source="snapshot", reason="expected a finite number"
)
- return float(default)
+ number = None
try:
number = float(value)
except (TypeError, ValueError, OverflowError):
- logger.warning(
- "Setting {} is not a usable number; using {}.", key, default
+ pass
+ # Raise outside the parser handler so its exception cannot expose a
+ # configured value through __context__.
+ if number is None or not math.isfinite(number):
+ raise SettingsValueError(
+ key, source="snapshot", reason="expected a finite number"
)
- return float(default)
- if not math.isfinite(number):
- logger.warning("Setting {} is not finite; using {}.", key, default)
- return float(default)
if number < minimum:
- logger.warning(
- "Setting {}={} is below the supported minimum; clamping to {}.",
- key,
- number,
- minimum,
+ raise SettingsValueError(
+ key, source="snapshot", reason=f"must be at least {minimum}"
)
- return float(minimum)
if maximum is not None and number > maximum:
- logger.warning(
- "Setting {}={} is above the supported maximum; clamping to {}.",
- key,
- number,
- maximum,
+ raise SettingsValueError(
+ key, source="snapshot", reason=f"must be at most {maximum}"
)
- return float(maximum)
return number
@@ -227,22 +199,12 @@ def _resolve_bounded_number(
minimum: float,
maximum: float | None,
) -> float:
- """Read a numeric setting and force it into ``[minimum, maximum]``.
+ """Read a numeric setting and validate its supported bounds.
``maximum=None`` means no upper bound; the value is still required to
be a finite number, so ``inf`` cannot slip through as 'no timeout'.
"""
- if isinstance(_raw_snapshot_value(settings_snapshot, key), bool):
- # A full-format snapshot entry would be coerced from ``True`` to
- # ``1`` by the number parser before we could see it, so the raw
- # stored value has to be inspected separately.
- logger.warning(
- "Setting {} is a boolean, which is not a valid number; using {}.",
- key,
- default,
- )
- return float(default)
- return _clamp_number(
+ return _validate_number(
key,
_get_setting_value(settings_snapshot, key, default),
default=default,
@@ -271,8 +233,8 @@ def resolve_request_timeout(settings_snapshot=None) -> float:
def resolve_max_retries(settings_snapshot=None) -> int:
"""Resolve the bounded SDK retry count shared by all clients.
- Retries multiply the number of attempts, so this is capped at
- ``MAX_MAX_RETRIES``. Each attempt has its own per-operation timeouts;
+ Retries multiply the number of attempts, so the configured value must
+ not exceed ``MAX_MAX_RETRIES``. Each attempt has per-operation timeouts;
SDK backoff and server-directed delays also affect total elapsed time.
"""
return int(
diff --git a/src/local_deep_research/llm/providers/base.py b/src/local_deep_research/llm/providers/base.py
index 483deafe17..e7115ecf22 100644
--- a/src/local_deep_research/llm/providers/base.py
+++ b/src/local_deep_research/llm/providers/base.py
@@ -1,6 +1,7 @@
"""Base class for LLM providers."""
from ...security.egress.classification import Exposure
+from ...settings.exceptions import SettingsValueError
# Single placeholder for ChatOpenAI(api_key=...) when no real key is
# configured (unauthenticated local LM Studio, llama.cpp, etc.). Subclasses
@@ -171,12 +172,14 @@ class BaseLLMProvider:
"""Build an ``Authorization: Bearer`` header from the resolved key.
Returns an empty dict when no real key is configured (so callers
- can spread it conditionally). Required-key providers that raise
- from ``resolve_api_key`` are treated as "no header" here too —
- the construction-time error happens elsewhere.
+ can spread it conditionally). A missing required key is treated as
+ "no header" here too; its construction-time error happens elsewhere.
+ Invalid configured values must propagate rather than remove auth.
"""
try:
key = cls.resolve_api_key(settings_snapshot)
+ except SettingsValueError:
+ raise
except ValueError:
return {}
return {"Authorization": f"Bearer {key}"} if key else {}
@@ -187,10 +190,12 @@ class BaseLLMProvider:
Returns False for missing/whitespace keys (required providers raise
ValueError; we swallow it). Also returns False on broader settings
- errors so callers like ``is_available()`` fail closed instead of
- propagating settings infrastructure failures.
+ infrastructure errors so callers like ``is_available()`` fail closed.
+ Invalid configured values propagate instead of appearing absent.
"""
try:
return cls.resolve_api_key(settings_snapshot) is not None
+ except SettingsValueError:
+ raise
except Exception:
return False
diff --git a/src/local_deep_research/llm/providers/implementations/custom_anthropic_endpoint.py b/src/local_deep_research/llm/providers/implementations/custom_anthropic_endpoint.py
index 83446af9e9..cf5cc37bd5 100644
--- a/src/local_deep_research/llm/providers/implementations/custom_anthropic_endpoint.py
+++ b/src/local_deep_research/llm/providers/implementations/custom_anthropic_endpoint.py
@@ -10,6 +10,7 @@ from ....security.secure_logging import logger
from ....config.thread_settings import get_setting_from_snapshot
from ....security.log_sanitizer import redact_secrets
+from ....settings.exceptions import SettingsValueError
from ..base import Exposure
from .anthropic import AnthropicProvider
@@ -64,6 +65,8 @@ class CustomAnthropicEndpointProvider(AnthropicProvider):
)
if api_key and str(api_key).strip():
return True
+ except SettingsValueError:
+ raise
except Exception as e:
# Redact in case a settings-layer error message embeds the key.
safe_msg = redact_secrets(str(e), api_key)
@@ -77,6 +80,8 @@ class CustomAnthropicEndpointProvider(AnthropicProvider):
)
if custom_url and str(custom_url).strip():
return True
+ except SettingsValueError:
+ raise
except Exception:
logger.debug(
f"Error reading URL setting '{cls.url_setting}'",
diff --git a/src/local_deep_research/llm/providers/implementations/custom_openai_endpoint.py b/src/local_deep_research/llm/providers/implementations/custom_openai_endpoint.py
index 500229fff7..94d8be4203 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
@@ -4,6 +4,7 @@ from ....security.secure_logging import logger
from ....config.thread_settings import get_setting_from_snapshot
from ....security.log_sanitizer import redact_secrets
+from ....settings.exceptions import SettingsValueError
from ....utilities.url_utils import normalize_url
from ..base import Exposure
from ..openai_base import OpenAICompatibleProvider
@@ -60,6 +61,8 @@ class CustomOpenAIEndpointProvider(OpenAICompatibleProvider):
)
if api_key and str(api_key).strip():
return True
+ except SettingsValueError:
+ raise
except Exception as e:
# Drop exc_info — the cause chain may embed the api_key value
# if a settings-layer error message surfaces it. Interpolate
@@ -77,6 +80,8 @@ class CustomOpenAIEndpointProvider(OpenAICompatibleProvider):
normalized = normalize_url(str(custom_url).strip())
if normalized.rstrip("/") != cls.default_base_url.rstrip("/"):
return True
+ except SettingsValueError:
+ raise
except Exception:
logger.debug(
f"Error reading URL setting '{cls.url_setting}'",
diff --git a/src/local_deep_research/llm/providers/implementations/llamacpp.py b/src/local_deep_research/llm/providers/implementations/llamacpp.py
index 6517ef7f0e..6c2bb937d4 100644
--- a/src/local_deep_research/llm/providers/implementations/llamacpp.py
+++ b/src/local_deep_research/llm/providers/implementations/llamacpp.py
@@ -7,6 +7,7 @@ beyond a single endpoint, use the `openai_endpoint` provider directly.
"""
from ....config.constants import DEFAULT_LLAMACPP_URL
+from ....settings.exceptions import SettingsValueError
from ....utilities.url_utils import normalize_url
from ..base import Exposure
from ..openai_base import OpenAICompatibleProvider
@@ -88,6 +89,8 @@ class LlamaCppProvider(OpenAICompatibleProvider):
allow_private_ips=True,
)
return response.status_code == 200
+ except SettingsValueError:
+ raise
except Exception:
return False
diff --git a/src/local_deep_research/llm/providers/implementations/lmstudio.py b/src/local_deep_research/llm/providers/implementations/lmstudio.py
index 8632c2786d..31359927b9 100644
--- a/src/local_deep_research/llm/providers/implementations/lmstudio.py
+++ b/src/local_deep_research/llm/providers/implementations/lmstudio.py
@@ -1,6 +1,7 @@
"""LM Studio LLM provider for Local Deep Research."""
from ....config.constants import DEFAULT_LMSTUDIO_URL
+from ....settings.exceptions import SettingsValueError
from ....utilities.url_utils import normalize_url
from ..base import Exposure
from ..openai_base import OpenAICompatibleProvider
@@ -103,6 +104,8 @@ class LMStudioProvider(OpenAICompatibleProvider):
allow_private_ips=True,
)
return response.status_code == 200
+ except SettingsValueError:
+ raise
except Exception:
return False
diff --git a/src/local_deep_research/llm/providers/implementations/ollama.py b/src/local_deep_research/llm/providers/implementations/ollama.py
index c29ede5f70..de711548e7 100644
--- a/src/local_deep_research/llm/providers/implementations/ollama.py
+++ b/src/local_deep_research/llm/providers/implementations/ollama.py
@@ -10,6 +10,7 @@ from ....security.secure_logging import logger
from ....security.log_sanitizer import scrub_error
from ....security.ssrf_validator import assert_base_url_safe
from ....security.url_redaction import redact_url_credentials
+from ....settings.exceptions import SettingsValueError
from ....utilities.url_utils import normalize_url
from ..base import BaseLLMProvider, Exposure
@@ -287,6 +288,8 @@ class OllamaProvider(BaseLLMProvider):
except Exception:
logger.warning("Unexpected error when checking Ollama")
return False
+ except SettingsValueError:
+ raise
except Exception:
logger.warning("Error in OllamaProvider.is_available")
return False
diff --git a/src/local_deep_research/llm/providers/openai_base.py b/src/local_deep_research/llm/providers/openai_base.py
index e8ec40f211..28ed44f497 100644
--- a/src/local_deep_research/llm/providers/openai_base.py
+++ b/src/local_deep_research/llm/providers/openai_base.py
@@ -12,6 +12,7 @@ from ...security.secure_logging import logger
from ...security.log_sanitizer import redact_secrets, scrub_error
from ...security.ssrf_validator import assert_base_url_safe
from ...security.url_redaction import redact_url_credentials
+from ...settings.exceptions import SettingsValueError
from ...utilities.url_utils import normalize_url
from ._helpers import (
MODEL_DISCOVERY_TIMEOUT_SECONDS,
@@ -430,6 +431,8 @@ class OpenAICompatibleProvider(BaseLLMProvider):
return cls.list_models_for_api(api_key, base_url)
+ except SettingsValueError:
+ raise
except Exception as e:
# Upstream exception messages (e.g., requests.HTTPError, OpenAI
# SDK errors from a subclass that builds the URL with the key in
diff --git a/src/local_deep_research/news/api.py b/src/local_deep_research/news/api.py
index c90780f7be..67c805d462 100644
--- a/src/local_deep_research/news/api.py
+++ b/src/local_deep_research/news/api.py
@@ -14,6 +14,7 @@ from .constants import validate_refresh_interval
from ..llm.providers.base import normalize_provider
from ..utilities.sql_utils import escape_like
from ..security.log_sanitizer import redact_and_bound_for_log
+from ..settings.exceptions import SettingsValueError
from .exceptions import (
InvalidLimitException,
SubscriptionNotFoundException,
@@ -1041,7 +1042,10 @@ def _validate_subscription_policy(
Best-effort: if the settings backend or policy module is unavailable
(e.g. programmatic API use without a settings DB), validation is
- skipped — the execution-time factory PEP remains the backstop.
+ skipped — the execution-time factory PEP remains the backstop. An
+ invalid configured setting is not such a failure: the check cannot run,
+ so the subscription is rejected with the setting's diagnostic, which
+ names the key but not the value.
"""
try:
from ..utilities.db_utils import get_settings_manager
@@ -1065,6 +1069,10 @@ def _validate_subscription_policy(
)
except PolicyDeniedError as exc:
return f"egress policy refused: {exc.decision.reason}"
+ except SettingsValueError:
+ # A ValueError subclass, but not an incoherent policy: the outer
+ # handler names the invalid setting.
+ raise
except ValueError as exc:
# An incoherent egress config makes context_from_snapshot
# raise ValueError. Surface it as a validation failure at
@@ -1101,6 +1109,11 @@ def _validate_subscription_policy(
f"under the current egress policy ({decision.reason})"
)
return None
+ except SettingsValueError as error:
+ # The snapshot read validates every effective setting, so one invalid
+ # row anywhere lands here. Skipping the check would persist a
+ # subscription the policy was never applied to.
+ return error.diagnostic
except Exception:
# Settings/policy unavailable → skip; execution-time PEP backstops.
logger.debug("subscription policy pre-check skipped", exc_info=True)
diff --git a/src/local_deep_research/research_library/zotero/sync_service.py b/src/local_deep_research/research_library/zotero/sync_service.py
index c4dd64398e..d1dc231ae7 100644
--- a/src/local_deep_research/research_library/zotero/sync_service.py
+++ b/src/local_deep_research/research_library/zotero/sync_service.py
@@ -60,6 +60,7 @@ from ...security import (
UnsafeFilenameError,
)
from ...settings.manager import SettingsManager
+from ...settings.exceptions import SettingsValueError
from ...utilities.type_utils import to_bool
from ..deletion.utils.cascade_helper import CascadeHelper
from ..services.pdf_storage_manager import (
@@ -241,6 +242,8 @@ class ZoteroSyncService:
interval = int(
sm.get_setting("zotero.sync_interval_minutes", 360) or 360
)
+ except SettingsValueError:
+ raise
except (TypeError, ValueError):
interval = 360
return ZoteroConfig(
diff --git a/src/local_deep_research/scheduler/background.py b/src/local_deep_research/scheduler/background.py
index 4e23662eac..418fbd6f29 100644
--- a/src/local_deep_research/scheduler/background.py
+++ b/src/local_deep_research/scheduler/background.py
@@ -13,6 +13,7 @@ from typing import Any, Callable, Dict, List
from cachetools import TTLCache
from loguru import logger
from ..settings.logger import log_settings
+from ..settings.exceptions import SettingsValueError
from ..settings.manager import SnapshotSettingsContext
from apscheduler.schedulers.background import BackgroundScheduler
@@ -236,6 +237,10 @@ class BackgroundJobScheduler:
),
}
log_settings(self.config, "Scheduler configuration loaded")
+ except SettingsValueError:
+ # Startup must not continue with unrelated defaults when any
+ # configured scheduler value is invalid.
+ raise
except Exception:
logger.exception("Error loading scheduler settings")
# Keep default config
@@ -355,6 +360,8 @@ class BackgroundJobScheduler:
return settings
+ except SettingsValueError:
+ raise
except Exception as e:
# ``password`` (retrieved above) is in the frame locals of
# this handler and of ``get_user_db_session``; a traceback
@@ -1531,6 +1538,8 @@ class BackgroundJobScheduler:
"rag.indexing_max_parallel_docs", 4
)
)
+ except SettingsValueError:
+ raise
except Exception:
_max_parallel = 4
_max_parallel = max(1, min(_max_parallel, 16))
diff --git a/src/local_deep_research/settings/__init__.py b/src/local_deep_research/settings/__init__.py
index c207c12cdf..8c370b09a3 100644
--- a/src/local_deep_research/settings/__init__.py
+++ b/src/local_deep_research/settings/__init__.py
@@ -12,6 +12,7 @@ from .exceptions import (
EnvironmentValueRangeError,
InvalidEnvironmentValueError,
MissingEnvironmentVariableError,
+ SettingsValueError,
)
from .manager import SettingsManager, SnapshotSettingsContext
@@ -24,4 +25,5 @@ __all__ = [
"EnvironmentValueRangeError",
"InvalidEnvironmentValueError",
"MissingEnvironmentVariableError",
+ "SettingsValueError",
]
diff --git a/src/local_deep_research/settings/base.py b/src/local_deep_research/settings/base.py
index 42a2bb85bb..a29844adda 100644
--- a/src/local_deep_research/settings/base.py
+++ b/src/local_deep_research/settings/base.py
@@ -26,6 +26,10 @@ class ISettingsManager(ABC):
Returns:
Setting value or default if not found
+
+ Raises:
+ SettingsValueError: The selected value cannot be converted to its
+ declared type, or that type is unsupported.
"""
pass
@@ -61,6 +65,11 @@ class ISettingsManager(ABC):
Returns:
Dictionary of all settings with metadata
+
+ Raises:
+ SettingsValueError: With ``include_environment_overrides``, any
+ effective value cannot be converted to its declared type, or
+ that type is unsupported.
"""
pass
diff --git a/src/local_deep_research/settings/env_settings.py b/src/local_deep_research/settings/env_settings.py
index f4dec440cb..e6ed087f15 100644
--- a/src/local_deep_research/settings/env_settings.py
+++ b/src/local_deep_research/settings/env_settings.py
@@ -32,6 +32,7 @@ from .exceptions import (
EnvironmentValueRangeError,
InvalidEnvironmentValueError,
MissingEnvironmentVariableError,
+ SettingsValueError,
)
T = TypeVar("T")
@@ -57,17 +58,21 @@ class EnvSetting(ABC, Generic[T]):
self.required = required
self.deprecated_env_var = deprecated_env_var
- def get_value(self) -> Optional[T]:
+ def get_value(
+ self, *, strict: bool = False, check_env: bool = True
+ ) -> Optional[T]:
"""Get the value from environment with type conversion."""
- raw = self._get_raw_value()
+ raw = self._get_raw_value() if check_env else None
if raw is None:
if self.required and self.default is None:
raise MissingEnvironmentVariableError(self.env_var)
return self.default
+ if strict:
+ return self._convert_value(raw, strict=True)
return self._convert_value(raw)
@abstractmethod
- def _convert_value(self, raw: str) -> T:
+ def _convert_value(self, raw: str, *, strict: bool = False) -> T:
"""Convert raw string value to the appropriate type."""
pass
@@ -118,8 +123,15 @@ class BooleanSetting(EnvSetting[bool]):
key, description, default, deprecated_env_var=deprecated_env_var
)
- def _convert_value(self, raw: str) -> bool:
+ def _convert_value(self, raw: str, *, strict: bool = False) -> bool:
"""Convert string to boolean."""
+ if strict:
+ normalized = raw.strip().lower()
+ if normalized in ("true", "1", "yes", "on", "enabled"):
+ return True
+ if normalized in ("false", "0", "no", "off", "disabled", ""):
+ return False
+ raise ValueError("Expected a boolean token")
return raw.lower() in ("true", "1", "yes", "on", "enabled")
@@ -142,7 +154,7 @@ class StringSetting(EnvSetting[str]):
deprecated_env_var=deprecated_env_var,
)
- def _convert_value(self, raw: str) -> str:
+ def _convert_value(self, raw: str, *, strict: bool = False) -> str:
"""Return string value as-is."""
return raw
@@ -198,7 +210,9 @@ class IntegerSetting(EnvSetting[int]):
self.raise_on_validation_error = raise_on_validation_error
self.strict_digits = strict_digits
- def _convert_value(self, raw: str) -> Optional[int]:
+ def _convert_value(
+ self, raw: str, *, strict: bool = False
+ ) -> Optional[int]:
"""Convert string to integer with validation."""
candidate = raw.strip()
if not candidate:
@@ -222,6 +236,8 @@ class IntegerSetting(EnvSetting[int]):
parse_error = exc
if parse_error is not None:
+ if strict:
+ raise parse_error
if self.raise_on_validation_error:
raise InvalidEnvironmentValueError(
self.env_var, raw, expected_type="integer"
@@ -257,11 +273,15 @@ class PathSetting(StringSetting):
self.must_exist = must_exist
self.create_if_missing = create_if_missing
- def get_value(self) -> Optional[str]:
+ def get_value(
+ self, *, strict: bool = False, check_env: bool = True
+ ) -> Optional[str]:
"""Get path value with optional validation/creation."""
- path_str = super().get_value()
- if path_str is None:
- return None
+ path_str = super().get_value(strict=strict, check_env=check_env)
+ if path_str is None or not check_env:
+ return path_str
+ if strict and not path_str.strip():
+ raise ValueError("Expected a nonempty path")
# Use pathlib for path operations
path = Path(path_str).expanduser()
@@ -271,19 +291,37 @@ class PathSetting(StringSetting):
path_str = os.path.expandvars(str(path))
path = Path(path_str).resolve()
+ if (
+ strict
+ and self.create_if_missing
+ and path.exists()
+ and not path.is_dir()
+ ):
+ raise ValueError("Expected a directory")
if self.create_if_missing and not path.exists():
- try:
- # Lazy import: this module is loaded very early (bootstrap
- # env-only settings), before the database and app are
- # initialized, so importing security at module load time
- # risks an import cycle.
- from ..security.directory_creation import create_directory
+ # Lazy import: this module is loaded very early (bootstrap
+ # env-only settings), before the database and app are
+ # initialized, so importing security at module load time
+ # risks an import cycle.
+ from ..security.directory_creation import (
+ DirectoryCreationSecurityError,
+ create_directory,
+ )
+ try:
create_directory(
path,
context=f"env-configured path setting '{self.key}'",
)
+ except DirectoryCreationSecurityError:
+ if strict:
+ raise ValueError(
+ "Could not prepare configured path"
+ ) from None
+ raise
except OSError:
+ if strict:
+ raise
logger.warning("Failed to create directory")
elif self.must_exist and not path.exists():
# Only raise if explicitly required to exist
@@ -338,7 +376,7 @@ class EnumSetting(EnvSetting[str]):
# Create a mapping from lowercase to original case
self._canonical_map = {v.lower(): v for v in allowed_values}
- def _convert_value(self, raw: str) -> str:
+ def _convert_value(self, raw: str, *, strict: bool = False) -> str:
"""Convert and validate value against allowed values."""
if self.case_sensitive:
if raw not in self.allowed_values:
@@ -399,6 +437,62 @@ class SettingsRegistry:
)
return default
+ def get_strict(
+ self,
+ key: str,
+ default: Optional[Any] = None,
+ *,
+ check_env: bool = True,
+ ) -> Any:
+ """Read for a settings manager without hiding invalid configuration.
+
+ Missing optional settings retain their registered or caller default.
+ Disabling environment lookup also disables path resolution/creation.
+ The legacy bootstrap ``get`` API retains its historical behavior.
+ """
+ setting = self._settings.get(key)
+ if setting is None:
+ return default
+
+ source = "default"
+ if check_env and (
+ setting.env_var in os.environ
+ or (
+ setting.deprecated_env_var is not None
+ and setting.deprecated_env_var in os.environ
+ )
+ ):
+ source = "environment"
+
+ # A custom converter has no strict-read contract. Do not call it and
+ # accidentally accept a fallback or suppress its validation failure.
+ reasons = {
+ BooleanSetting: "expected a boolean token",
+ IntegerSetting: "expected an integer within the allowed range",
+ EnumSetting: "expected one of the declared choices",
+ PathSetting: "could not resolve or prepare the configured path",
+ StringSetting: "required value is missing",
+ SecretSetting: "required value is missing",
+ }
+ reason = reasons.get(type(setting))
+ if reason is None:
+ raise SettingsValueError(
+ key,
+ source=source,
+ reason="unsupported environment setting type",
+ )
+
+ try:
+ value = setting.get_value(strict=True, check_env=check_env)
+ except (ValueError, TypeError, OSError, RuntimeError):
+ # Converters and filesystem errors can contain configured secrets
+ # or paths. Raise outside the handler so no raw exception is kept
+ # as the exception context or emitted in the traceback.
+ pass
+ else:
+ return value if value is not None else default
+ raise SettingsValueError(key, source=source, reason=reason)
+
def get_setting_object(self, key: str) -> Optional[EnvSetting]:
"""Get the setting object itself for introspection."""
return self._settings.get(key)
diff --git a/src/local_deep_research/settings/exceptions.py b/src/local_deep_research/settings/exceptions.py
index 967b3101d9..a7d2b8f8d2 100644
--- a/src/local_deep_research/settings/exceptions.py
+++ b/src/local_deep_research/settings/exceptions.py
@@ -5,6 +5,30 @@ from pathlib import Path
from typing import Any
+class SettingsValueError(ValueError):
+ """A configured setting cannot be read safely.
+
+ Include only the setting key, source and a fixed diagnostic reason. Values
+ and the exceptions raised while parsing them may contain credentials.
+ """
+
+ def __init__(self, key: str, *, source: str, reason: str):
+ self.key = key
+ self.source = source
+ self.reason = reason
+ super().__init__(self.diagnostic)
+
+ @property
+ def diagnostic(self) -> str:
+ """Return the setting key, its source and the reason, without a value.
+
+ HTTP handlers return this text so an operator can locate the setting.
+ It is rebuilt from the three fields rather than taken from the
+ exception's arguments.
+ """
+ return f"Invalid setting {self.key!r} from {self.source}: {self.reason}"
+
+
class EnvSettingError(ValueError):
"""Base class for environment setting errors."""
diff --git a/src/local_deep_research/settings/manager.py b/src/local_deep_research/settings/manager.py
index ac0b57ae6e..97bfa629b3 100644
--- a/src/local_deep_research/settings/manager.py
+++ b/src/local_deep_research/settings/manager.py
@@ -1,5 +1,6 @@
import functools
import json
+import math
import os
import string
import threading
@@ -27,6 +28,7 @@ from ..web.models.settings import (
)
from .base import ISettingsManager
from .env_registry import registry as env_registry
+from .exceptions import SettingsValueError
# Existing saved values remain in place, but accounts cannot redirect library
@@ -121,7 +123,11 @@ def parse_boolean(value: Any) -> bool:
def _parse_number(x):
"""Parse number, returning int if it's a whole number, otherwise float."""
+ if isinstance(x, bool):
+ raise ValueError("Expected a number")
f = float(x)
+ if not math.isfinite(f):
+ raise ValueError("Expected a finite number")
if f.is_integer():
return int(f)
return f
@@ -141,7 +147,9 @@ def _parse_json_value(x):
try:
return json.loads(stripped)
except (json.JSONDecodeError, ValueError, RecursionError):
- logger.warning("Failed to parse JSON value, returning raw")
+ # The JSON database column may already contain a decoded
+ # scalar string. Preserve that value; environment input is
+ # known to be encoded and is parsed strictly by the reader.
return x
return x
@@ -158,16 +166,16 @@ def _parse_multiselect(x):
return x
if isinstance(x, str):
stripped = x.strip()
- if stripped.startswith("["):
- try:
- parsed = json.loads(stripped)
- if isinstance(parsed, list):
- return parsed
- except (json.JSONDecodeError, ValueError, RecursionError):
- pass
- # Comma-separated fallback
+ if stripped.startswith(("[", "{")):
+ parsed = json.loads(stripped)
+ if not isinstance(parsed, list):
+ raise ValueError("Expected a list")
+ return parsed
+ # Comma-separated values are an explicitly supported input format.
return [item.strip() for item in stripped.split(",") if item.strip()]
- return x
+ if x is None:
+ return None
+ raise ValueError("Expected a list or comma-separated values")
def _filter_setting_columns(data: dict) -> dict:
@@ -232,14 +240,7 @@ def validate_imported_setting_value(
not isinstance(ui_element, str)
or ui_element not in UI_ELEMENT_TO_SETTING_TYPE
):
- # An unknown ui_element comes from the shipped defaults, not from the
- # imported file: default_meta is self.default_settings. There is
- # nothing to enforce for one, and probing get_typed_setting_value
- # would log a default-substitution warning about a value this path
- # stores verbatim. That value is then dead on read: the same helper
- # substitutes the default for an element the type map lacks, so the
- # imported value never comes back out.
- return None
+ return "Unsupported setting type"
if value == default_meta.get("value"):
# The value equals the currently shipped default, so the defaults
@@ -257,13 +258,16 @@ def validate_imported_setting_value(
# the registry does serve.
return None
- typed_value = get_typed_setting_value(
- key=key,
- value=value,
- ui_element=ui_element,
- default=None,
- check_env=False,
- )
+ try:
+ typed_value = get_typed_setting_value(
+ key=key,
+ value=value,
+ ui_element=ui_element,
+ default=None,
+ check_env=False,
+ )
+ except SettingsValueError as error:
+ return error.reason
if typed_value is None:
# A shipped optional default may legitimately be null; the equality
# guard above accepts that exact value. Otherwise this is either an
@@ -502,6 +506,21 @@ UI_ELEMENT_TO_SETTING_TYPE: Dict[str, Callable[..., Any]] = {
}
+def _reject_json_constant(_value: str):
+ """Reject JSON's non-standard NaN/Infinity extensions without echoing input."""
+ raise ValueError("Expected a finite JSON number")
+
+
+def _parse_environment_boolean(value: str) -> bool:
+ """Environment input has no HTML checkbox presence semantics."""
+ normalized = value.strip().lower()
+ if normalized in ("true", "1", "yes", "on", "enabled"):
+ return True
+ if normalized in ("false", "0", "no", "off", "disabled"):
+ return False
+ raise ValueError("Expected a boolean token")
+
+
def get_typed_setting_value(
key: str,
value: Any,
@@ -517,66 +536,48 @@ def get_typed_setting_value(
key: The setting key.
value: The setting value from the database.
ui_element: The setting UI element ID.
- default: Default value to return if the value of the setting is
- invalid.
+ default: Default value to return when the setting is unset (None).
check_env: If true, it will check the environment variable for
this setting before reading from the DB.
Returns:
The value of the setting.
+ Raises:
+ SettingsValueError: The selected value cannot be converted, or its
+ declared setting type is unsupported. Invalid overrides never
+ fall through to a lower-priority value.
+
"""
- setting_type = UI_ELEMENT_TO_SETTING_TYPE.get(ui_element, None)
- if setting_type is None:
- logger.warning(
- "Got unknown type {} for setting {}, returning default value.",
- ui_element,
- key,
+ env_value = check_env_setting(key) if check_env else None
+ source = "environment" if env_value is not None else "value"
+ if (
+ not isinstance(ui_element, str)
+ or ui_element not in UI_ELEMENT_TO_SETTING_TYPE
+ ):
+ raise SettingsValueError(
+ key, source=source, reason="unsupported setting type"
)
- return default
-
- # NOTE: never interpolate a setting VALUE into the log lines below.
- # Any settings value is a plausible secret carrier — an API key, a
- # bearer token, or a JSON container with one nested inside — and this
- # converter is reached from every read path, including the
- # post-commit settings-changed emit that runs after
- # ``PUT /settings/api/{key}``. A malformed row (e.g. a dict stored in
- # a ``number`` row) would otherwise write the whole container, secret
- # included, to the log at WARNING level. The key, the declared
- # ui_element and the value's type name identify the bad row without
- # disclosing it. See #6201.
-
- # Check environment variable first (highest priority).
- if check_env:
- env_value = check_env_setting(key)
- if env_value is not None:
- try:
- return setting_type(env_value)
- except ValueError:
- logger.warning(
- "Setting {} has an invalid environment value of type {} "
- "for ui_element {} (value omitted). Falling back to DB.",
- key,
- type(env_value).__name__,
- ui_element,
- )
-
- # If value is None (not in database), return default.
+ setting_type = UI_ELEMENT_TO_SETTING_TYPE[ui_element]
+ if env_value is not None:
+ value = env_value
if value is None:
return default
-
- # Read from the database.
try:
+ if ui_element == "json" and env_value is not None:
+ return json.loads(value, parse_constant=_reject_json_constant)
+ if ui_element == "checkbox" and env_value is not None:
+ # Environment variables are configuration, not submitted HTML
+ # checkboxes. An unrecognized token must not enable a feature.
+ return _parse_environment_boolean(value)
return setting_type(value)
- except (ValueError, TypeError):
- logger.warning(
- "Setting {} has an invalid value of type {} for ui_element {} "
- "(value omitted). Returning default.",
- key,
- type(value).__name__,
- ui_element,
- )
- return default
+ except (ValueError, TypeError, OverflowError, RecursionError):
+ pass
+ # Raise outside the handler: even a suppressed __context__ can contain
+ # credentials from float()/json.loads() errors. See #6201.
+ raise SettingsValueError(
+ key, source=source, reason=f"expected a valid {ui_element} value"
+ )
def check_env_setting(key: str) -> str | None:
@@ -778,6 +779,8 @@ class SettingsManager(ISettingsManager):
logger.info(
"Settings are locked. Disabling all settings changes."
)
+ except SettingsValueError:
+ raise
except Exception:
logger.bind(policy_audit=True).warning(
"Failed to check settings lock status; denying changes"
@@ -973,7 +976,13 @@ class SettingsManager(ISettingsManager):
this setting before reading from the DB.
Returns:
- Setting value or default if not found
+ Setting value or default if not found. An environment override
+ for a key with no row and no declared type is returned as the
+ raw string.
+
+ Raises:
+ SettingsValueError: The selected value cannot be converted to its
+ declared type, or that type is unsupported.
"""
if self._closed:
logger.error(
@@ -988,7 +997,7 @@ class SettingsManager(ISettingsManager):
# First check if this is an env-only setting
if env_registry.is_env_only(key):
- return env_registry.get(key, default)
+ return env_registry.get_strict(key, default, check_env=check_env)
# If using database first approach and session available, check database
try:
@@ -1047,6 +1056,12 @@ class SettingsManager(ISettingsManager):
default=default,
check_env=True,
)
+ # No type is declared, so there is nothing to validate the
+ # override against: return it unconverted, as before strict
+ # reads. Untyped keys such as app.api_rate_limit and
+ # app.enable_api are read on every /api/v1 request, and their
+ # consumers parse the string themselves. Typed keys still
+ # raise above on a value that cannot be converted.
logger.warning(
"Setting '{}' has env var override but is not in "
"defaults — returning raw string without type "
@@ -1272,12 +1287,18 @@ class SettingsManager(ISettingsManager):
Args:
bypass_cache: If True, bypass the cache and read directly from database
- include_environment_overrides: If True, overlay current LDR_* values.
+ include_environment_overrides: If True, validate effective values
+ and overlay current LDR_* values. False exports stored values
+ and metadata unchanged, including invalid values for repair.
strict: If True, propagate database and enum query failures.
-
Returns:
Dictionary of all settings
+
+ Raises:
+ SettingsValueError: With ``include_environment_overrides``, any
+ effective value cannot be converted to its declared type, or
+ that type is unsupported.
"""
if self._closed:
logger.error(
@@ -1295,21 +1316,6 @@ class SettingsManager(ISettingsManager):
for key, default_setting in self.default_settings.items():
result[key] = dict(default_setting)
- # Check env var override for defaults not yet in DB
- if include_environment_overrides:
- env_value = check_env_setting(key)
- if env_value is not None:
- ui_element = default_setting.get("ui_element", "text")
- typed_value = get_typed_setting_value(
- key,
- None,
- ui_element,
- default=env_value,
- check_env=True,
- )
- result[key]["value"] = typed_value
- result[key]["editable"] = False
-
# Override with database settings
try:
db_settings = self.__query_settings()
@@ -1371,30 +1377,25 @@ class SettingsManager(ISettingsManager):
"step": setting.step,
"visible": setting.visible,
"editable": False
- if self.settings_locked
+ if (include_environment_overrides and self.settings_locked)
or is_operator_only_setting(str(setting.key))
else setting.editable,
}
- # Override from the environment variables if needed.
- if include_environment_overrides:
- env_value = check_env_setting(str(setting.key))
- if env_value is not None:
- ui_element = result[str(setting.key)].get(
- "ui_element", setting.ui_element
- )
- typed_value = get_typed_setting_value(
- str(setting.key),
- None,
- ui_element,
- default=env_value,
- check_env=True,
- )
- result[str(setting.key)]["value"] = typed_value
- # Mark it as non-editable, because changes to the DB
- # value have no effect as long as the environment
- # variable is set.
- result[str(setting.key)]["editable"] = False
+ # Validate only after choosing the effective row. A valid database row
+ # may replace an obsolete default, and a valid environment override may
+ # replace an invalid stored value. Neither may hide an invalid selected
+ # value by silently substituting another setting.
+ if include_environment_overrides:
+ for key, metadata in result.items():
+ typed_value = get_typed_setting_value(
+ key,
+ metadata.get("value"),
+ metadata.get("ui_element", "text"),
+ )
+ if check_env_setting(key) is not None:
+ metadata["value"] = typed_value
+ metadata["editable"] = False
# Re-inject search strategy options from code after DB merge,
# since the DB stores options=null for this setting.
@@ -1771,7 +1772,9 @@ class SettingsManager(ISettingsManager):
overwrite: If true, it will overwrite the value of settings that
are already in the database. If false, each key keeps the
value of its own stored row; the values of its child keys
- are never folded into it.
+ are never folded into it. A stored value that is invalid
+ for its type is kept as stored, with a warning that names
+ the key but not the value, and the import continues.
delete_extra: If true, it will delete any settings that are in
the database but don't have a corresponding entry in
`settings_data`.
@@ -1844,8 +1847,15 @@ class SettingsManager(ISettingsManager):
setting_values["value"] = existing_value[0]
value_replaced_from_db = True
if not overwrite:
- existing_value = self.get_setting(key, check_env=False)
- if isinstance(existing_value, dict):
+ try:
+ existing_value = self.get_setting(key, check_env=False)
+ reread_own_row = isinstance(existing_value, dict)
+ except SettingsValueError:
+ # get_setting() also converts child rows, so the
+ # invalid value may belong to a child. Re-read the
+ # row stored under exactly this key.
+ reread_own_row = True
+ if reread_own_row:
# get_setting() folds child rows, including ASCII
# case variants its LIKE lookup matches, into a
# mapping. Writing that mapping back would replace
@@ -1856,13 +1866,28 @@ class SettingsManager(ISettingsManager):
.filter(Setting.key == key)
.first()
)
- existing_value = (
- None
- if stored_row is None
- else self.__get_typed_setting_value(
- stored_row, None, check_env=False
- )
- )
+ existing_value = None
+ if stored_row is not None:
+ try:
+ existing_value = self.__get_typed_setting_value(
+ stored_row, None, check_env=False
+ )
+ except SettingsValueError as error:
+ # One invalid stored row must not abort the
+ # reconciliation for every other key, and
+ # replacing it with the default would hide
+ # the error. Keep the stored value; reads
+ # keep reporting it until it is corrected.
+ # The reason is a fixed string that never
+ # contains the value.
+ reason = error.reason
+ logger.warning(
+ "Keeping the stored value of setting "
+ "{!r} during defaults reconciliation: {}",
+ key,
+ reason,
+ )
+ existing_value = stored_row.value
if existing_value is not None:
setting_values["value"] = existing_value
value_replaced_from_db = True
@@ -1988,8 +2013,8 @@ class SettingsManager(ISettingsManager):
return
# Read the changed values only after the recipient check: each
- # read types the stored row, so an unknown ui_element logs a
- # default-substitution warning for an emit that never happens.
+ # read types the stored row, so an invalid value or unknown
+ # ui_element raises for an emit that never happens.
settings_data = {}
if changed_keys:
for key in changed_keys:
diff --git a/src/local_deep_research/web/dependencies/rate_limit.py b/src/local_deep_research/web/dependencies/rate_limit.py
index 175745fcdb..7e673d20cc 100644
--- a/src/local_deep_research/web/dependencies/rate_limit.py
+++ b/src/local_deep_research/web/dependencies/rate_limit.py
@@ -2052,24 +2052,26 @@ def set_request_api_rate_limit(value: object) -> None:
Only 0 (the kill switch) and positive ints are cached as given. A
string of ASCII digits (surrounding whitespace allowed) is cached as
the int it spells: app.api_rate_limit has no defaults-JSON entry, so
- an env override (LDR_APP_API_RATE_LIMIT=120) or a text-typed settings
- row reaches here as the raw string "120", which main's Flask code
- honoured ("0" therefore disables the limit just as 0 does). ASCII
- only: str.isdecimal() also passes other scripts' digits, which int()
- converts, but a number typed into an env var or a text column is
- [0-9], so anything else is refused rather than quietly honoured. A
- string longer than _NUMERIC_VALUE_MAX_CHARS is not scanned or
- converted at all: no rate limit is that long, and this runs on every
- request. The default is cached in place of anything else, with a
- warning naming the value, because nothing validates the setting
- upstream and a negative, fractional, boolean or non-numeric value can
- arrive here. Cached as-is, such a value would count as "custom": the
- static limit steps aside, and slowapi, unable to parse the limit
- string built from it, logs an error and skips the dynamic limit -
- leaving the user with no limit at all. A stored invalid value comes
- back on every request, so the warning is emitted once per distinct
- value per process (bounded, see _WARNED_INVALID_VALUES_MAX) and
- repeats are logged at debug.
+ SettingsManager.get_setting returns an env override
+ (LDR_APP_API_RATE_LIMIT=120) unconverted, and that override or a
+ text-typed settings row reaches here as the raw string "120", which
+ main's Flask code honoured ("0" therefore disables the limit just as
+ 0 does). ASCII only: str.isdecimal() also passes other scripts'
+ digits, which int() converts, but a number typed into an env var or
+ a text column is [0-9], so anything else is refused rather than
+ quietly honoured. A string longer than _NUMERIC_VALUE_MAX_CHARS is
+ not scanned or converted at all: no rate limit is that long, and
+ this runs on every request. The default is cached in place of
+ anything else, with a warning naming the value, because the settings
+ layer checks a value only against its declared type, if any, so a
+ negative, fractional, boolean or non-numeric value can arrive here.
+ Cached as-is, such a value would count as "custom": the static limit
+ steps aside, and slowapi, unable to parse the limit string built from
+ it, logs an error and skips the dynamic limit - leaving the user with
+ no limit at all. A stored invalid value comes back on every request,
+ so the warning is emitted once per distinct value per process
+ (bounded, see _WARNED_INVALID_VALUES_MAX) and repeats are logged at
+ debug.
"""
if isinstance(value, str) and len(value) <= _NUMERIC_VALUE_MAX_CHARS:
stripped = value.strip()
diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.py
index 493cddfd88..c38316d9cc 100644
--- a/src/local_deep_research/web/fastapi_app.py
+++ b/src/local_deep_research/web/fastapi_app.py
@@ -19,7 +19,12 @@ from importlib import resources as importlib_resources
from pathlib import Path
from fastapi import FastAPI, Request
-from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse
+from fastapi.responses import (
+ HTMLResponse,
+ JSONResponse,
+ PlainTextResponse,
+ RedirectResponse,
+)
from loguru import logger
from starlette.middleware.sessions import SessionMiddleware
from starlette.requests import ClientDisconnect
@@ -67,7 +72,13 @@ _BRANDED_ERROR_COPY: dict[int, tuple[str, str]] = {
}
-def _render_branded_error_page(request: Request, status_code: int):
+def _render_branded_error_page(
+ request: Request,
+ status_code: int,
+ *,
+ title: str | None = None,
+ message: str | None = None,
+):
"""Render ``templates/pages/error.html`` for a browser-facing error.
Ports the defensive design of the Flask handler this replaces (PR
@@ -82,12 +93,17 @@ def _render_branded_error_page(request: Request, status_code: int):
swallowed and logged at debug; callers fall back to the previous
plain-text/JSON response.
+ ``title`` and ``message`` replace the copy for ``status_code``. The
+ template escapes both.
+
Returns the rendered ``Response`` on success, or ``None`` on any
failure.
"""
- title, message = _BRANDED_ERROR_COPY.get(
+ default_title, default_message = _BRANDED_ERROR_COPY.get(
status_code, ("Something went wrong", "Please try again.")
)
+ title = default_title if title is None else title
+ message = default_message if message is None else message
from ..security.egress.policy import DEFAULT_EGRESS_SCOPE
# If a session is present -- real or a caller-supplied placeholder
@@ -1719,6 +1735,41 @@ def _register_exception_handlers(app: FastAPI) -> None:
# for partial test builds without the security package.
pass
+ # Strict settings reads raise SettingsValueError for an invalid
+ # configured value. One that reaches the app gets its diagnostic, which
+ # names the key, its source and a fixed reason but never the value, so
+ # the operator can find the setting. Without this handler the catch-all
+ # above would answer with a generic "Server error".
+ from ..settings.exceptions import SettingsValueError
+
+ @app.exception_handler(SettingsValueError)
+ async def handle_settings_value_error(
+ request: Request, exc: SettingsValueError
+ ):
+ from .routers.notes import _log_value_preview
+
+ diagnostic = exc.diagnostic
+ logger.error(
+ "Invalid setting on {} {}: {}",
+ request.method,
+ _log_value_preview(request.url.path),
+ diagnostic,
+ )
+ if _is_api_request(request):
+ return JSONResponse({"error": diagnostic}, status_code=500)
+ page = _render_branded_error_page(
+ request,
+ 500,
+ title="Invalid setting",
+ message=(
+ f"{diagnostic}. Correct the setting in the settings page "
+ "or the deployment environment, or remove it, then reload."
+ ),
+ )
+ if page is not None:
+ return page
+ return PlainTextResponse(diagnostic, status_code=500)
+
# ---------------------------------------------------------------------------
# Database middleware (before each request)
@@ -2797,6 +2848,7 @@ def _mount_all(app: FastAPI) -> None:
effective_scope_for_display,
unprotected_egress_allowed,
)
+ from ..settings.exceptions import SettingsValueError
from ..settings.manager import check_env_setting
settings = {}
@@ -2870,6 +2922,13 @@ def _mount_all(app: FastAPI) -> None:
"embeddings.require_local", False
),
}
+ except SettingsValueError:
+ # An invalid configured setting is not the password case below.
+ # Clearing the session would only send the user back here after
+ # the next login, where the same read fails again: a login
+ # loop. The app's SettingsValueError handler shows the
+ # diagnostic instead, and the session is kept.
+ raise
except Exception:
# Password not available (e.g. server restarted) — force re-login.
#
diff --git a/src/local_deep_research/web/routers/api_v1.py b/src/local_deep_research/web/routers/api_v1.py
index 477cd4048b..9dc13147d7 100644
--- a/src/local_deep_research/web/routers/api_v1.py
+++ b/src/local_deep_research/web/routers/api_v1.py
@@ -23,6 +23,7 @@ from loguru import logger
from ...api.research_functions import analyze_documents
from ...database.session_context import get_user_db_session
from ...security.log_sanitizer import sanitize_error_for_client
+from ...settings.exceptions import SettingsValueError
from ...utilities.db_utils import get_settings_manager
from ..dependencies.auth import get_session_username, require_auth
from ..dependencies.json_body import is_json_request
@@ -977,6 +978,11 @@ def _load_user_context_into_params(
opt-in to proceed with defaults (empty snapshot, no egress policy)
instead; it is logged loudly so it is never silent.
+ An invalid configured setting (``SettingsValueError``) also returns a
+ 503, with ``reason`` ``invalid_setting`` and an ``error`` naming the
+ key, its source and the reason but not the value. The opt-in does not
+ apply to it.
+
Runs sync SQLAlchemy — call from a threadpool, not the event loop.
"""
if not username:
@@ -1000,6 +1006,37 @@ def _load_user_context_into_params(
f"with {len(snapshot)} settings"
)
return None
+ except SettingsValueError as error:
+ # Handled before the generic branch so the unavailable-database
+ # opt-in below cannot waive invalid configuration. The diagnostic
+ # names the key, its source and the reason, never the value or the
+ # parser's own exception, so it is the one part of this exception
+ # that may reach the client. It is read into a string here, and the
+ # body is built from that string: the response-leakage guard
+ # (tests/web/routers/test_error_response_leakage.py) rejects any use
+ # of a bound exception inside a response body.
+ diagnostic = error.diagnostic
+ logger.bind(policy_audit=True).warning(
+ "Research refused because of an invalid setting: {}",
+ diagnostic,
+ user=username,
+ )
+ return JSONResponse(
+ {
+ "error": (
+ "The research was REFUSED because a configured "
+ f"setting is invalid. {diagnostic}"
+ ),
+ "how_to_fix": (
+ "Correct or remove the named setting in the "
+ "deployment environment or the saved settings, then "
+ "retry. allow_default_settings does not bypass an "
+ "invalid setting."
+ ),
+ "reason": "invalid_setting",
+ },
+ status_code=503,
+ )
except Exception:
# logger.exception captures the traceback so the root cause
# (e.g. SQLCipher decrypt failure, settings table corruption,
diff --git a/src/local_deep_research/web/routers/library.py b/src/local_deep_research/web/routers/library.py
index 9fab98977a..0b6adf1951 100644
--- a/src/local_deep_research/web/routers/library.py
+++ b/src/local_deep_research/web/routers/library.py
@@ -61,6 +61,7 @@ from ...research_library.utils import (
from ...utilities.db_utils import get_settings_manager
from ...config.paths import get_library_directory
from ...security.log_sanitizer import redact_and_bound_for_log
+from ...settings.exceptions import SettingsValueError
from ...web.exceptions import AuthenticationRequiredError
from ..dependencies.json_body import read_json_dict
from .notes import _log_value_preview
@@ -214,6 +215,10 @@ def library_page(
shared_library = settings.get_setting(
"research_library.shared_library", False
)
+ except SettingsValueError:
+ # An invalid configured value must not render the page as if the
+ # defaults were configured. The app's handler shows the diagnostic.
+ raise
except Exception:
pdf_storage_mode = "database"
shared_library = False
diff --git a/src/local_deep_research/web/routers/news_pages.py b/src/local_deep_research/web/routers/news_pages.py
index 51e66071b0..ae2ba7d089 100644
--- a/src/local_deep_research/web/routers/news_pages.py
+++ b/src/local_deep_research/web/routers/news_pages.py
@@ -9,6 +9,7 @@ from loguru import logger
from .notes import _log_value_preview
from ...constants import DEFAULT_SEARCH_TOOL, get_available_strategies
+from ...settings.exceptions import SettingsValueError
from ..dependencies.auth import require_auth
from ..template_config import templates
from typing import Annotated
@@ -143,6 +144,10 @@ def edit_subscription_page(
with get_user_db_session(username) as db_session:
_load_user_settings(default_settings, db_session, username)
+ except SettingsValueError:
+ # Not a subscription loading error: the app's handler names the
+ # invalid setting.
+ raise
except Exception:
logger.exception(
f"Error loading subscription {_log_value_preview(subscription_id)}"
@@ -241,5 +246,9 @@ def _load_user_settings(default_settings, db_session=None, username=None):
),
}
)
+ except SettingsValueError:
+ # An invalid configured value must not prefill the form with
+ # defaults as if they were the saved settings.
+ raise
except Exception:
logger.warning("Could not load user settings")
diff --git a/src/local_deep_research/web/routers/rag.py b/src/local_deep_research/web/routers/rag.py
index c8d2049a51..af80cdc06a 100644
--- a/src/local_deep_research/web/routers/rag.py
+++ b/src/local_deep_research/web/routers/rag.py
@@ -68,6 +68,7 @@ from ...security.log_sanitizer import (
from ...utilities.db_utils import get_settings_manager
from ...utilities.resource_utils import safe_close
from ...research_library.services.library_rag_service import LibraryRAGService
+from ...settings.exceptions import SettingsValueError
from ...settings.manager import SettingsManager, check_env_setting
from ...research_library.utils import (
apply_user_subdir,
@@ -1330,6 +1331,8 @@ def index_all(
_max_workers = int(
settings.get_setting("rag.indexing_max_parallel_docs", 4)
)
+ except SettingsValueError:
+ raise
except Exception:
_max_workers = 4
_max_workers = max(1, min(_max_workers, 16))
@@ -3519,6 +3522,8 @@ def index_collection(
_max_workers = int(
_settings.get_setting("rag.indexing_max_parallel_docs", 4)
)
+ except SettingsValueError:
+ raise
except Exception:
_max_workers = 4
# See index_all: the force-reindex reset needs the user's settings
@@ -3913,6 +3918,8 @@ def trigger_auto_index(
_auto_max_workers = int(
settings.get_setting("rag.indexing_max_parallel_docs", 4)
)
+ except SettingsValueError:
+ raise
except Exception:
_auto_max_workers = 4
_auto_max_workers = max(1, min(_auto_max_workers, 16))
@@ -4806,6 +4813,23 @@ def _start_background_index_sync(
else None
)
+ # Resolve per-job parallel fan-out before committing the task
+ # (request-scoped session) and forward into the worker, which
+ # runs on a background thread where the no-arg
+ # ``get_settings_manager()`` is unsafe (#3453).
+ try:
+ _bg_settings = get_settings_manager(db_session, username)
+ _bg_max_workers = int(
+ _bg_settings.get_setting(
+ "rag.indexing_max_parallel_docs", 4
+ )
+ )
+ except SettingsValueError:
+ raise
+ except Exception:
+ _bg_max_workers = 4
+ _bg_max_workers = max(1, min(_bg_max_workers, 16))
+
# Create new task
task_id = str(uuid.uuid4())
task = TaskMetadata(
@@ -4827,21 +4851,6 @@ def _start_background_index_sync(
with _active_sse_indexers_lock:
_active_background_indexers[lock_key] = task_id
- # Resolve per-job parallel fan-out here (request-scoped
- # session) and forward into the worker — the worker itself
- # runs on a background thread where the no-arg
- # ``get_settings_manager()`` is unsafe (#3453).
- try:
- _bg_settings = get_settings_manager(db_session, username)
- _bg_max_workers = int(
- _bg_settings.get_setting(
- "rag.indexing_max_parallel_docs", 4
- )
- )
- except Exception:
- _bg_max_workers = 4
- _bg_max_workers = max(1, min(_bg_max_workers, 16))
-
# Start background thread. Copy the request's contextvars so
# any service code inside the worker that calls
# `get_current_username()` sees the actual user instead of None.
diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.py
index 61d5a21dcf..9779572ff9 100644
--- a/src/local_deep_research/web/routers/research.py
+++ b/src/local_deep_research/web/routers/research.py
@@ -30,6 +30,7 @@ from datetime import datetime, UTC
from pathlib import Path
from loguru import logger
+from ...settings.exceptions import SettingsValueError
from ...settings.logger import log_settings
from sqlalchemy import case, func
from sqlalchemy.orm import Session
@@ -247,6 +248,20 @@ def _non_string_request_field(data):
return None
+def _settings_value_error_response(error):
+ """Refuse a research start because a configured setting is invalid.
+
+ This is a server-side configuration error, not a request error, so it
+ is a 500 rather than one of the 400 messages for request fields. The
+ message names the key, its source and the reason, never the value.
+ """
+ logger.error("Research start refused: {}", error.diagnostic)
+ return JSONResponse(
+ {"status": "error", "message": error.diagnostic},
+ status_code=500,
+ )
+
+
def _extract_research_params(data, settings_manager):
"""Extract and resolve research parameters from request data and settings.
@@ -260,7 +275,9 @@ def _extract_research_params(data, settings_manager):
string ``custom_endpoint`` (from the request or the saved setting) fails
the SSRF guard, or when ``iterations`` / ``questions_per_iteration`` is
not an integer in range. ``_start_research_sync`` maps each to a fixed
- 400 message.
+ 400 message. A settings read raises ``SettingsValueError`` (also a
+ ``ValueError``) for an invalid configured value; that one is returned
+ as a 500 naming the setting instead.
"""
bad_field = _non_string_request_field(data)
if bad_field is not None:
@@ -502,7 +519,9 @@ def _precheck_engine_policy(settings_manager, params, search_engine, username):
Returns a ``JSONResponse`` when the request should be rejected, or
``None`` to continue. Falls through (returns None) when there's no
real dict snapshot to validate or the policy module errors — the
- factory PEP still enforces at engine-instantiation time.
+ factory PEP still enforces at engine-instantiation time. An invalid
+ configured setting is not such an error: it rejects the request with
+ the setting diagnostic instead of skipping the check.
"""
try:
from ...security.egress.policy import (
@@ -583,6 +602,10 @@ def _precheck_engine_policy(settings_manager, params, search_engine, username):
},
status_code=400,
)
+ except SettingsValueError:
+ # A ValueError subclass, but not a policy decision: the outer
+ # handler reports which setting is invalid.
+ raise
except ValueError as exc:
# An invalid policy config is unrecoverable. Previously this
# raised, fell through to the outer ``except Exception``
@@ -732,6 +755,11 @@ def _precheck_engine_policy(settings_manager, params, search_engine, username):
status_code=400,
)
return None
+ except SettingsValueError as error:
+ # The snapshot read above validates every effective setting, so one
+ # invalid row anywhere lands here. Skipping the check would let the
+ # run start without it; refuse and name the setting instead.
+ return _settings_value_error_response(error)
except Exception:
# Policy module unavailable / internal error → log and fall
# through; the factory PEP will catch any actual violation.
@@ -1070,6 +1098,11 @@ def _start_research_sync(
settings_manager = SettingsManager(db_session=db_session)
try:
params = _extract_research_params(data, settings_manager)
+ except SettingsValueError as error:
+ # Ahead of the ValueError mapping below: its substring matching
+ # would report an invalid saved or environment value as a bad
+ # request field (e.g. "iterations must be an integer ...").
+ return _settings_value_error_response(error)
except ValueError as exc:
# SSRF guard or parameter validation in _extract_research_params
# rejected the input — return main's clean 400 contract
@@ -1291,6 +1324,9 @@ def _start_research_sync(
# can retain a pooled connection and later wait for the gate
# while a queue tick holds the gate and waits for a connection.
db_session.rollback()
+ except SettingsValueError as error:
+ # An invalid concurrency limit must not become "do not queue".
+ return _settings_value_error_response(error)
except Exception:
logger.exception("Failed to check active researches")
# Default to not queueing if we can't check
diff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.py
index 9bd76fbf9d..e528296849 100644
--- a/src/local_deep_research/web/routers/settings.py
+++ b/src/local_deep_research/web/routers/settings.py
@@ -102,7 +102,9 @@ from ...utilities.db_utils import get_settings_manager
from ...utilities.type_utils import unwrap_setting
from ...utilities.url_utils import normalize_url
+from ...settings.exceptions import SettingsValueError
from ...settings.manager import (
+ UI_ELEMENT_TO_SETTING_TYPE,
_infer_ui_element,
check_env_setting,
get_typed_setting_value,
@@ -576,19 +578,29 @@ def validate_setting(
Returns:
Tuple of (is_valid, error_message)
"""
- # Keep the submitted value so a failed conversion cannot be confused with
- # an intentionally-unset optional numeric. The converter uses ``None`` for
- # both outcomes when its default is None.
raw_value = value
-
- # Convert value to appropriate type first using SettingsManager's logic
- value = get_typed_setting_value(
- key=str(setting.key),
- value=value,
- ui_element=str(setting.ui_element),
- default=None,
- check_env=False,
- )
+ numeric_ui = setting.ui_element in ("number", "slider", "range")
+ # Blank form inputs explicitly clear optional numeric settings; they are
+ # normalized to None on write, not used as a fallback for bad numbers.
+ if numeric_ui and (
+ raw_value is None
+ or (isinstance(raw_value, str) and not raw_value.strip())
+ ):
+ return True, None
+ try:
+ value = get_typed_setting_value(
+ key=str(setting.key),
+ value=value,
+ ui_element=str(setting.ui_element),
+ default=None,
+ check_env=False,
+ )
+ except SettingsValueError as error:
+ if numeric_ui:
+ return False, "Value must be a number"
+ if setting.ui_element == "checkbox":
+ return False, "Value must be a boolean"
+ return False, error.reason
# Validate based on UI element type
if setting.ui_element == "checkbox":
@@ -597,14 +609,6 @@ def validate_setting(
return False, "Value must be a boolean"
elif setting.ui_element in ("number", "slider", "range"):
- # None and blank HTML numeric inputs represent an intentionally-unset
- # optional value. A nonblank value that failed conversion also becomes
- # None, but must be rejected instead of silently erasing the setting.
- if raw_value is None or (
- isinstance(raw_value, str) and not raw_value.strip()
- ):
- return True, None
-
# After conversion, should be numeric
if (
isinstance(raw_value, bool)
@@ -639,6 +643,28 @@ def validate_setting(
return True, None
+def _strict_read_rejection(key: str, value: Any, ui_element: Any) -> str | None:
+ """Return why a strict settings read would reject this row, or None.
+
+ A write must not store a row that every effective read of the account
+ then refuses with ``SettingsValueError``. This applies the read's own
+ rules: the type must be supported and the value must convert to it.
+ Pass the value and the ui_element exactly as they will be stored. The
+ reason never contains the value.
+ """
+ try:
+ get_typed_setting_value(
+ key=key,
+ value=value,
+ ui_element=ui_element,
+ default=None,
+ check_env=False,
+ )
+ except SettingsValueError as error:
+ return error.reason
+ return None
+
+
def coerce_setting_for_write(key: str, value: Any, ui_element: str) -> Any:
"""Coerce an incoming value to the correct type before writing to the DB.
@@ -667,18 +693,18 @@ def coerce_setting_for_write(key: str, value: Any, ui_element: str) -> Any:
# erase the evidence validate_setting needs to reject type confusion.
return value
- coerced = get_typed_setting_value(
- key=key,
- value=value,
- ui_element=ui_element,
- default=None,
- check_env=False,
- )
- if numeric_ui and value is not None and coerced is None:
- # Preserve a nonblank conversion failure for validate_setting. Returning
- # None here would make every caller treat malformed input as an
- # intentionally-unset optional numeric (several skip validation for
- # None entirely).
+ try:
+ coerced = get_typed_setting_value(
+ key=key,
+ value=value,
+ ui_element=ui_element,
+ default=None,
+ check_env=False,
+ )
+ except SettingsValueError:
+ # Preserve the submitted input so validate_setting can return the
+ # route's normal validation error. Never replace it with None/default,
+ # which would turn a malformed value into an accepted optional value.
return value
# Canonicalise the egress scope on the write path: the select options
# are exact lowercase strings, so a value arriving with surrounding
@@ -2151,6 +2177,22 @@ def _save_all_settings_sync(form_data: dict, username: str):
elif isinstance(value, (dict, list)):
new_setting["ui_element"] = "textarea"
+ # A JSON body can carry NaN, Infinity or an integer too
+ # large for a float, which the number type rejects on
+ # read.
+ rejection = _strict_read_rejection(
+ key, value, new_setting["ui_element"]
+ )
+ if rejection is not None:
+ validation_errors.append(
+ {
+ "key": key,
+ "name": new_setting["name"],
+ "error": rejection,
+ }
+ )
+ continue
+
# Create the setting without committing yet — see above
db_setting = create_or_update_setting(
new_setting, commit=False, db_session=db_session
@@ -2184,23 +2226,9 @@ def _save_all_settings_sync(form_data: dict, username: str):
status_code=400,
)
- # All settings validated: commit the batch atomically.
- db_session.commit()
- changed_settings = updated_settings + created_settings
- if changed_settings:
- settings_manager.emit_settings_changed_after_commit(
- changed_settings
- )
-
- invalidate_settings_caches(username)
- reschedule_document_jobs_if_needed(
- username, updated_settings + created_settings
- )
- reschedule_zotero_jobs_if_needed(
- username, updated_settings + created_settings
- )
-
- # Get all settings to return to the client for proper state update
+ # Prepare the effective response before committing. An invalid
+ # environment override must refuse the batch before any edit or
+ # post-commit effect becomes visible.
all_settings = {}
for setting in db_session.query(Setting).all():
# Convert enum to string if present
@@ -2244,6 +2272,25 @@ def _save_all_settings_sync(form_data: dict, username: str):
)
_echo_meta["editable"] = False
+ # The echo above covers only keys with a saved row. An override on
+ # a declared (default) key without a row is part of the same
+ # effective configuration, so it must refuse the batch too rather
+ # than surface only on the next typed read.
+ _defaults = settings_manager.default_settings
+ for _default_key, _default_meta in _defaults.items():
+ if (
+ _default_key in all_settings
+ or check_env_setting(_default_key) is None
+ ):
+ continue
+ get_typed_setting_value(
+ key=_default_key,
+ value=_default_meta.get("value"),
+ ui_element=str(_default_meta.get("ui_element", "text")),
+ default=_default_meta.get("value"),
+ check_env=True,
+ )
+
# Operator-gate the "unprotected" escape hatch out of the
# egress-scope select's options unless explicitly enabled, and
# normalise the displayed value (#5148 / 87537d9ec). Without
@@ -2319,21 +2366,39 @@ def _save_all_settings_sync(form_data: dict, username: str):
),
}
- warning_affecting_keys = WARNING_AFFECTING_KEYS
+ # The writes and response both validated: commit atomically.
+ db_session.commit()
+ changed_settings = updated_settings + created_settings
+ # The batch is committed from here on. A settings error raised by
+ # a post-commit effect must not be reported as a refused save.
+ try:
+ if changed_settings:
+ settings_manager.emit_settings_changed_after_commit(
+ changed_settings
+ )
- # Check if any warning-affecting settings were changed
- if any(
- key in warning_affecting_keys
- for key in updated_settings + created_settings
- ):
- warnings = calculate_warnings(username=username)
- response_data["warnings"] = warnings
- logger.info(
- f"Bulk settings update affected warning keys, calculated {len(warnings)} warnings"
- )
+ invalidate_settings_caches(username)
+ reschedule_document_jobs_if_needed(username, changed_settings)
+ reschedule_zotero_jobs_if_needed(username, changed_settings)
+
+ # Check if any warning-affecting settings were changed
+ if any(
+ key in WARNING_AFFECTING_KEYS for key in changed_settings
+ ):
+ warnings = calculate_warnings(username=username)
+ response_data["warnings"] = warnings
+ logger.info(
+ f"Bulk settings update affected warning keys, calculated {len(warnings)} warnings"
+ )
+ except SettingsValueError as error:
+ _log_post_save_settings_error(error)
return response_data
+ except SettingsValueError as error:
+ return _settings_value_error_response(
+ "settings for bulk save", error, bulk_save=True
+ )
except Exception:
logger.exception("Error saving settings")
return JSONResponse(
@@ -2817,6 +2882,37 @@ async def save_settings(
return RedirectResponse(url="/settings/", status_code=302)
+def _log_post_save_settings_error(error: SettingsValueError) -> None:
+ """Log a settings error raised after a bulk save already committed.
+
+ ``error.diagnostic`` holds only the key, its source and a fixed reason,
+ never the value.
+ """
+ logger.error(
+ "Settings saved, but a post-save step could not read settings: {}",
+ error.diagnostic,
+ )
+
+
+def _settings_value_error_response(
+ resource: str, error: SettingsValueError, *, bulk_save: bool = False
+) -> JSONResponse:
+ """Return the diagnostic for an invalid configured setting.
+
+ The upgrade guide tells operators to locate the setting from this
+ message, so it replaces the generic error. ``error.diagnostic`` holds
+ only the key, its source and a fixed reason, never the value.
+ Bulk saves retain their existing status/message response fields.
+ """
+ logger.error("Could not load {}: {}", resource, error.diagnostic)
+ body = (
+ {"status": "error", "message": error.diagnostic}
+ if bulk_save
+ else {"error": error.diagnostic}
+ )
+ return JSONResponse(body, status_code=500)
+
+
# API Routes
@router.get("/api")
def api_get_all_settings(
@@ -2883,6 +2979,8 @@ def api_get_all_settings(
settings = DataSanitizer.redact_settings_snapshot(settings)
return {"status": "success", "settings": settings}
+ except SettingsValueError as error:
+ return _settings_value_error_response("settings", error)
except Exception:
logger.exception("Error getting settings")
return JSONResponse(
@@ -2977,19 +3075,9 @@ def api_get_ui_elements(
):
"""Get all UI element types"""
try:
- # Define supported UI element types
- ui_elements = [
- "text",
- "select",
- "checkbox",
- "slider",
- "number",
- "textarea",
- "color",
- "date",
- "file",
- "password",
- ]
+ # The types a settings read can convert. A new setting with any
+ # other ui_element is rejected on write.
+ ui_elements = list(UI_ELEMENT_TO_SETTING_TYPE)
return {"ui_elements": ui_elements}
except Exception:
@@ -4100,13 +4188,11 @@ def api_get_available_search_engines(
# design (see ``_apply_guarded_url_overlay``), so an engine the
# runtime will refuse must read as disabled under the shipped
# ``adaptive`` default too, not only under ``public_only``.
- try:
- policy_snapshot = settings_manager.get_settings_snapshot()
- except Exception: # pragma: no cover - defensive
- logger.exception(
- "settings snapshot unavailable for egress filter"
- )
- policy_snapshot = {}
+ # A snapshot failure must not be replaced with an empty policy:
+ # the filter and the overlay would then deny nothing, so the
+ # list would be served unfiltered. Let it reach the handlers
+ # below, which return an error instead of a list.
+ policy_snapshot = settings_manager.get_settings_snapshot()
policy_snapshot = policy_snapshot or {}
if apply_egress_filter:
# Runs the guarded-URL overlay itself, after the PDP pass.
@@ -4127,6 +4213,8 @@ def api_get_available_search_engines(
"favorites": favorites,
}
+ except SettingsValueError as error:
+ return _settings_value_error_response("available search engines", error)
except Exception:
logger.exception("Error getting available search engines")
return JSONResponse(
@@ -5129,6 +5217,8 @@ def api_get_db_setting(
return JSONResponse(
{"error": f"Setting not found: {key}"}, status_code=404
)
+ except SettingsValueError as error:
+ return _settings_value_error_response("setting", error)
except Exception:
logger.exception("Error getting setting {}", _log_value_preview(key))
return JSONResponse(
@@ -5367,6 +5457,34 @@ def _api_update_setting_sync(data, key, username):
{"error": f"Invalid value for setting {key}"},
status_code=400,
)
+ # set_setting() re-infers the type of a text row from
+ # the value, so a non-finite JSON number would be
+ # stored as an invalid number row. Check the row it
+ # will store.
+ rejection = (
+ None
+ if _is_reconciled_container
+ else _strict_read_rejection(
+ key,
+ value,
+ _infer_ui_element(value, db_setting.ui_element),
+ )
+ )
+ if rejection is not None:
+ logger.warning(
+ "Validation failed for setting {}: {}",
+ _log_value_preview(key),
+ rejection,
+ )
+ return JSONResponse(
+ {
+ "error": (
+ f"Invalid value for setting {key}: "
+ f"{rejection}"
+ )
+ },
+ status_code=400,
+ )
# Cross-field egress-policy validation. The full-form saves run
# these guards unconditionally for every key; this single-key
@@ -5516,6 +5634,28 @@ def _api_update_setting_sync(data, key, username):
if "ui_element" not in setting_dict:
setting_dict["ui_element"] = _infer_ui_element(value)
+ # The caller may choose the type. An unsupported type, or a
+ # value that type cannot convert, would make every
+ # effective settings read of this account fail, and only a
+ # DELETE could undo it.
+ rejection = _strict_read_rejection(
+ key, value, setting_dict["ui_element"]
+ )
+ if rejection is not None:
+ logger.warning(
+ "Rejected new setting {}: {}",
+ _log_value_preview(key),
+ rejection,
+ )
+ return JSONResponse(
+ {
+ "error": (
+ f"Invalid value for setting {key}: {rejection}"
+ )
+ },
+ status_code=400,
+ )
+
# Creation has no prior value, so the sentinel cannot mean
# "keep the stored secret" the way it does on the update path —
# every occurrence of it, exact match included, is a corrupted
diff --git a/src/local_deep_research/web/services/settings_service.py b/src/local_deep_research/web/services/settings_service.py
index 1c4a77b37e..ef542ffcf9 100644
--- a/src/local_deep_research/web/services/settings_service.py
+++ b/src/local_deep_research/web/services/settings_service.py
@@ -5,6 +5,7 @@ from loguru import logger
from sqlalchemy.orm import Session
from ...database.models import Setting
+from ...settings.exceptions import SettingsValueError
from ...settings.manager import DYNAMIC_SETTINGS, get_typed_setting_value
from ...utilities.db_utils import get_settings_manager
@@ -180,22 +181,29 @@ def validate_setting(
Returns:
tuple[bool, Optional[str]]: (is_valid, error_message)
"""
- # Keep the submitted value so a failed conversion cannot be confused with
- # an intentionally-unset optional numeric. The converter uses ``None`` for
- # both outcomes when its default is None.
raw_value = value
-
- # Convert value to appropriate type first using SettingsManager's logic.
- # Inlined (rather than delegating to routers.settings.validate_setting) so
- # this service no longer imports the router — breaking the settings
- # service <-> routes circular dependency (#2898).
- value = get_typed_setting_value(
- key=str(setting.key),
- value=value,
- ui_element=str(setting.ui_element),
- default=None,
- check_env=False,
- )
+ numeric_ui = setting.ui_element in ("number", "slider", "range")
+ # Blank form inputs explicitly clear optional numeric settings; they are
+ # normalized to None on write, not used as a fallback for bad numbers.
+ if numeric_ui and (
+ raw_value is None
+ or (isinstance(raw_value, str) and not raw_value.strip())
+ ):
+ return True, None
+ try:
+ value = get_typed_setting_value(
+ key=str(setting.key),
+ value=value,
+ ui_element=str(setting.ui_element),
+ default=None,
+ check_env=False,
+ )
+ except SettingsValueError as error:
+ if numeric_ui:
+ return False, "Value must be a number"
+ if setting.ui_element == "checkbox":
+ return False, "Value must be a boolean"
+ return False, error.reason
# Validate based on UI element type
if setting.ui_element == "checkbox":
@@ -204,13 +212,6 @@ def validate_setting(
return False, "Value must be a boolean"
elif setting.ui_element in ("number", "slider", "range"):
- # None and blank HTML inputs represent an intentionally-unset optional
- # numeric; a nonblank conversion failure must remain invalid.
- if raw_value is None or (
- isinstance(raw_value, str) and not raw_value.strip()
- ):
- return True, None
-
# After conversion, should be numeric
if (
isinstance(raw_value, bool)
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
index 6d257ce8ef..858ce2b181 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -1696,6 +1696,23 @@
});
}
+ /**
+ * Replace the loading spinner with a lasting error message. For an
+ * invalid configured setting the server's message names the key, its
+ * source and the reason, which the user needs to repair it. A toast or
+ * a self-hiding alert alone would leave "Loading settings..." on screen.
+ * @param {string} message - The error message (rendered as text only)
+ */
+ function showSettingsLoadError(message) {
+ const text = 'Error loading settings: ' + message;
+ const box = document.createElement('div');
+ box.className = 'alert alert-danger';
+ box.setAttribute('role', 'alert');
+ box.textContent = text;
+ settingsContent.replaceChildren(box);
+ showAlert(text, 'error', false);
+ }
+
/**
* Load settings from the API
*/
@@ -1753,11 +1770,11 @@
initExpandedJsonControls();
}, 100);
} else {
- showAlert('Error loading settings: ' + data.message, 'error');
+ showSettingsLoadError(data.message);
}
})
.catch(error => {
- showAlert('Error loading settings: ' + error, 'error');
+ showSettingsLoadError(error?.message || String(error));
});
}
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
index 5951b34cff..6dff8d3ab7 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_elasticsearch.py
@@ -8,6 +8,7 @@ from langchain_core.language_models import BaseLLM
from ...constants import DEFAULT_SEARCH_TOOL, SNIPPET_LENGTH_SHORT
from ...security.secure_logging import logger
+from ...settings.exceptions import SettingsValueError
from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
@@ -170,6 +171,8 @@ class ElasticsearchSearchEngine(BaseSearchEngine):
cls._AVAILABILITY_TTL_SECONDS,
)
return available
+ except SettingsValueError:
+ raise
except Exception as exc:
logger.debug(
"Elasticsearch is_available probe raised exception ({}) — failing open",
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py b/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py
index 6bd45c6789..92d803cc55 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_nasa_ads.py
@@ -7,6 +7,7 @@ from ...security.secure_logging import logger
from ...constants import SNIPPET_LENGTH_LONG, USER_AGENT
from ...security.safe_requests import safe_get
+from ...settings.exceptions import SettingsValueError
from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
@@ -88,6 +89,8 @@ class NasaAdsSearchEngine(BaseSearchEngine):
"search.engine.web.nasa_ads.api_key",
settings_snapshot=settings_snapshot,
)
+ except SettingsValueError:
+ raise
except Exception:
logger.debug(
"Failed to read nasa_ads.api_key from settings snapshot",
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py b/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
index 93d1331b92..8b8c704de1 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
@@ -9,6 +9,7 @@ from langchain_core.language_models import BaseLLM
from ...constants import SNIPPET_LENGTH_LONG, USER_AGENT
from ...security.safe_requests import safe_get
from ...security.secure_logging import logger
+from ...settings.exceptions import SettingsValueError
from ...utilities.openalex_enrichment import (
OPENALEX_AUTH_FAILURE_STATUSES,
bounded_error_body,
@@ -135,6 +136,8 @@ class OpenAlexSearchEngine(BaseSearchEngine):
default="",
settings_snapshot=settings_snapshot,
)
+ except SettingsValueError:
+ raise
except Exception:
logger.debug(
"Failed to read openalex.email from settings snapshot"
@@ -155,6 +158,8 @@ class OpenAlexSearchEngine(BaseSearchEngine):
default="",
settings_snapshot=settings_snapshot,
)
+ except SettingsValueError:
+ raise
except Exception:
logger.debug(
"Failed to read openalex.api_key from settings snapshot"
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py
index 62cbdd6f67..a8e49abeeb 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_semantic_scholar.py
@@ -8,6 +8,7 @@ from requests.adapters import HTTPAdapter
from urllib3.util import Retry
from ...constants import SNIPPET_LENGTH_SHORT
+from ...settings.exceptions import SettingsValueError
from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
from ...security import SafeSession
@@ -108,6 +109,8 @@ class SemanticScholarSearchEngine(BaseSearchEngine):
"search.engine.web.semantic_scholar.api_key",
settings_snapshot=settings_snapshot,
)
+ except SettingsValueError:
+ raise
except Exception:
logger.debug(
"Failed to read semantic_scholar.api_key from settings snapshot",
diff --git a/src/local_deep_research/web_search_engines/search_engine_factory.py b/src/local_deep_research/web_search_engines/search_engine_factory.py
index d88ca27ae3..d12ecd072b 100644
--- a/src/local_deep_research/web_search_engines/search_engine_factory.py
+++ b/src/local_deep_research/web_search_engines/search_engine_factory.py
@@ -5,6 +5,7 @@ from ..security.egress.policy import PolicyDeniedError
from ..security.log_sanitizer import scrub_error
from ..security.module_whitelist import get_safe_module_class
from ..security.secure_logging import logger
+from ..settings.exceptions import SettingsValueError
from .engine_groups import is_collection_engine
from .retriever_registry import retriever_registry
from ..utilities.search_utilities import LANGUAGE_CODE_MAP
@@ -831,6 +832,8 @@ def create_search_engine(
# rather than being downgraded to a generic "failed to create"
# None — which would fail OPEN from an enforcement standpoint.
raise
+ except SettingsValueError:
+ raise
except Exception as e:
safe_msg = scrub_error(e, api_key)
logger.exception(
@@ -1033,6 +1036,8 @@ def _create_full_search_wrapper(
pass
return service
+ except SettingsValueError:
+ raise
except Exception as e:
# Extract any credential values the wrapper was going to receive
# so a constructor exception echoing them gets literal-redacted
@@ -1219,6 +1224,8 @@ def get_search(
except TypeError:
try:
avail = engine.is_available()
+ except SettingsValueError:
+ raise
except Exception as exc:
logger.debug(
"Engine availability fallback failed for {} ({})",
@@ -1226,6 +1233,8 @@ def get_search(
type(exc).__name__,
)
avail = None
+ except SettingsValueError:
+ raise
except Exception as exc:
logger.debug(
"Engine availability check failed for {} ({})",
diff --git a/src/local_deep_research/web_search_engines/search_engines_config.py b/src/local_deep_research/web_search_engines/search_engines_config.py
index 82fbc689b2..164bd3915e 100644
--- a/src/local_deep_research/web_search_engines/search_engines_config.py
+++ b/src/local_deep_research/web_search_engines/search_engines_config.py
@@ -14,6 +14,7 @@ from ..security.secure_logging import logger
from ..config.thread_settings import get_setting_from_snapshot
from ..security.log_sanitizer import scrub_error
+from ..settings.exceptions import SettingsValueError
from ..utilities.db_utils import get_settings_manager
from .search_engine_base import _is_api_key_placeholder
@@ -119,6 +120,8 @@ def _get_setting(
return get_setting_from_snapshot(
key, default_value, settings_snapshot=settings_snapshot
)
+ except SettingsValueError:
+ raise
except Exception as e:
logger.debug(
f"Could not get setting {key} from snapshot: {scrub_error(e)}"
@@ -129,6 +132,8 @@ def _get_setting(
try:
settings_manager = get_settings_manager(db_session, username)
return settings_manager.get_setting(key, default_value)
+ except SettingsValueError:
+ raise
except Exception as e:
logger.debug(
f"Could not get setting {key} from db_session: {scrub_error(e)}"
@@ -642,6 +647,8 @@ def _engine_class_is_available(
return bool(
engine_class.is_available(settings_snapshot=settings_snapshot)
)
+ except SettingsValueError:
+ raise
except Exception as exc:
logger.debug(
"is_available raised for {} — treating as available ({})",
diff --git a/tests/advanced_search_system/tools/test_fetch_modes.py b/tests/advanced_search_system/tools/test_fetch_modes.py
index 0450fb68ae..31e1b0dd44 100644
--- a/tests/advanced_search_system/tools/test_fetch_modes.py
+++ b/tests/advanced_search_system/tools/test_fetch_modes.py
@@ -26,6 +26,7 @@ from local_deep_research.advanced_search_system.tools.fetch import (
FETCH_MODES,
build_fetch_tool,
)
+from local_deep_research.settings.exceptions import SettingsValueError
def _fetcher_cm(*, status="success", title="Page", content="Body text"):
@@ -1766,24 +1767,27 @@ def _clear_max_fetches_environment(monkeypatch):
(50, 50, 50),
(51, 50, 50),
(-1, 9, 9),
- ("invalid", 9, 9),
+ ("invalid", 9, SettingsValueError),
(3.9, 3, 3),
- (False, 0, 0),
- (True, 1, 1),
+ (False, 0, SettingsValueError),
+ (True, 1, SettingsValueError),
("3.9", 9, 3),
- ("inf", 9, 9),
- ("-inf", 9, 9),
- ("nan", 9, 9),
- ("1e400", 9, 9),
- pytest.param("9" * 5000, 9, 9, id="very-long-number"),
- (float("inf"), 9, 9),
- (float("-inf"), 9, 9),
- (float("nan"), 9, 9),
+ ("inf", 9, SettingsValueError),
+ ("-inf", 9, SettingsValueError),
+ ("nan", 9, SettingsValueError),
+ ("1e400", 9, SettingsValueError),
+ pytest.param("9" * 5000, 9, SettingsValueError, id="very-long-number"),
+ (float("inf"), 9, SettingsValueError),
+ (float("-inf"), 9, SettingsValueError),
+ (float("nan"), 9, SettingsValueError),
],
)
def test_max_fetches_reader_preserves_snapshot_limits_and_default(
shape, value, legacy_expected, typed_expected
):
+ # A typed row that is not a finite number is an invalid configured
+ # setting: it raises instead of selecting the default. Raw and sparse
+ # legacy rows keep their int() coercion and fallback.
entry = value
if shape == "legacy":
entry = {"value": value}
@@ -1796,9 +1800,16 @@ def test_max_fetches_reader_preserves_snapshot_limits_and_default(
else entry
}
expected = typed_expected if shape == "typed" else legacy_expected
- assert (
- fetch_module._read_max_fetches_setting(snapshot, default=9) == expected
- )
+ if expected is SettingsValueError:
+ with pytest.raises(SettingsValueError) as raised:
+ fetch_module._read_max_fetches_setting(snapshot, default=9)
+ assert raised.value.key == "search.fetch.max_per_topic"
+ assert raised.value.source == "value"
+ else:
+ assert (
+ fetch_module._read_max_fetches_setting(snapshot, default=9)
+ == expected
+ )
assert snapshot == original
@@ -1811,12 +1822,12 @@ def test_max_fetches_reader_preserves_snapshot_limits_and_default(
("0", 0),
("51", 50),
("-1", 9),
- ("invalid", 1),
+ ("invalid", SettingsValueError),
("", 1),
- ("inf", 9),
- ("1e400", 9),
- ("nan", 9),
- pytest.param("9" * 5000, 9, id="very-long-env-number"),
+ ("inf", SettingsValueError),
+ ("1e400", SettingsValueError),
+ ("nan", SettingsValueError),
+ pytest.param("9" * 5000, SettingsValueError, id="very-long-env-number"),
],
)
def test_max_fetches_reader_pins_environment_precedence_by_snapshot_shape(
@@ -1829,12 +1840,21 @@ def test_max_fetches_reader_pins_environment_precedence_by_snapshot_shape(
elif shape == "typed":
entry = {"value": 1, "ui_element": "number"}
snapshot = {"search.fetch.max_per_topic": entry}
- # The canonical typed accessor applies environment priority; raw and
- # sparse legacy snapshots deliberately retain their historical behavior.
+ # The canonical typed accessor applies environment priority, and an
+ # override it cannot convert raises instead of falling back to the
+ # snapshot; raw and sparse legacy snapshots deliberately retain their
+ # historical behavior.
expected = typed_expected if shape == "typed" else 1
- assert (
- fetch_module._read_max_fetches_setting(snapshot, default=9) == expected
- )
+ if expected is SettingsValueError:
+ with pytest.raises(SettingsValueError) as raised:
+ fetch_module._read_max_fetches_setting(snapshot, default=9)
+ assert raised.value.source == "environment"
+ assert env_value not in str(raised.value)
+ else:
+ assert (
+ fetch_module._read_max_fetches_setting(snapshot, default=9)
+ == expected
+ )
assert snapshot == {"search.fetch.max_per_topic": entry}
@@ -1854,7 +1874,6 @@ def test_max_fetches_reader_typed_null_uses_canonical_environment_priority(
@pytest.mark.parametrize(
"entry",
[
- {"value": 5, "ui_element": "bogus"},
{"value": {"unexpected": 5}},
{"ui_element": "number"},
],
@@ -1868,6 +1887,16 @@ def test_max_fetches_reader_invalid_rows_keep_caller_default(entry):
)
+def test_max_fetches_reader_unsupported_type_is_not_replaced_by_default():
+ with pytest.raises(SettingsValueError) as raised:
+ fetch_module._read_max_fetches_setting(
+ {"search.fetch.max_per_topic": {"value": 5, "ui_element": "bogus"}},
+ default=9,
+ )
+ assert raised.value.key == "search.fetch.max_per_topic"
+ assert raised.value.reason == "unsupported setting type"
+
+
def test_max_fetches_reader_accessor_failure_keeps_caller_default():
with patch.object(
thread_settings,
@@ -1921,7 +1950,7 @@ def test_missing_max_fetches_snapshot_keeps_default_over_thread_context(
({"value": 1, "ui_element": "number"}, None, 3, 1),
({"value": 0, "ui_element": "number"}, None, 3, 3),
({"value": 51, "ui_element": "number"}, None, 51, 50),
- ({"value": "inf", "ui_element": "number"}, None, 3, 2),
+ ({"value": "inf", "ui_element": "number"}, 0, 3, 3),
({"value": 1, "ui_element": "number"}, 0, 3, 3),
],
)
@@ -1958,7 +1987,6 @@ def test_fetch_tools_apply_snapshot_limits_and_explicit_overrides(
"env_value, override, attempts, expected",
[
("7", None, 8, 7),
- ("inf", None, 3, 2),
("0", None, 3, 3),
("inf", 0, 3, 3),
("7", 2, 3, 2),
@@ -1989,3 +2017,35 @@ def test_fetch_tools_apply_typed_environment_limits_and_explicit_overrides(
arguments["focus"] = "Relevant evidence"
tool.invoke(arguments)
assert cm.__enter__.return_value.fetch.call_count == expected
+
+
+ "mode", ["full", "summary_focus", "summary_focus_query"]
+)
+ "entry, env_value, source",
+ [
+ ({"value": "inf", "ui_element": "number"}, None, "value"),
+ ({"value": 1, "ui_element": "number"}, "inf", "environment"),
+ ({"value": 1, "ui_element": "unsupported-widget"}, None, "value"),
+ ],
+ ids=["typed-row", "typed-override", "unsupported-type"],
+)
+def test_fetch_tools_refuse_an_invalid_typed_limit(
+ mode, entry, env_value, source, monkeypatch
+):
+ # Without an explicit max_fetches the builder reads the setting. An
+ # invalid typed limit must stop the build, not become the default 2.
+ if env_value is not None:
+ monkeypatch.setenv("LDR_SEARCH_FETCH_MAX_PER_TOPIC", env_value)
+ with pytest.raises(SettingsValueError) as raised:
+ build_fetch_tool(
+ mode,
+ SearchResultsCollector([]),
+ model=_model_returning("Useful summary"),
+ overall_query="Research question",
+ settings_snapshot={"search.fetch.max_per_topic": entry},
+ )
+ assert raised.value.key == "search.fetch.max_per_topic"
+ assert raised.value.source == source
+ assert raised.value.__context__ is None
diff --git a/tests/advanced_search_system/tools/test_fetch_settings_errors.py b/tests/advanced_search_system/tools/test_fetch_settings_errors.py
new file mode 100644
index 0000000000..b02970622a
--- /dev/null
+++ b/tests/advanced_search_system/tools/test_fetch_settings_errors.py
@@ -0,0 +1,178 @@
+"""Fetch limits must preserve managed settings errors before doing work."""
+
+from types import SimpleNamespace
+from unittest.mock import MagicMock, Mock
+
+import pytest
+
+from local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy import (
+ SearchResultsCollector,
+)
+from local_deep_research.advanced_search_system.tools.fetch import (
+ CONTENT_MAX_LENGTH,
+ _read_content_max_length_setting,
+ build_fetch_tool,
+)
+from local_deep_research.settings.exceptions import SettingsValueError
+
+
+KEY = "search.fetch.content_max_length"
+ENVIRONMENT_KEY = "LDR_SEARCH_FETCH_CONTENT_MAX_LENGTH"
+INVALID_VALUE = "invalid-private-number"
+
+
+def _invalid_snapshot(monkeypatch, source):
+ monkeypatch.delenv(ENVIRONMENT_KEY, raising=False)
+ value = INVALID_VALUE if source == "value" else 12000
+ if source == "environment":
+ monkeypatch.setenv(ENVIRONMENT_KEY, INVALID_VALUE)
+ return {KEY: {"value": value, "ui_element": "number"}}
+
+
[email protected]("source", ["value", "environment"])
+def test_invalid_managed_length_is_not_replaced_by_default(monkeypatch, source):
+ snapshot = _invalid_snapshot(monkeypatch, source)
+
+ with pytest.raises(SettingsValueError) as raised:
+ _read_content_max_length_setting(snapshot)
+
+ assert raised.value.key == KEY
+ assert raised.value.source == source
+ assert INVALID_VALUE not in str(raised.value)
+ assert raised.value.__cause__ is None
+ assert raised.value.__context__ is None
+
+
+def test_unsupported_length_type_is_not_replaced_by_default(monkeypatch):
+ monkeypatch.delenv(ENVIRONMENT_KEY, raising=False)
+
+ with pytest.raises(SettingsValueError) as raised:
+ _read_content_max_length_setting(
+ {KEY: {"value": 12000, "ui_element": "unsupported-widget"}}
+ )
+
+ assert raised.value.key == KEY
+
+
+def _tool_case(monkeypatch, snapshot, mode, url):
+ payload = {
+ "status": "success",
+ "title": "Example",
+ "content": "Example content",
+ "url": url,
+ }
+ fetcher = MagicMock()
+ fetcher.return_value.__enter__.return_value.fetch.return_value = payload
+ monkeypatch.setattr(
+ "local_deep_research.content_fetcher.ContentFetcher", fetcher
+ )
+ collector = SearchResultsCollector([])
+ monkeypatch.setattr(
+ collector, "try_record_fetch", Mock(wraps=collector.try_record_fetch)
+ )
+ model = Mock()
+ model.invoke.return_value = SimpleNamespace(content="Relevant excerpt")
+ resolver = Mock(
+ side_effect=lambda target: (
+ payload if target.startswith("/library/document/") else None
+ )
+ )
+ tool = build_fetch_tool(
+ mode,
+ collector,
+ settings_snapshot=snapshot,
+ model=model,
+ overall_query="research topic",
+ library_resolver=resolver,
+ )
+ arguments = {"url": url}
+ if mode != "full":
+ arguments["focus"] = "research topic"
+ return SimpleNamespace(
+ tool=tool,
+ arguments=arguments,
+ fetcher=fetcher,
+ collector=collector,
+ model=model,
+ resolver=resolver,
+ )
+
+
[email protected]("source", ["value", "environment"])
+ "mode", ["full", "summary_focus", "summary_focus_query"]
+)
+ "url", ["https://example.com/paper", "/library/document/example"]
+)
+def test_invalid_length_stops_fetch_without_consuming_budget(
+ monkeypatch, source, mode, url
+):
+ snapshot = _invalid_snapshot(monkeypatch, source)
+ case = _tool_case(monkeypatch, snapshot, mode, url)
+
+ result = case.tool.invoke(case.arguments)
+
+ assert result.startswith("Error fetching ")
+ assert KEY in result
+ assert INVALID_VALUE not in result
+ case.fetcher.assert_not_called()
+ case.resolver.assert_not_called()
+ case.collector.try_record_fetch.assert_not_called()
+ assert case.collector.get_fetch_count() == 0
+ case.model.invoke.assert_not_called()
+
+
+ "mode", ["full", "summary_focus", "summary_focus_query"]
+)
+ "url", ["https://example.com/paper", "/library/document/example"]
+)
+def test_valid_length_allows_fetch_and_preserves_budget_accounting(
+ monkeypatch, mode, url
+):
+ monkeypatch.delenv(ENVIRONMENT_KEY, raising=False)
+ snapshot = {KEY: {"value": 12000, "ui_element": "number"}}
+ case = _tool_case(monkeypatch, snapshot, mode, url)
+
+ result = case.tool.invoke(case.arguments)
+
+ assert result.startswith("[1] Title: Example")
+ expected_content = (
+ "Example content" if mode == "full" else "Relevant excerpt"
+ )
+ assert expected_content in result
+ case.resolver.assert_called_once_with(url)
+ if url.startswith("https://"):
+ case.fetcher.return_value.__enter__.return_value.fetch.assert_called_once_with(
+ url, max_length=12000
+ )
+ assert case.collector.get_fetch_count() == 1
+ else:
+ case.fetcher.assert_not_called()
+ assert case.collector.get_fetch_count() == 0
+ assert case.model.invoke.call_count == (0 if mode == "full" else 1)
+
+
[email protected]("override,expected", [(None, 12000), ("15000", 15000)])
+def test_valid_managed_length_retains_environment_precedence(
+ monkeypatch, override, expected
+):
+ monkeypatch.delenv(ENVIRONMENT_KEY, raising=False)
+ if override is not None:
+ monkeypatch.setenv(ENVIRONMENT_KEY, override)
+
+ assert (
+ _read_content_max_length_setting(
+ {KEY: {"value": 12000, "ui_element": "number"}}
+ )
+ == expected
+ )
+
+
[email protected]("snapshot", [None, {}, {KEY: "invalid"}, {KEY: -5}])
+def test_missing_or_untyped_legacy_values_keep_fallback(monkeypatch, snapshot):
+ monkeypatch.delenv(ENVIRONMENT_KEY, raising=False)
+
+ assert _read_content_max_length_setting(snapshot) == CONTENT_MAX_LENGTH
diff --git a/tests/api/test_in_memory_settings_environment.py b/tests/api/test_in_memory_settings_environment.py
index 1c5ccd3f62..f38e3c5085 100644
--- a/tests/api/test_in_memory_settings_environment.py
+++ b/tests/api/test_in_memory_settings_environment.py
@@ -7,6 +7,7 @@ import pytest
from local_deep_research.api.settings_utils import InMemorySettingsManager
from local_deep_research.settings.base import ISettingsManager
from local_deep_research.settings.manager import SettingsManager
+from local_deep_research.settings.exceptions import SettingsValueError
@pytest.fixture
@@ -150,6 +151,28 @@ def test_import_preserves_stored_baseline_and_refreshes_locked_metadata(
assert manager.get_setting("policy.egress_scope") == "adaptive"
+def test_preserved_value_does_not_validate_ignored_import_input(
+ monkeypatch, default_settings
+):
+ manager = make_manager(default_settings)
+ monkeypatch.setenv("LDR_APP_PORT", "8080")
+ manager.import_settings(
+ {
+ "app.port": {
+ "value": "invalid-ignored-input",
+ "ui_element": "number",
+ "description": "Updated description",
+ }
+ },
+ preserve_environment_locked=True,
+ )
+ exported = manager.get_all_settings(include_environment_overrides=False)
+ assert exported["app.port"]["value"] == 5000
+ assert exported["app.port"]["description"] == "Updated description"
+ assert manager.get_setting("app.port") == 8080
+ assert manager.get_setting("app.port", check_env=False) == 5000
+
+
def test_load_defaults_preserves_stored_baseline_and_refreshes_locked_metadata(
monkeypatch, default_settings
):
@@ -242,8 +265,16 @@ def test_import_of_bare_scalar_still_replaces_unlocked_entry(
{"app.port": 9999}, preserve_environment_locked=True
)
- # Then the scalar import behaves as before the preservation flag
- assert manager.get_all_settings()["app.port"] == 9999
+ # Raw exports still expose the replaced value, but effective reads cannot
+ # validate an entry that no longer carries type metadata.
+ assert (
+ manager.get_all_settings(include_environment_overrides=False)[
+ "app.port"
+ ]
+ == 9999
+ )
+ with pytest.raises(SettingsValueError, match="app.port"):
+ manager.get_all_settings()
def test_settings_managers_expose_environment_override_toggle():
diff --git a/tests/api/test_in_memory_settings_import_atomicity.py b/tests/api/test_in_memory_settings_import_atomicity.py
new file mode 100644
index 0000000000..907b00f208
--- /dev/null
+++ b/tests/api/test_in_memory_settings_import_atomicity.py
@@ -0,0 +1,99 @@
+"""A rejected import must preserve the live in-memory configuration."""
+
+import copy
+
+import pytest
+
+from local_deep_research.api.settings_utils import InMemorySettingsManager
+from local_deep_research.settings.exceptions import SettingsValueError
+
+
+def full_snapshot():
+ manager = InMemorySettingsManager()
+ manager.set_setting("llm.model", "previously-configured-model")
+ before = manager.get_all_settings(include_environment_overrides=False)
+ # Include every saved entry, with a changed value before the rejected
+ # entry and a configured model after it. Missing later entries would be
+ # data loss, not the requested removal of keys absent from the import.
+ keys = ["app.host", "app.port"] + [
+ key for key in before if key not in ("app.host", "app.port")
+ ]
+ incoming = {key: copy.deepcopy(before[key]) for key in keys}
+ incoming["app.host"]["value"] = "replacement.example"
+ incoming["app.host"]["description"] = "Imported host description"
+ try:
+ yield manager, before, incoming
+ finally:
+ manager._base_manager.close()
+
+
[email protected]("delete_extra", [False, True])
[email protected]("preserve_environment_locked", [False, True])
[email protected]("invalid_kind", ["metadata", "custom_number"])
+def test_rejected_full_import_preserves_live_state(
+ full_snapshot,
+ monkeypatch,
+ delete_extra,
+ preserve_environment_locked,
+ invalid_kind,
+):
+ manager, before, incoming = full_snapshot
+ if preserve_environment_locked:
+ monkeypatch.setenv("LDR_APP_HOST", "operator.example")
+ if invalid_kind == "metadata":
+ invalid_key = "app.port"
+ incoming[invalid_key]["ui_element"] = "unsupported-widget"
+ else:
+ invalid_key = "custom.import_number"
+ incoming = {
+ "app.host": incoming["app.host"],
+ invalid_key: {"value": "invalid-number", "ui_element": "number"},
+ **{
+ key: value
+ for key, value in incoming.items()
+ if key != "app.host"
+ },
+ }
+ submitted = copy.deepcopy(incoming)
+
+ with pytest.raises(SettingsValueError) as raised:
+ manager.import_settings(
+ incoming,
+ delete_extra=delete_extra,
+ preserve_environment_locked=preserve_environment_locked,
+ )
+
+ assert raised.value.key == invalid_key
+ assert (
+ manager.get_all_settings(include_environment_overrides=False) == before
+ )
+ assert incoming == submitted
+ assert manager.get_setting("llm.model", check_env=False) == (
+ "previously-configured-model"
+ )
+
+
[email protected]("delete_extra", [False, True])
+def test_valid_full_import_applies_changes_and_preserves_later_entries(
+ full_snapshot, delete_extra
+):
+ manager, before, incoming = full_snapshot
+ submitted = copy.deepcopy(incoming)
+
+ manager.import_settings(incoming, delete_extra=delete_extra)
+
+ after = manager.get_all_settings(include_environment_overrides=False)
+ assert after.keys() == before.keys()
+ assert (
+ manager.get_setting("app.host", check_env=False)
+ == "replacement.example"
+ )
+ assert (
+ manager.get_setting("app.port", check_env=False)
+ == before["app.port"]["value"]
+ )
+ assert manager.get_setting("llm.model", check_env=False) == (
+ "previously-configured-model"
+ )
+ assert incoming == submitted
diff --git a/tests/api/test_settings_snapshot.py b/tests/api/test_settings_snapshot.py
index 97c5b1fa1c..74864591ba 100644
--- a/tests/api/test_settings_snapshot.py
+++ b/tests/api/test_settings_snapshot.py
@@ -3,12 +3,16 @@ Tests for InMemorySettingsManager.get_settings_snapshot() and import_settings()
in api/settings_utils.py.
Tests cover:
-- get_settings_snapshot: full format extraction, simplified format passthrough, mixed
+- get_settings_snapshot: typed extraction, invalid stored shapes, missing optional values
- import_settings: overwrite=True, overwrite=False, delete_extra, type handling, empty
"""
from unittest.mock import patch, MagicMock
+import pytest
+
+from local_deep_research.settings.exceptions import SettingsValueError
+
def _make_manager_with_settings(settings_dict):
"""Create an InMemorySettingsManager with pre-loaded settings (no disk I/O)."""
@@ -23,6 +27,7 @@ def _make_manager_with_settings(settings_dict):
mgr = InMemorySettingsManager()
mgr._settings = settings_dict.copy()
mgr._base_manager = MagicMock()
+ mgr._base_manager.default_settings = {}
return mgr
@@ -37,25 +42,29 @@ class TestGetSettingsSnapshot:
snapshot = mgr.get_settings_snapshot()
assert snapshot["key1"] == 42
- def test_simplified_format_passthrough(self):
- """Non-dict or dict-without-value entries pass through as-is."""
+ def test_scalar_store_entry_raises_but_remains_exportable(self):
mgr = _make_manager_with_settings({"key1": "simple_value"})
- snapshot = mgr.get_settings_snapshot()
- assert snapshot["key1"] == "simple_value"
-
- def test_mixed_formats(self):
- """Mix of full and simplified formats in one snapshot."""
- mgr = _make_manager_with_settings(
- {
- "full_key": {"value": True, "ui_element": "checkbox"},
- "simple_key": 100,
- "dict_no_value": {"other": "data"},
- }
- )
- snapshot = mgr.get_settings_snapshot()
- assert snapshot["full_key"] is True
- assert snapshot["simple_key"] == 100
- assert snapshot["dict_no_value"] == {"other": "data"}
+ with pytest.raises(SettingsValueError, match="key1"):
+ mgr.get_settings_snapshot()
+ assert mgr.get_all_settings(include_environment_overrides=False) == {
+ "key1": "simple_value"
+ }
+
+ def test_bad_entry_does_not_return_partial_snapshot(self):
+ original = {
+ "full_key": {"value": True, "ui_element": "checkbox"},
+ "simple_key": 100,
+ }
+ mgr = _make_manager_with_settings(original)
+ with pytest.raises(SettingsValueError, match="simple_key"):
+ mgr.get_settings_snapshot()
+ assert mgr._settings == original
+
+ def test_missing_optional_value_keeps_its_metadata(self):
+ original = {"optional": {"ui_element": "text"}}
+ mgr = _make_manager_with_settings(original)
+ assert mgr.get_setting("optional") is None
+ assert mgr.get_settings_snapshot() == original
def test_empty_settings(self):
"""Empty settings → empty snapshot."""
@@ -83,7 +92,7 @@ class TestGetSettingsSnapshot:
def test_list_value(self):
"""Full format with list value → snapshot has the list."""
mgr = _make_manager_with_settings(
- {"key": {"value": [1, 2, 3], "ui_element": "text"}}
+ {"key": {"value": [1, 2, 3], "ui_element": "json"}}
)
snapshot = mgr.get_settings_snapshot()
assert snapshot["key"] == [1, 2, 3]
@@ -126,15 +135,13 @@ class TestImportSettings:
assert "new_key" in mgr._settings
def test_import_full_format_with_type_conversion(self):
- """Full format dicts get _get_typed_value applied."""
+ """Full format values are converted by the real import path."""
mgr = _make_manager_with_settings({})
- mgr._get_typed_value = MagicMock(return_value=42)
mgr.import_settings(
{"key": {"value": "42", "ui_element": "number"}}, overwrite=True
)
- mgr._get_typed_value.assert_called()
- # Value should be the typed result
assert mgr._settings["key"]["value"] == 42
+ assert type(mgr.get_setting("key")) is int
def test_import_simple_value_no_type_conversion(self):
"""Simple (non-dict) values are stored as-is without type conversion."""
diff --git a/tests/api/test_settings_utils.py b/tests/api/test_settings_utils.py
index c5d05a37f4..e3b304c4f2 100644
--- a/tests/api/test_settings_utils.py
+++ b/tests/api/test_settings_utils.py
@@ -11,6 +11,7 @@ from local_deep_research.api.settings_utils import (
extract_setting_value,
)
from local_deep_research.settings.manager import SettingsManager
+from local_deep_research.settings.exceptions import SettingsValueError
class TestInMemorySettingsManager:
@@ -239,12 +240,12 @@ class TestInMemorySettingsManager:
assert manager._get_typed_value(setting_data, "hello") == "hello"
def test_get_typed_value_unknown_type(self):
- """Test type conversion for unknown ui_element returns as-is."""
+ """Unknown ui_element is an explicit configuration error."""
manager = InMemorySettingsManager()
setting_data = {"ui_element": "unknown_type"}
- result = manager._get_typed_value(setting_data, "value")
- assert result == "value"
+ with pytest.raises(SettingsValueError):
+ manager._get_typed_value(setting_data, "value")
def test_load_from_defaults_file(self):
"""Test that load_from_defaults_file reloads defaults."""
diff --git a/tests/api/test_settings_utils_gaps.py b/tests/api/test_settings_utils_gaps.py
index 4fdd3fc800..452eccfd7a 100644
--- a/tests/api/test_settings_utils_gaps.py
+++ b/tests/api/test_settings_utils_gaps.py
@@ -9,6 +9,8 @@ test_settings_utils_behavior.py by covering paths that those files miss.
import pytest
+from local_deep_research.settings.exceptions import SettingsValueError
+
from local_deep_research.api.settings_utils import (
InMemorySettingsManager,
extract_bool_setting,
@@ -56,9 +58,9 @@ class TestGetTypedValueConversionEdgeCases:
assert manager._get_typed_value({"ui_element": ui}, None) is None
def test_number_with_empty_string(self, manager):
- """Empty string cannot be parsed as number; returns original value."""
- result = manager._get_typed_value({"ui_element": "number"}, "")
- assert result == ""
+ """Empty numeric input is invalid rather than an absent value."""
+ with pytest.raises(SettingsValueError):
+ manager._get_typed_value({"ui_element": "number"}, "")
def test_range_with_negative_float(self, manager):
result = manager._get_typed_value({"ui_element": "range"}, "-2.5")
@@ -177,12 +179,18 @@ class TestGetSettingsSnapshot:
snapshot = manager.get_settings_snapshot()
assert snapshot["snap.test"] == "hello"
- def test_non_dict_settings_passed_through(self, manager):
- """If a setting is not a dict (unlikely but possible), pass through."""
- # Force a raw value into _settings
+ def test_non_dict_settings_fail_effective_read_but_remain_exportable(
+ self, manager
+ ):
manager._settings["raw.val"] = "plain_string"
- snapshot = manager.get_settings_snapshot()
- assert snapshot["raw.val"] == "plain_string"
+ with pytest.raises(SettingsValueError, match="raw.val"):
+ manager.get_settings_snapshot()
+ assert (
+ manager.get_all_settings(include_environment_overrides=False)[
+ "raw.val"
+ ]
+ == "plain_string"
+ )
def test_snapshot_is_independent_copy(self, manager):
"""Modifying snapshot should not affect manager state."""
@@ -251,14 +259,15 @@ class TestImportSettingsTypedValues:
all_settings = manager.get_all_settings()
assert all_settings["imp.bool"]["value"] is True
- def test_plain_value_stored_as_is(self, manager):
- """Non-dict values are stored without type conversion."""
- manager.import_settings(
- {"imp.raw": "just_a_string"},
- delete_extra=True,
- )
- all_settings = manager.get_all_settings()
- assert all_settings["imp.raw"] == "just_a_string"
+ def test_plain_value_is_exportable_but_not_an_effective_setting(
+ self, manager
+ ):
+ manager.import_settings({"imp.raw": "just_a_string"}, delete_extra=True)
+ assert manager.get_all_settings(
+ include_environment_overrides=False
+ ) == {"imp.raw": "just_a_string"}
+ with pytest.raises(SettingsValueError, match="imp.raw"):
+ manager.get_all_settings()
# ---------------------------------------------------------------------------
diff --git a/tests/api/test_settings_utils_typed_value.py b/tests/api/test_settings_utils_typed_value.py
index 2932384c6c..28b2fc2346 100644
--- a/tests/api/test_settings_utils_typed_value.py
+++ b/tests/api/test_settings_utils_typed_value.py
@@ -5,9 +5,12 @@ Critical for ensuring settings are stored with correct types. Edge
cases around type conversion failures are untested.
"""
+import traceback
+
import pytest
from local_deep_research.api.settings_utils import InMemorySettingsManager
+from local_deep_research.settings.exceptions import SettingsValueError
@pytest.fixture
@@ -134,13 +137,12 @@ class TestGetTypedValuePassword:
class TestGetTypedValueUnknownType:
- """Unknown ui_element types — value returned as-is."""
+ """Unknown type metadata cannot silently pass through."""
- def test_unknown_type_returns_value(self, manager):
- result = manager._get_typed_value(
- {"ui_element": "custom_widget"}, "val"
- )
- assert result == "val"
+ @pytest.mark.parametrize("ui_element", ["custom_widget", None])
+ def test_unknown_type_raises(self, manager, ui_element):
+ with pytest.raises(SettingsValueError):
+ manager._get_typed_value({"ui_element": ui_element}, "val")
def test_missing_ui_element_defaults_to_text(self, manager):
result = manager._get_typed_value({}, "val")
@@ -148,13 +150,11 @@ class TestGetTypedValueUnknownType:
class TestGetTypedValueConversionFailure:
- """Type conversion failures — value returned as-is."""
+ """Invalid selected values are rejected instead of returned raw."""
def test_non_numeric_for_number(self, manager):
- result = manager._get_typed_value(
- {"ui_element": "number"}, "not_a_number"
- )
- assert result == "not_a_number"
+ with pytest.raises(SettingsValueError):
+ manager._get_typed_value({"ui_element": "number"}, "not_a_number")
def test_none_for_number(self, manager):
result = manager._get_typed_value({"ui_element": "number"}, None)
@@ -162,50 +162,39 @@ class TestGetTypedValueConversionFailure:
class TestGetTypedValueConversionFailureNeverLogsValue:
- """The conversion-failure WARNING must not interpolate the value.
-
- This is the sink #6201 changed from a raw f-string that interpolated
- the value, to a value-omitted form. Round 8 / B3: the change had NO
- direct regression test on this call path, so restoring the raw
- interpolation passed every test in this file.
-
- EXACT REVERT THIS CATCHES: restoring
- ``logger.warning(f"Failed to convert value {value} to type "
- f"{setting_type}")`` in ``InMemorySettingsManager._get_typed_value``
- -- the repr of the dict (nested secret included) or of the scalar
- secret then reaches the captured log.
-
- The POSITIVE CONTROL is not optional: the package disables its own
- loguru namespace at import, so "no secret captured" passes with
- nothing captured at all. The control is the warning itself, which
- must still name the declared ui_element and the value's type name.
- """
+ """Errors are useful diagnostics without retaining submitted values.
- def test_container_secret_never_logged(self, manager, loguru_caplog):
- secret = "sk-live-typed-value-8842"
+ The raised settings error is the positive control: this cannot pass just
+ because package logging is disabled. Both scalar ValueError text and
+ a nested container's repr must stay out of errors, logs and chaining.
+ """
- with loguru_caplog.at_level("WARNING"):
- # float(dict) raises TypeError -> the exact branch that used
- # to interpolate the whole container.
- result = manager._get_typed_value(
- {"ui_element": "number"}, {"stop_token": secret, "retries": 4}
+ @pytest.mark.parametrize("container", [False, True])
+ def test_rejected_value_is_absent_from_error_and_logs(
+ self, manager, loguru_caplog, container
+ ):
+ secret = "typed-value-private-sentinel-8842"
+ value = {"nested_secret": secret, "retries": 4} if container else secret
+ key = "custom.numeric"
+ with (
+ loguru_caplog.at_level("WARNING"),
+ pytest.raises(SettingsValueError) as raised,
+ ):
+ manager._get_typed_value(
+ {"key": key, "ui_element": "number"}, value
)
- assert result == {"stop_token": secret, "retries": 4}
- assert "number" in loguru_caplog.text # positive control
- assert "dict" in loguru_caplog.text # the kept diagnostic
- assert secret not in loguru_caplog.text
- assert "stop_token" not in loguru_caplog.text
-
- def test_scalar_secret_never_logged(self, manager, loguru_caplog):
- secret = "s3cr3t-typed-value-env-0417"
-
- with loguru_caplog.at_level("WARNING"):
- # float(str) raises ValueError -> the scalar arm of the same
- # sink (an LDR_* override is where a provider key lives).
- result = manager._get_typed_value({"ui_element": "number"}, secret)
-
- assert result == secret
- assert "number" in loguru_caplog.text # positive control
- assert "str" in loguru_caplog.text # the kept diagnostic
- assert secret not in loguru_caplog.text
+ error = raised.value
+ assert key in str(error)
+ assert error.__cause__ is None
+ assert error.__context__ is None
+ rendered = (
+ str(error)
+ + repr(error)
+ + repr(error.args)
+ + repr(vars(error))
+ + "".join(traceback.format_exception(error))
+ + loguru_caplog.text
+ )
+ assert secret not in rendered
+ assert "nested_secret" not in rendered
diff --git a/tests/config/test_snapshot_setting_errors.py b/tests/config/test_snapshot_setting_errors.py
new file mode 100644
index 0000000000..0bee40ad45
--- /dev/null
+++ b/tests/config/test_snapshot_setting_errors.py
@@ -0,0 +1,47 @@
+"""Configuration failures must survive background snapshot reads."""
+
+import pytest
+
+from local_deep_research.config.thread_settings import get_setting_from_snapshot
+from local_deep_research.settings.exceptions import SettingsValueError
+
+
[email protected]("read_key", ["search.iterations", "search"])
+def test_invalid_environment_stops_exact_and_namespace_snapshot_reads(
+ monkeypatch, read_key
+):
+ monkeypatch.setenv("LDR_SEARCH_ITERATIONS", "invalid-private-value")
+ snapshot = {"search.iterations": {"value": 5, "ui_element": "number"}}
+
+ with pytest.raises(SettingsValueError) as caught:
+ get_setting_from_snapshot(read_key, 2, settings_snapshot=snapshot)
+
+ assert caught.value.key == "search.iterations"
+ assert caught.value.source == "environment"
+ assert "invalid-private-value" not in str(caught.value)
+ assert caught.value.__context__ is None
+ assert caught.value.__cause__ is None
+ assert snapshot["search.iterations"]["value"] == 5
+
+
+def test_namespace_override_uses_full_setting_name(monkeypatch):
+ monkeypatch.setenv("LDR_SEARCH_ITERATIONS", "7")
+ monkeypatch.setenv("LDR_ITERATIONS", "invalid-unrelated-value")
+ snapshot = {"search.iterations": {"value": 5, "ui_element": "number"}}
+
+ assert get_setting_from_snapshot("search", settings_snapshot=snapshot) == {
+ "iterations": 7
+ }
+
+
[email protected]("read_key", ["search.iterations", "search"])
+def test_invalid_stored_snapshot_cannot_use_caller_default(
+ monkeypatch, read_key
+):
+ monkeypatch.delenv("LDR_SEARCH_ITERATIONS", raising=False)
+ snapshot = {
+ "search.iterations": {"value": "invalid", "ui_element": "number"}
+ }
+
+ with pytest.raises(SettingsValueError):
+ get_setting_from_snapshot(read_key, 2, settings_snapshot=snapshot)
diff --git a/tests/config/test_thread_settings_extended.py b/tests/config/test_thread_settings_extended.py
index cd88df4881..680215c631 100644
--- a/tests/config/test_thread_settings_extended.py
+++ b/tests/config/test_thread_settings_extended.py
@@ -181,7 +181,9 @@ class TestGetSettingFromSnapshotChildKeys:
"parent.child": {"value": "raw_child", "ui_element": "checkbox"},
}
result = get_setting_from_snapshot("parent", settings_snapshot=snapshot)
- mock_gtsv.assert_called_once_with("child", "raw_child", "checkbox")
+ mock_gtsv.assert_called_once_with(
+ "parent.child", "raw_child", "checkbox"
+ )
assert result == {"child": "typed_child"}
def test_no_partial_prefix_confusion(self, clean_thread_local):
diff --git a/tests/embeddings/test_embedding_request_timeout.py b/tests/embeddings/test_embedding_request_timeout.py
index afcf3c8a00..d45394ebc0 100644
--- a/tests/embeddings/test_embedding_request_timeout.py
+++ b/tests/embeddings/test_embedding_request_timeout.py
@@ -22,6 +22,7 @@ from local_deep_research.embeddings.providers.implementations.openai import (
from local_deep_research.llm.providers._helpers import (
MODEL_DISCOVERY_TIMEOUT_SECONDS,
)
+from local_deep_research.settings.exceptions import SettingsValueError
_OLLAMA_MODULE = (
"local_deep_research.embeddings.providers.implementations.ollama"
@@ -52,9 +53,9 @@ def _side_effect(values):
class TestOllamaEmbeddingsTimeout:
@pytest.mark.parametrize(
("configured", "expected"),
- # (None -> the default; 0 -> clamped up to the 1s floor; 10**9 ->
- # honoured, since the upper bound was removed deliberately.)
- [(None, 1800.0), (37, 37.0), (0, 1.0), (10**9, 1.0e9)],
+ # Missing uses the default; the 1s floor is valid; 10**9 is
+ # honoured, since the upper bound was removed deliberately.
+ [(None, 1800.0), (1, 1.0), (37, 37.0), (10**9, 1.0e9)],
)
def test_client_kwargs_carry_a_bounded_timeout(self, configured, expected):
# Given
@@ -85,6 +86,27 @@ class TestOllamaEmbeddingsTimeout:
# is a behaviour change and must break a test, not ride along.
assert timeout.connect == min(5.0, expected)
+ def test_zero_timeout_is_rejected_before_client_construction(self):
+ values = _settings({"llm.request_timeout": 0})
+
+ with patch(
+ f"{_OLLAMA_MODULE}.get_setting_from_snapshot",
+ side_effect=_side_effect(values),
+ ):
+ with patch(
+ f"{_OLLAMA_MODULE}.get_ollama_base_url",
+ return_value="http://localhost:11434",
+ ):
+ with patch(f"{_OLLAMA_MODULE}.OllamaEmbeddings") as mock_cls:
+ with pytest.raises(SettingsValueError) as raised:
+ OllamaEmbeddingsProvider.create_embeddings(
+ settings_snapshot=values
+ )
+
+ assert raised.value.key == "llm.request_timeout"
+ assert raised.value.source == "snapshot"
+ mock_cls.assert_not_called()
+
class TestOpenAIEmbeddingsTimeout:
def test_request_timeout_and_retries_are_bounded(self):
diff --git a/tests/js/components/settings-load-error-display.test.js b/tests/js/components/settings-load-error-display.test.js
new file mode 100644
index 0000000000..1a452dcf95
--- /dev/null
+++ b/tests/js/components/settings-load-error-display.test.js
@@ -0,0 +1,66 @@
+/**
+ * A failed settings load must leave the server's message on screen.
+ *
+ * For an invalid configured setting, GET /settings/api answers 500 with a
+ * diagnostic naming the key, its source and the reason. The settings page
+ * is where the user goes to repair it, so the message must replace the
+ * "Loading settings..." spinner instead of being dropped because the toast
+ * service is loaded.
+ */
+
+import RealDOMPurify from 'dompurify';
+
+import '@js/config/urls.js';
+import '@js/services/api.js';
+import '@js/utils/alert-helpers.js';
+import '@js/utils/provider-options.js';
+import '@js/utils/value-helpers.js';
+import '@js/security/xss-protection.js';
+import '@js/services/ui.js';
+
+const DIAGNOSTIC = (
+ "Invalid setting 'llm.<img src=x onerror=alert(1)>' from value: "
+ + 'expected a valid number value'
+);
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ delete globalThis.DOMPurify;
+});
+
+describe('settings load failure', () => {
+ it('replaces the loading spinner with the diagnostic as text', async () => {
+ vi.useFakeTimers();
+ globalThis.DOMPurify = RealDOMPurify;
+ document.body.innerHTML = `
+ <form id="settings-form">
+ <div id="settings-alert" style="display:none"></div>
+ <div id="settings-content"><p>Loading settings...</p></div>
+ </form>
+ `;
+ vi.stubGlobal('fetch', vi.fn(url => {
+ if (url === URLS.SETTINGS_API.BASE) {
+ return Promise.resolve(new Response(
+ JSON.stringify({ error: DIAGNOSTIC }),
+ { status: 500, statusText: 'Internal Server Error' },
+ ));
+ }
+ return Promise.resolve(new Response('{}', { status: 200 }));
+ }));
+ expect(typeof window.ui.showMessage).toBe('function');
+
+ await import('@js/components/settings.js');
+ await vi.advanceTimersByTimeAsync(151);
+
+ const content = document.getElementById('settings-content');
+ expect(content.textContent).toBe(`Error loading settings: ${DIAGNOSTIC}`);
+ expect(content.querySelector('img')).toBeNull();
+
+ const alert = document.getElementById('settings-alert');
+ expect(alert.textContent).toContain(DIAGNOSTIC);
+ expect(alert.querySelector('img')).toBeNull();
+ expect(alert.style.display).toBe('block');
+ });
+});
diff --git a/tests/llm_providers/test_request_timeout.py b/tests/llm_providers/test_request_timeout.py
index c69ad5e493..419bdb3329 100644
--- a/tests/llm_providers/test_request_timeout.py
+++ b/tests/llm_providers/test_request_timeout.py
@@ -41,6 +41,7 @@ from local_deep_research.llm.providers.implementations.lmstudio import (
from local_deep_research.llm.providers.implementations.openai import (
OpenAIProvider,
)
+from local_deep_research.settings.exceptions import SettingsValueError
_OPENAI_COMPATIBLE_CHAT_PATCH = (
@@ -135,31 +136,12 @@ class TestRequestTimeoutResolution:
assert timeout == 1800
assert isinstance(timeout, float)
- @pytest.mark.parametrize(
- ("configured_timeout", "expected"),
- [
- (0, 1.0),
- (-5, 1.0),
- (Fraction(1) - Fraction(1, 2**54), 1.0),
- ],
- )
- def test_clamps_out_of_range_values_instead_of_raising(
- self, configured_timeout, expected
- ):
- """An operator typo must not be a self-inflicted LLM outage.
-
- Before the clamp, every one of these raised ``ValueError`` out of
- each provider's ``create_llm``, so a single bad field killed all
- LLM construction until it was corrected.
- """
- # Given
+ @pytest.mark.parametrize("configured_timeout", [0, -5, Fraction(1, 2)])
+ def test_rejects_out_of_range_values(self, configured_timeout):
snapshot = {"llm.request_timeout": configured_timeout}
- # When
- timeout = resolve_request_timeout(snapshot)
-
- # Then
- assert timeout == expected
+ with pytest.raises(SettingsValueError, match="llm.request_timeout"):
+ resolve_request_timeout(snapshot)
@pytest.mark.parametrize(
"configured_timeout", [1801, 10**9, Fraction(1800) + Fraction(1, 2**40)]
@@ -193,18 +175,21 @@ class TestRequestTimeoutResolution:
[30],
],
)
- def test_falls_back_to_the_default_for_unusable_shapes(
- self, configured_timeout
- ):
- """Every other reader on the construction path degrades; so does this."""
- # Given
+ def test_rejects_unusable_shapes(self, configured_timeout):
snapshot = {"llm.request_timeout": configured_timeout}
- # When
- timeout = resolve_request_timeout(snapshot)
+ with pytest.raises(SettingsValueError, match="llm.request_timeout"):
+ resolve_request_timeout(snapshot)
- # Then
- assert timeout == 1800.0
+ def test_invalid_value_is_not_exposed_in_the_error_or_its_context(self):
+ configured_timeout = "credential-looking-invalid-value"
+
+ with pytest.raises(SettingsValueError) as caught:
+ resolve_request_timeout({"llm.request_timeout": configured_timeout})
+
+ assert configured_timeout not in str(caught.value)
+ assert caught.value.__context__ is None
+ assert caught.value.__cause__ is None
def test_full_format_snapshot_without_ui_element_still_resolves(self):
"""A full-format entry lacking ``ui_element`` resolves to ``"60"``.
@@ -221,19 +206,13 @@ class TestRequestTimeoutResolution:
# Then
assert timeout == 60.0
- def test_full_format_snapshot_with_a_boolean_number_value_uses_default(
- self,
- ):
- # Given — the number parser would coerce ``True`` to ``1``
+ def test_full_format_snapshot_rejects_a_boolean_number_value(self):
snapshot = {
"llm.request_timeout": {"value": True, "ui_element": "number"}
}
- # When
- timeout = resolve_request_timeout(snapshot)
-
- # Then
- assert timeout == 1800.0
+ with pytest.raises(SettingsValueError, match="llm.request_timeout"):
+ resolve_request_timeout(snapshot)
class TestMaxRetriesResolution:
@@ -245,11 +224,7 @@ class TestMaxRetriesResolution:
({"llm.max_retries": 0}, 0),
({"llm.max_retries": 4}, 4),
({"llm.max_retries": "3"}, 3),
- # Out of range: a user setting 1000 must not get 1000 attempts.
- ({"llm.max_retries": 1000}, 5),
- ({"llm.max_retries": -1}, 0),
- ({"llm.max_retries": True}, 2),
- ({"llm.max_retries": "nope"}, 2),
+ ({"llm.max_retries": 5}, 5),
],
)
def test_resolves_within_bounds(self, snapshot, expected):
@@ -260,6 +235,14 @@ class TestMaxRetriesResolution:
assert retries == expected
assert isinstance(retries, int)
+ @pytest.mark.parametrize(
+ "configured_retries",
+ [1000, -1, True, "nope", float("nan"), float("inf")],
+ )
+ def test_rejects_invalid_configured_retries(self, configured_retries):
+ with pytest.raises(SettingsValueError, match="llm.max_retries"):
+ resolve_max_retries({"llm.max_retries": configured_retries})
+
class TestOllamaClientKwargs:
"""``llm.request_timeout`` and auth headers flow via client_kwargs."""
@@ -382,29 +365,14 @@ class TestRequestTimeoutConstructorWiring:
({"llm.request_timeout": 37}, 37),
({}, 1800),
({"llm.request_timeout": None}, 1800),
- # Below the floor: clamped, never raised.
- ({"llm.request_timeout": 0}, 1),
# Above the old ceiling: honoured, no longer clamped.
({"llm.request_timeout": 10**9}, 10**9),
- # The UI number parser runs before timeout clamping. Its
- # conversion overflow must default and still construct clients.
- (
- {
- "llm.request_timeout": {
- "value": 10**400,
- "ui_element": "number",
- }
- },
- 1800,
- ),
),
ids=(
"configured",
"missing",
"explicit-none",
- "too-low",
"very-high",
- "full-format-overflow",
),
)
@pytest.mark.parametrize(
@@ -468,13 +436,9 @@ class TestRequestTimeoutConstructorWiring:
(
({}, 2),
({"llm.max_retries": 0}, 0),
- ({"llm.max_retries": 1000}, 5),
- (
- {"llm.max_retries": {"value": 10**400, "ui_element": "number"}},
- 2,
- ),
+ ({"llm.max_retries": 5}, 5),
),
- ids=("default", "disabled", "clamped", "full-format-overflow"),
+ ids=("default", "disabled", "maximum"),
)
@pytest.mark.parametrize(
("provider", "chat_patch"),
@@ -513,6 +477,25 @@ class TestRequestTimeoutConstructorWiring:
# Then
assert mock_chat.call_args.kwargs["max_retries"] == expected_retries
+ @pytest.mark.parametrize(
+ "invalid_timeout",
+ [
+ 0,
+ True,
+ "not-a-number",
+ float("inf"),
+ {"value": True, "ui_element": "number"},
+ {"value": 10**400, "ui_element": "number"},
+ ],
+ ids=(
+ "below-minimum",
+ "bool",
+ "text",
+ "nonfinite",
+ "full-bool",
+ "full-overflow",
+ ),
+ )
@pytest.mark.parametrize(
("provider", "chat_patch"),
_CONSTRUCTOR_CASES,
@@ -526,32 +509,48 @@ class TestRequestTimeoutConstructorWiring:
"ollama",
),
)
- def test_an_unusable_timeout_never_blocks_client_construction(
- self, provider, chat_patch
+ def test_an_invalid_timeout_blocks_client_construction(
+ self, provider, chat_patch, invalid_timeout
):
- """A bad value must degrade to the default, not raise."""
- # Given
snapshot = {
**_PROVIDER_SETTINGS[provider],
"llm.supports_max_tokens": False,
- "llm.request_timeout": True,
+ "llm.request_timeout": invalid_timeout,
}
- # When
with patch(chat_patch) as mock_chat:
- provider.create_llm(
- model_name="test-model", settings_snapshot=snapshot
- )
+ with pytest.raises(SettingsValueError, match="llm.request_timeout"):
+ provider.create_llm(
+ model_name="test-model", settings_snapshot=snapshot
+ )
- # Then
- mock_chat.assert_called_once()
- kwargs = mock_chat.call_args.kwargs
- if provider is OllamaProvider:
- assert kwargs["client_kwargs"]["timeout"].read == 1800
- elif issubclass(provider, AnthropicProvider):
- assert kwargs["timeout"] == 1800
- else:
- assert kwargs["request_timeout"] == (5.0, 1800, 1800, 1800)
+ mock_chat.assert_not_called()
+
+ @pytest.mark.parametrize(
+ "invalid_retries",
+ [1000, True, {"value": 10**400, "ui_element": "number"}],
+ ids=("above-maximum", "bool", "full-overflow"),
+ )
+ @pytest.mark.parametrize(
+ ("provider", "chat_patch"),
+ [case for case in _CONSTRUCTOR_CASES if case[0] is not OllamaProvider],
+ )
+ def test_invalid_retries_block_client_construction(
+ self, provider, chat_patch, invalid_retries
+ ):
+ snapshot = {
+ **_PROVIDER_SETTINGS[provider],
+ "llm.supports_max_tokens": False,
+ "llm.max_retries": invalid_retries,
+ }
+
+ with patch(chat_patch) as mock_chat:
+ with pytest.raises(SettingsValueError, match="llm.max_retries"):
+ provider.create_llm(
+ model_name="test-model", settings_snapshot=snapshot
+ )
+
+ mock_chat.assert_not_called()
class TestOpenAIHttpxClientSharing:
diff --git a/tests/llm_providers/test_request_timeout_behavior.py b/tests/llm_providers/test_request_timeout_behavior.py
index 12d41d725e..30620a4b8f 100644
--- a/tests/llm_providers/test_request_timeout_behavior.py
+++ b/tests/llm_providers/test_request_timeout_behavior.py
@@ -27,6 +27,7 @@ from openai import APITimeoutError
from local_deep_research.llm.providers.implementations.custom_openai_endpoint import (
CustomOpenAIEndpointProvider,
)
+from local_deep_research.settings.exceptions import SettingsValueError
_COMPLETION_BODY = json.dumps(
{
@@ -177,20 +178,17 @@ class TestSilentServer:
assert len(slow_server.attempts) == 3
assert retried > baseline * 2, (baseline, retried)
- def test_an_out_of_range_timeout_is_clamped_rather_than_fatal(
- self, slow_server
+ @pytest.mark.parametrize(
+ ("timeout", "retries", "invalid_key"),
+ [(0, 0, "llm.request_timeout"), (1, 1000, "llm.max_retries")],
+ )
+ def test_invalid_settings_prevent_client_construction_and_requests(
+ self, slow_server, timeout, retries, invalid_key
):
- """``0`` used to raise ValueError out of every create_llm call."""
- # Given
- slow_server.mode = "silent"
- llm = _make_llm(slow_server, timeout=0, retries=0)
+ with pytest.raises(SettingsValueError, match=invalid_key):
+ _make_llm(slow_server, timeout=timeout, retries=retries)
- # When
- elapsed = _elapsed_failure(llm)
-
- # Then — clamped up to the 1s minimum, not an outage
- assert len(slow_server.attempts) == 1
- assert elapsed < 3.0, elapsed
+ assert slow_server.attempts == []
class TestResponseBodyPacing:
diff --git a/tests/llm_providers/test_settings_error_propagation.py b/tests/llm_providers/test_settings_error_propagation.py
new file mode 100644
index 0000000000..7785d123dc
--- /dev/null
+++ b/tests/llm_providers/test_settings_error_propagation.py
@@ -0,0 +1,142 @@
+"""Invalid provider settings must not select anonymous or fallback behavior."""
+
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.llm.providers.implementations.custom_anthropic_endpoint import (
+ CustomAnthropicEndpointProvider,
+)
+from local_deep_research.llm.providers.implementations.custom_openai_endpoint import (
+ CustomOpenAIEndpointProvider,
+)
+from local_deep_research.llm.providers.implementations.llamacpp import (
+ LlamaCppProvider,
+)
+from local_deep_research.llm.providers.implementations.lmstudio import (
+ LMStudioProvider,
+)
+from local_deep_research.llm.providers.implementations.ollama import (
+ OllamaProvider,
+)
+from local_deep_research.llm.providers.implementations.openai import (
+ OpenAIProvider,
+)
+from local_deep_research.settings.exceptions import SettingsValueError
+
+
+def _invalid_number_entry():
+ return {"value": "not-a-number", "ui_element": "number"}
+
+
[email protected]("provider", [OllamaProvider, OpenAIProvider])
[email protected]("method", ["build_bearer_header", "has_api_key"])
+def test_invalid_credentials_are_not_treated_as_missing(provider, method):
+ snapshot = {provider.api_key_setting: _invalid_number_entry()}
+
+ with pytest.raises(SettingsValueError, match=provider.api_key_setting):
+ getattr(provider, method)(snapshot)
+
+
+def _ollama_snapshot():
+ return {
+ "llm.ollama.url": "http://localhost:11434",
+ "llm.local_context_window_size": 8192,
+ "llm.supports_max_tokens": False,
+ "llm.ollama.api_key": _invalid_number_entry(),
+ }
+
+
+def test_invalid_ollama_credentials_prevent_anonymous_client_construction():
+ with patch(
+ "local_deep_research.llm.providers.implementations.ollama.ChatOllama"
+ ) as constructor:
+ with pytest.raises(SettingsValueError, match="llm.ollama.api_key"):
+ OllamaProvider.create_llm(
+ model_name="test-model", settings_snapshot=_ollama_snapshot()
+ )
+
+ constructor.assert_not_called()
+
+
+def test_invalid_ollama_credentials_prevent_availability_request():
+ with patch(
+ "local_deep_research.llm.providers.implementations.ollama.safe_get"
+ ) as request:
+ with pytest.raises(SettingsValueError, match="llm.ollama.api_key"):
+ OllamaProvider.is_available(_ollama_snapshot())
+
+ request.assert_not_called()
+
+
+ "provider", [CustomAnthropicEndpointProvider, CustomOpenAIEndpointProvider]
+)
[email protected]("invalid_field", ["api_key_setting", "url_setting"])
+def test_custom_endpoint_availability_does_not_replace_invalid_settings(
+ provider,
+ invalid_field,
+):
+ invalid_key = getattr(provider, invalid_field)
+ snapshot = {
+ provider.api_key_setting: None,
+ provider.url_setting: "http://localhost:9090",
+ invalid_key: _invalid_number_entry(),
+ }
+
+ with pytest.raises(SettingsValueError, match=invalid_key):
+ provider.is_available(snapshot)
+
+
[email protected]("provider", [LMStudioProvider, LlamaCppProvider])
[email protected]("invalid_field", ["api_key_setting", "url_setting"])
+def test_local_provider_availability_does_not_hide_invalid_settings(
+ provider,
+ invalid_field,
+):
+ invalid_key = getattr(provider, invalid_field)
+ snapshot = {
+ provider.api_key_setting: None,
+ provider.url_setting: "http://localhost:9090/v1",
+ invalid_key: _invalid_number_entry(),
+ }
+
+ with patch("local_deep_research.security.safe_get") as request:
+ with pytest.raises(SettingsValueError, match=invalid_key):
+ provider.is_available(snapshot)
+
+ request.assert_not_called()
+
+
+def test_get_llm_propagates_invalid_settings_from_registered_provider(
+ monkeypatch,
+):
+ from local_deep_research.config import llm_config
+ from local_deep_research.security.egress import policy
+ from types import SimpleNamespace
+
+ monkeypatch.setattr(llm_config, "is_llm_registered", lambda *a, **k: True)
+ monkeypatch.setattr(
+ llm_config,
+ "get_llm_from_registry",
+ lambda *a, **k: OllamaProvider.create_llm,
+ )
+ monkeypatch.setattr(
+ policy, "resolve_run_primary_engine", lambda *a, **k: "test-primary"
+ )
+ monkeypatch.setattr(
+ policy,
+ "context_from_snapshot",
+ lambda *a, **k: SimpleNamespace(require_local_llm=False),
+ )
+ with patch(
+ "local_deep_research.llm.providers.implementations.ollama.ChatOllama"
+ ) as constructor:
+ with pytest.raises(SettingsValueError, match="llm.ollama.api_key"):
+ llm_config.get_llm(
+ provider="ollama",
+ model_name="test-model",
+ settings_snapshot=_ollama_snapshot(),
+ )
+
+ constructor.assert_not_called()
diff --git a/tests/news/test_scheduler_invalid_settings.py b/tests/news/test_scheduler_invalid_settings.py
new file mode 100644
index 0000000000..a9c4786536
--- /dev/null
+++ b/tests/news/test_scheduler_invalid_settings.py
@@ -0,0 +1,88 @@
+"""Invalid scheduler configuration must stop startup without default jobs."""
+
+import os
+from unittest.mock import Mock
+
+import pytest
+
+from local_deep_research.scheduler.background import BackgroundJobScheduler
+from local_deep_research.settings.exceptions import SettingsValueError
+from local_deep_research.settings.manager import SettingsManager
+
+
+def scheduler_configuration(monkeypatch):
+ for name in list(os.environ):
+ if name.startswith("LDR_NEWS_SCHEDULER_"):
+ monkeypatch.delenv(name)
+ monkeypatch.setenv("LDR_NEWS_SCHEDULER_ENABLED", "true")
+ monkeypatch.setenv("LDR_NEWS_SCHEDULER_RETENTION_HOURS", "72")
+ monkeypatch.setenv("LDR_NEWS_SCHEDULER_CLEANUP_INTERVAL_HOURS", "24")
+ manager = SettingsManager(seed_defaults=False)
+ # Keep the real initializer/start/readers while avoiding the global
+ # singleton and replacing only the backend that starts threads/jobs.
+ scheduler = object.__new__(BackgroundJobScheduler)
+ scheduler.config = scheduler._load_default_config()
+ scheduler.scheduler = Mock()
+ scheduler.is_running = False
+ try:
+ yield scheduler, manager
+ finally:
+ manager.close()
+
+
+ "setting",
+ ["retention_hours", "activity_check_interval", "cleanup_interval_hours"],
+)
+def test_invalid_configuration_stops_before_start(
+ scheduler_configuration, monkeypatch, setting
+):
+ scheduler, manager = scheduler_configuration
+ monkeypatch.setenv(
+ f"LDR_NEWS_SCHEDULER_{setting.upper()}", "invalid-number"
+ )
+
+ # This is the startup sequence in FastAPI's lifespan: an initialization
+ # error must escape so its outer error handler never reaches start().
+ with pytest.raises(SettingsValueError) as raised:
+ scheduler.initialize_with_settings(manager)
+ scheduler.start()
+
+ assert raised.value.key == f"news.scheduler.{setting}"
+ assert raised.value.source == "environment"
+ assert scheduler.is_running is False
+ scheduler.scheduler.start.assert_not_called()
+ scheduler.scheduler.add_job.assert_not_called()
+
+
+def test_valid_configuration_starts_with_the_selected_cleanup_interval(
+ scheduler_configuration,
+):
+ scheduler, manager = scheduler_configuration
+
+ scheduler.initialize_with_settings(manager)
+ scheduler.start()
+
+ scheduler.scheduler.start.assert_called_once()
+ cleanup = next(
+ call
+ for call in scheduler.scheduler.add_job.call_args_list
+ if call.kwargs.get("id") == "cleanup_inactive_users"
+ )
+ assert cleanup.kwargs["hours"] == 24
+ assert scheduler.config["retention_hours"] == 72
+ assert scheduler.is_running is True
+
+
+def test_disabled_scheduler_does_not_start(
+ scheduler_configuration, monkeypatch
+):
+ scheduler, manager = scheduler_configuration
+ monkeypatch.setenv("LDR_NEWS_SCHEDULER_ENABLED", "false")
+
+ scheduler.initialize_with_settings(manager)
+ scheduler.start()
+
+ scheduler.scheduler.start.assert_not_called()
+ scheduler.scheduler.add_job.assert_not_called()
diff --git a/tests/rate_limiting/test_rate_limiting.py b/tests/rate_limiting/test_rate_limiting.py
index 5b4c853ef4..2c77133934 100644
--- a/tests/rate_limiting/test_rate_limiting.py
+++ b/tests/rate_limiting/test_rate_limiting.py
@@ -393,11 +393,11 @@ class TestAdaptiveRateLimitTrackerProfiles(unittest.TestCase):
},
"rate_limiting.exploration_rate": {
"value": 0.1,
- "ui_element": "slider",
+ "ui_element": "range",
},
"rate_limiting.learning_rate": {
"value": 0.3,
- "ui_element": "slider",
+ "ui_element": "range",
},
}
tracker = AdaptiveRateLimitTracker(
@@ -419,11 +419,11 @@ class TestAdaptiveRateLimitTrackerProfiles(unittest.TestCase):
},
"rate_limiting.exploration_rate": {
"value": 0.1,
- "ui_element": "slider",
+ "ui_element": "range",
},
"rate_limiting.learning_rate": {
"value": 0.3,
- "ui_element": "slider",
+ "ui_element": "range",
},
}
tracker = AdaptiveRateLimitTracker(
@@ -444,21 +444,21 @@ class TestAdaptiveRateLimitTrackerProfiles(unittest.TestCase):
"ui_element": "select",
},
"rate_limiting.exploration_rate": {
- "value": 0.1,
- "ui_element": "slider",
+ "value": 0.05,
+ "ui_element": "range",
},
"rate_limiting.learning_rate": {
- "value": 0.3,
- "ui_element": "slider",
+ "value": 0.2,
+ "ui_element": "range",
},
}
tracker = AdaptiveRateLimitTracker(
settings_snapshot=settings_snapshot, programmatic_mode=True
)
- # Balanced profile should use configured rates
- self.assertEqual(tracker.exploration_rate, 0.1)
- self.assertEqual(tracker.learning_rate, 0.3)
+ # Distinct from tracker defaults: the snapshot must drive both rates.
+ self.assertEqual(tracker.exploration_rate, 0.05)
+ self.assertEqual(tracker.learning_rate, 0.2)
class TestApplyRateLimit(unittest.TestCase):
diff --git a/tests/search_engines/conftest.py b/tests/search_engines/conftest.py
index a4e8a5d3a5..6fd35f7a8f 100644
--- a/tests/search_engines/conftest.py
+++ b/tests/search_engines/conftest.py
@@ -13,7 +13,7 @@ def mock_settings_snapshot():
"rate_limiting.enabled": {"value": True, "ui_element": "checkbox"},
"rate_limiting.profile": {
"value": "balanced",
- "ui_element": "dropdown",
+ "ui_element": "select",
},
"rate_limiting.memory_window": {"value": 100, "ui_element": "number"},
"rate_limiting.exploration_rate": {
diff --git a/tests/search_engines/test_rate_limiter.py b/tests/search_engines/test_rate_limiter.py
index c40b661bd4..2f0394d465 100644
--- a/tests/search_engines/test_rate_limiter.py
+++ b/tests/search_engines/test_rate_limiter.py
@@ -37,12 +37,18 @@ class TestAdaptiveRateLimitTrackerInit:
assert tracker.programmatic_mode is True
def test_init_with_settings_snapshot(self, mock_settings_snapshot):
- """Initializes with settings snapshot."""
+ """Initializes and applies the profile from a typed settings snapshot."""
+ mock_settings_snapshot["rate_limiting.profile"]["value"] = (
+ "conservative"
+ )
tracker = AdaptiveRateLimitTracker(
settings_snapshot=mock_settings_snapshot,
programmatic_mode=True,
)
assert tracker.settings_snapshot == mock_settings_snapshot
+ assert tracker.enabled is True
+ assert tracker.exploration_rate == 0.05
+ assert tracker.learning_rate == 0.2
def test_init_empty_caches(self):
"""Initializes with empty caches."""
diff --git a/tests/security/test_egress_unprotected_ui_gate.py b/tests/security/test_egress_unprotected_ui_gate.py
index 39cff87f83..b1aa778d79 100644
--- a/tests/security/test_egress_unprotected_ui_gate.py
+++ b/tests/security/test_egress_unprotected_ui_gate.py
@@ -220,7 +220,7 @@ class TestSaveAllSettingsEchoGate:
monkeypatch.delenv(ENV_VAR, raising=False)
_, db_patch = _patched_db(existing_settings=[self._egress_row()])
- settings_manager = Mock(settings_locked=False)
+ settings_manager = Mock(settings_locked=False, default_settings={})
created = Mock()
created.type = "LLM"
with (
diff --git a/tests/security/test_settings_egress_and_secrets_fastapi.py b/tests/security/test_settings_egress_and_secrets_fastapi.py
index 345326704b..24117026f6 100644
--- a/tests/security/test_settings_egress_and_secrets_fastapi.py
+++ b/tests/security/test_settings_egress_and_secrets_fastapi.py
@@ -2148,62 +2148,30 @@ class TestBulkSecretWriteBackAndEcho:
def test_reconciled_container_on_a_number_row_is_never_logged(
self, settings_user
):
- """Round-5 defect (1), second half: the ``validate_setting`` skip had
- NO test at ANY of the three call sites, even though its stated
- rationale is a secret DISCLOSURE channel.
-
- A dict/list value can sit on a ``number`` row -- ``ui_element`` is
- caller-supplied metadata on a new key and is never reconciled
- against the value's actual shape. Feeding a merged container to
- ``validate_setting`` there reaches ``get_typed_setting_value``'s
- bare ``float(value)``, which raises ``TypeError``; the row is then
- rejected ("Value must be a number") and the legitimate edit is
- lost.
-
- SCOPE CORRECTION (round 6). This test was originally written as a
- LEAK test: the ``TypeError`` handler used to log ``"Setting {key}
- has invalid value {value}"`` at WARNING -- the whole container,
- secret leaf included -- so reverting either skip disclosed the
- restored secret to the log. It went red anyway, because the leak
- was never confined to the two write-back call sites this test
- reverts: ``PUT /settings/api/<key>`` commits and then emits a
- settings-changed event, whose ``get_setting(key)`` reaches the
- same converter with the same container AFTER both skips have
- already done their job. The fix was therefore made in the
- converter (``settings/manager.py``), which no longer logs a
- setting VALUE on any path; see
- ``test_typed_value_converter_never_logs_the_value_itself`` below,
- which pins that directly. The log assertions kept here are the
- END-TO-END form of the same property -- no secret reaches the log
- through ANY of the three write routes, whatever they call -- and
- they are what caught this in the first place.
-
- EXACT REVERTS THIS STILL CATCHES, at all three write routes:
- * dropping the ``validate_setting`` skip -- the container is
- rejected as "Value must be a number", so the PUT/bulk calls
- below stop returning 200/302 and the final ``stored ==``
- assertion loses the edit; and
- * reinstating the setting value in either of the converter's
- two WARNING lines -- the leak assertion below fires again.
-
- What this test does NOT catch, and where that coverage lives: a
- coercion-only revert on a NUMERIC row is invisible here.
- ``coerce_setting_for_write`` returns the submitted value unchanged
- when a numeric conversion fails (see its ``numeric_ui and coerced
- is None`` branch), so the stored row is identical either way, and
- the converter no longer logs anything incriminating. The coercion
- skip is pinned instead by the four
- ``..._is_not_coerced_to_str`` / ``..._does_not_leak`` tests above,
- on "text"/"textarea" rows -- the shape where coercion actually
- does damage, because ``str()`` flattens the merged container to a
- Python repr carrying the restored secret in the clear.
-
- The POSITIVE CONTROL is not optional: the package disables its own
- loguru namespace at import, so "no secret in the captured lines"
- would pass even if nothing was ever captured. The control asserts a
- known router WARNING from the same routes, in the same capture
- block, did arrive.
+ """Legacy containers retain secrets across guarded writes and errors.
+
+ Custom row creation used to persist a dict under numeric UI
+ metadata. It now refuses that row, because every strict read would
+ reject it, but a database written by an older release can still
+ hold one. The strict effective reader must reject that invalid
+ schema/value combination, while the existing secret reconciliation
+ write paths must preserve the stored container and its masked
+ leaves. A failed read must not flatten it, substitute a default, or
+ reveal it in a response, converter exception, or post-commit
+ notification log.
+
+ The three write routes deliberately retain their existing guarded
+ merge behavior. Text/textarea tests above cover the separate hazard
+ of coercing a reconciled container into a secret-bearing repr.
"""
+ from local_deep_research.database.models.settings import (
+ Setting,
+ SettingType,
+ )
+ from local_deep_research.database.session_context import (
+ get_user_db_session,
+ )
+
client, username, password = settings_user
suffix = uuid.uuid4().hex[:6]
key = f"llm.probe_{suffix}.cfg"
@@ -2215,14 +2183,46 @@ class TestBulkSecretWriteBackAndEcho:
f"/settings/api/{key}",
json={"value": real_value, "ui_element": "number"},
)
- assert create.status_code == 201, create.text[:300]
- meta = client.get(f"/settings/api/{key}").json()
- # The premise: a container value on a NUMERIC row. `float()`
- # cannot convert it, which is the whole hazard.
- assert meta["ui_element"] == "number"
- assert meta["value"] == {"stop_token": REDACTED, "retries": 3}
+ assert create.status_code == 400, create.text[:300]
+ assert real_secret not in create.text
+ assert create.json() == {
+ "error": (
+ f"Invalid value for setting {key}: "
+ "expected a valid number value"
+ )
+ }
+ # Plant the legacy row an older release could create, then
+ # verify its shape directly: an effective GET is required to
+ # reject its invalid numeric value.
+ with get_user_db_session(username, password) as session:
+ session.add(
+ Setting(
+ key=key,
+ value=real_value,
+ type=SettingType.LLM,
+ name="Cfg",
+ ui_element="number",
+ )
+ )
+ session.commit()
+ with get_user_db_session(username, password) as session:
+ row = session.query(Setting).filter(Setting.key == key).one()
+ assert row.ui_element == "number"
+ assert row.value == real_value
with _captured_warnings() as lines:
+ rejected_read = client.get(f"/settings/api/{key}")
+ assert rejected_read.status_code == 500, rejected_read.text
+ # The repair diagnostic names the row, never its value.
+ assert rejected_read.json() == {
+ "error": (
+ f"Invalid setting {key!r} from value: "
+ "expected a valid number value"
+ )
+ }
+ assert real_secret not in rejected_read.text
+ assert _stored_value(username, password, key) == real_value
+
# A genuine edit through each of the three write routes in
# turn: `retries` changes, `stop_token` stays masked.
put_resp = client.put(
@@ -2230,6 +2230,7 @@ class TestBulkSecretWriteBackAndEcho:
json={"value": {"stop_token": REDACTED, "retries": 4}},
)
assert put_resp.status_code == 200, put_resp.text[:300]
+ assert real_secret not in put_resp.text
bulk_resp = client.post(
"/settings/save_all_settings",
@@ -2237,6 +2238,7 @@ class TestBulkSecretWriteBackAndEcho:
)
assert bulk_resp.status_code == 200, bulk_resp.text[:300]
assert key in bulk_resp.json()["updated"], bulk_resp.text[:300]
+ assert real_secret not in bulk_resp.text
form_resp = client.post(
"/settings/save_settings",
@@ -2265,6 +2267,11 @@ class TestBulkSecretWriteBackAndEcho:
"rejection WARNING for the control key never reached the "
f"sink (captured {len(lines)} line(s))"
)
+ # The invalid read reached the strict converter; an unrelated
+ # server error must not satisfy the expected failure above.
+ assert any(
+ f"Invalid setting {key!r} from value" in line for line in lines
+ ), lines
leaked = [line for line in lines if real_secret in line]
assert not leaked, (
"the restored secret was written to the log on a number "
@@ -2283,102 +2290,50 @@ class TestBulkSecretWriteBackAndEcho:
finally:
client.delete(f"/settings/api/{key}")
- def test_typed_value_converter_never_logs_the_value_itself(self):
- """Round-6 defect (1): the leak was in the CONVERTER, not at any one
- call site, and no route-level skip could close it.
-
- ``test_reconciled_container_on_a_number_row_is_never_logged`` above
- covers the three write routes. It still went red, because a FOURTH
- path reaches the same converter with the restored container and is
- not a write-back call site at all:
- ``PUT /settings/api/<key>`` calls ``set_setting(...)`` with no
- ``commit=`` argument, which defaults to ``commit=True``, so
- ``SettingsManager.set_setting`` commits and then calls
- ``_emit_settings_changed([key])`` -> ``get_setting(key)`` ->
- ``get_typed_setting_value``. On a ``number``/``range``/``slider``
- row holding a dict, ``_parse_number``'s bare ``float(value)``
- raises ``TypeError`` and the handler logged the whole container --
- restored secret included -- at WARNING. The bulk routes pass
- ``commit=False`` and never emit, which is why only the PUT path
- tripped it and only the leak assertion failed.
-
- Skipping the converter at a fourth call site would have been
- whack-a-mole: ``validate_imported_setting_value`` reaches it too,
- and so does any future reader. The fix is that
- ``get_typed_setting_value`` no longer logs a setting VALUE at all
- -- a settings value is, by this PR's own premise, a plausible
- secret carrier. This test pins the converter directly, so it fails
- if the value is ever reinstated in EITHER of that function's two
- warning lines, whichever route happens to reach it.
-
- EXACT REVERT THIS CATCHES: restoring ``key, value`` (or ``key,
- env_value``) as the interpolated arguments of either
- ``logger.warning("Setting {} has ... value {} ...")`` call in
- ``settings/manager.py``.
-
- The POSITIVE CONTROL is not optional here either: the package
- disables its own loguru namespace at import, so "no secret in the
- captured lines" would pass with nothing captured at all. The
- control is the diagnostic the line MUST still carry -- the key.
- """
- from local_deep_research.settings.manager import (
- get_typed_setting_value,
- )
+ def test_typed_value_converter_errors_do_not_expose_values(self):
+ """Both parser failure paths retain a key without retaining secrets."""
+ import traceback
+
+ from local_deep_research.settings.exceptions import SettingsValueError
+ from local_deep_research.settings.manager import get_typed_setting_value
key = "llm.probe_converter_unit.cfg"
db_secret = "s3cr3t-converter-db-7731"
env_secret = "s3cr3t-converter-env-7731"
with _captured_warnings() as lines:
- # (a) The DB arm: a container on a `number` row. `float(dict)`
- # raises TypeError -- the exact branch the failing CI job hit.
- db_result = get_typed_setting_value(
- key=key,
- value={"stop_token": db_secret, "retries": 4},
- ui_element="number",
- default=None,
- check_env=False,
- )
- # (b) The sibling arm, same function: an env override that
- # cannot be converted. `float(str)` raises ValueError and the
- # handler logged `env_value` -- an LDR_* override is where a
- # provider API key most often lives.
+ with pytest.raises(SettingsValueError) as db_error:
+ get_typed_setting_value(
+ key=key,
+ value={"stop_token": db_secret, "retries": 4},
+ ui_element="number",
+ default=10,
+ check_env=False,
+ )
with patch.dict(
"os.environ",
{"LDR_LLM_PROBE_CONVERTER_UNIT_CFG": env_secret},
):
- env_result = get_typed_setting_value(
- key=key,
- value=None,
- ui_element="number",
- default=None,
- check_env=True,
- )
-
- assert db_result is None
- assert env_result is None
-
- # POSITIVE CONTROL: both warnings reached the sink AND still name
- # the key, which is the diagnostic that must survive the fix.
- assert sum(1 for line in lines if key in line) >= 2, (
- "log capture is not wired up, or the converter's warnings no "
- "longer name the setting key (captured "
- f"{len(lines)} line(s)): {lines}"
- )
-
- for secret in (db_secret, env_secret):
- leaked = [line for line in lines if secret in line]
- assert not leaked, (
- "get_typed_setting_value wrote a setting value to the log: "
- f"{leaked[0][:300]}"
- )
- # Not even the container's structure: a sub-key name can itself be
- # the interesting half of a leak.
- assert not [line for line in lines if "stop_token" in line], lines
+ with pytest.raises(SettingsValueError) as env_error:
+ get_typed_setting_value(
+ key=key,
+ value=3,
+ ui_element="number",
+ default=10,
+ )
- # What the line must still say instead of the value: the type it
- # actually got, so a malformed row stays diagnosable.
- assert any("dict" in line for line in lines), lines
+ for caught, source in ((db_error, "value"), (env_error, "environment")):
+ error = caught.value
+ assert error.key == key
+ assert error.source == source
+ assert key in str(error)
+ assert error.__cause__ is None
+ assert error.__context__ is None
+ rendered = "".join(traceback.format_exception(error))
+ for secret in (db_secret, env_secret):
+ assert secret not in rendered
+ assert not any(secret in line for line in lines)
+ assert not any("stop_token" in line for line in lines)
def test_masked_list_edit_survives_javascript_number_normalization(
self, settings_user
diff --git a/tests/security/test_settings_secret_redaction_isolation.py b/tests/security/test_settings_secret_redaction_isolation.py
index 40b53fa8be..41084aba47 100644
--- a/tests/security/test_settings_secret_redaction_isolation.py
+++ b/tests/security/test_settings_secret_redaction_isolation.py
@@ -1260,14 +1260,18 @@ def test_sensitive_multiselect_bare_sentinel_roundtrip_stays_a_noop():
key, "multiselect", guard_value, stored
)
- # REGRESSION PROOF: the raw (un-guarded) coercion is exactly the
- # one-element-list mangling that used to reach the guards and cause
- # the false rejection.
+ # Strict parsing rejects the JSON-looking bare sentinel rather than
+ # interpreting it as CSV. Write coercion preserves rejected input for
+ # validation, so both paths must keep this no-op scalar unchanged.
raw_coerced = coerce_setting_for_write(
key=key, value=REDACTED, ui_element="multiselect"
)
- assert raw_coerced == [REDACTED]
- assert not _is_secret_empty_noop(key, "multiselect", raw_coerced, stored)
+ assert raw_coerced == REDACTED
+ assert _is_secret_empty_noop(key, "multiselect", raw_coerced, stored)
+
+ # The historical list-shaped input is still a different operation: it
+ # must not become a no-op over a three-element stored list.
+ assert not _is_secret_empty_noop(key, "multiselect", [REDACTED], stored)
def test_policy_audit_line_cannot_carry_a_credential():
@@ -1560,18 +1564,26 @@ def test_sensitive_multiselect_spliced_sentinel_is_rejected_not_merged():
key, "multiselect", guard_value, stored
)
- # REGRESSION PROOF: the raw (un-guarded) coercion is exactly the split
- # that used to reach the container arm, and the container arm then
- # merges it into a 200 that loses "tok-real-2".
+ # Strict parsing rejects JSON-looking input, so a leading sentinel
+ # is no longer split even by raw coercion. A trailing sentinel still
+ # looks like ordinary supported CSV: bypassing the guard really does
+ # split it and silently replace the first stored item. Keep that real
+ # negative control rather than relying on the old parser's fallback.
+ assert (
+ coerce_setting_for_write(
+ key=key, value=f"{REDACTED},new", ui_element="multiselect"
+ )
+ == f"{REDACTED},new"
+ )
raw_coerced = coerce_setting_for_write(
- key=key, value=f"{REDACTED},new", ui_element="multiselect"
+ key=key, value=f"new,{REDACTED}", ui_element="multiselect"
)
- assert raw_coerced == [REDACTED, "new"]
+ assert raw_coerced == ["new", REDACTED]
merged, is_noop, is_rejected = _resolve_container_secret_write(
raw_coerced, stored, REDACTED
)
assert (is_noop, is_rejected) == (False, False)
- assert merged == ["tok-real-1", "new"] # "tok-real-2" destroyed
+ assert merged == ["new", "tok-real-2"] # "tok-real-1" destroyed
# CONTROL: the BARE sentinel round-trip stays the 200 no-op the
# sibling test above pins -- this narrowing must not turn it into a
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 260a2a6031..81878eff40 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -1416,7 +1416,7 @@
},
"llm.max_retries": {
"category": "llm_parameters",
- "description": "Maximum provider SDK retries per failed inference or embedding request. Applies to OpenAI-compatible and Anthropic SDKs; the Ollama client does not retry. Values outside 0-5 are clamped. Each retry starts another request with its own per-operation timeouts; SDK backoff or server-requested retry delays can further extend elapsed time. This setting does not impose a total request deadline. Model discovery SDK retries are disabled.",
+ "description": "Maximum provider SDK retries per failed inference or embedding request. Applies to OpenAI-compatible and Anthropic SDKs; the Ollama client does not retry. Configured values must be finite numbers within 0-5; invalid values raise a settings error instead of being replaced. An absent or unset optional value uses the default. Each retry starts another request with its own per-operation timeouts; SDK backoff or server-requested retry delays can further extend elapsed time. This setting does not impose a total request deadline. Model discovery SDK retries are disabled.",
"editable": true,
"max_value": 5,
"min_value": 0,
@@ -1706,7 +1706,7 @@
},
"llm.request_timeout": {
"category": "llm_parameters",
- "description": "Per-operation HTTP timeout in seconds for LLM inference and embedding requests, applied to every supported provider. It bounds each connect, write and wait for the next response chunk individually; it is not a cap on the total duration of a response. A peer that keeps sending data can exceed this value, including for a non-streaming response. Connecting is separately capped at 5 seconds for OpenAI-compatible and Ollama clients; Anthropic inference uses this value for connecting too. There is no upper limit; values below 1 second are clamped to 1, and non-numeric or non-finite values use the default. Model discovery is unaffected: OpenAI-compatible providers and Anthropic use 30 seconds, while Google and Ollama retain provider-specific limits of 10 and 5 seconds, respectively.",
+ "description": "Per-operation HTTP timeout in seconds for LLM inference and embedding requests, applied to every supported provider. It bounds each connect, write and wait for the next response chunk individually; it is not a cap on the total duration of a response. A peer that keeps sending data can exceed this value, including for a non-streaming response. Connecting is separately capped at 5 seconds for OpenAI-compatible and Ollama clients; Anthropic inference uses this value for connecting too. There is no upper limit. Configured values must be finite numbers of at least 1 second; invalid values raise a settings error instead of being replaced. An absent or unset optional value uses the default. Model discovery is unaffected: OpenAI-compatible providers and Anthropic use 30 seconds, while Google and Ollama retain provider-specific limits of 10 and 5 seconds, respectively.",
"editable": true,
"max_value": null,
"min_value": 1,
diff --git a/tests/settings/test_discovery_settings_errors.py b/tests/settings/test_discovery_settings_errors.py
new file mode 100644
index 0000000000..76b5752b38
--- /dev/null
+++ b/tests/settings/test_discovery_settings_errors.py
@@ -0,0 +1,64 @@
+"""Invalid configuration must remain distinguishable from an unavailable API."""
+
+from unittest.mock import patch
+
+import pytest
+
+from local_deep_research.embeddings.providers.implementations.openai import (
+ OpenAIEmbeddingsProvider,
+)
+from local_deep_research.llm.providers.implementations.custom_openai_endpoint import (
+ CustomOpenAIEndpointProvider,
+)
+from local_deep_research.llm.providers.implementations.openai import (
+ OpenAIProvider,
+)
+from local_deep_research.settings.exceptions import SettingsValueError
+
+
[email protected]("invalid_field", ["api_key", "base_url"])
[email protected]("method", ["is_available", "get_available_models"])
+def test_embedding_discovery_reports_invalid_settings(invalid_field, method):
+ invalid_key = f"embeddings.openai.{invalid_field}"
+ snapshot = {
+ "embeddings.openai.api_key": None,
+ "embeddings.openai.base_url": "http://localhost:9090/v1",
+ invalid_key: {"value": "not-a-number", "ui_element": "number"},
+ }
+ with patch("openai.OpenAI") as client:
+ with pytest.raises(SettingsValueError) as raised:
+ getattr(OpenAIEmbeddingsProvider, method)(snapshot)
+ assert raised.value.key == invalid_key
+ client.assert_not_called()
+
+
+ "provider, invalid_field",
+ [
+ (OpenAIProvider, "api_key_setting"),
+ (CustomOpenAIEndpointProvider, "url_setting"),
+ ],
+)
+def test_llm_discovery_reports_invalid_settings(provider, invalid_field):
+ invalid_key = getattr(provider, invalid_field)
+ snapshot = {
+ provider.api_key_setting: "test-key",
+ provider.url_setting: "http://localhost:9090/v1",
+ invalid_key: {"value": "not-a-number", "ui_element": "number"},
+ }
+ with patch.object(provider, "list_models_for_api") as request:
+ with pytest.raises(SettingsValueError) as raised:
+ provider.list_models(snapshot)
+ assert raised.value.key == invalid_key
+ request.assert_not_called()
+
+
+def test_unconfigured_embedding_provider_remains_unavailable():
+ snapshot = {
+ "embeddings.openai.api_key": None,
+ "embeddings.openai.base_url": None,
+ }
+ with patch("openai.OpenAI") as client:
+ assert OpenAIEmbeddingsProvider.is_available(snapshot) is False
+ assert OpenAIEmbeddingsProvider.get_available_models(snapshot) == []
+ client.assert_not_called()
diff --git a/tests/settings/test_env_settings_strict.py b/tests/settings/test_env_settings_strict.py
new file mode 100644
index 0000000000..287de9ded9
--- /dev/null
+++ b/tests/settings/test_env_settings_strict.py
@@ -0,0 +1,340 @@
+"""Manager-facing environment reads reject invalid configured values."""
+
+import traceback
+
+import pytest
+
+from local_deep_research.settings.env_registry import (
+ registry as shipped_registry,
+)
+from local_deep_research.settings.env_settings import (
+ BooleanSetting,
+ EnumSetting,
+ EnvSetting,
+ IntegerSetting,
+ PathSetting,
+ SecretSetting,
+ SettingsRegistry,
+ StringSetting,
+)
+from local_deep_research.settings.exceptions import SettingsValueError
+
+
+def registry_with(setting):
+ registry = SettingsRegistry()
+ registry.register_category("strict", [setting])
+ return registry
+
+
+ "raw", ["not-an-integer", "1.5", "NaN", "inf", "0", "11"]
+)
+def test_invalid_integer_never_selects_another_value(monkeypatch, raw):
+ setting = IntegerSetting(
+ "strict.integer", "integer", default=5, min_value=1, max_value=10
+ )
+ registry = registry_with(setting)
+ monkeypatch.setenv(setting.env_var, raw)
+
+ with pytest.raises(SettingsValueError) as error:
+ registry.get_strict(setting.key, default=9)
+
+ assert error.value.key == setting.key
+ assert error.value.source == "environment"
+ assert error.value.__cause__ is None
+ assert error.value.__context__ is None
+
+
[email protected]("raw", ["", " \t"])
[email protected]("strict_digits", [False, True])
[email protected]("registered_default", [None, 5])
+def test_blank_integer_is_unset_for_managed_and_bootstrap_reads(
+ monkeypatch, raw, strict_digits, registered_default
+):
+ # Main's orchestrator compatibility applies to all integer readers,
+ # including settings that opt into trust-boundary validation.
+ setting = IntegerSetting(
+ "strict.integer",
+ "integer",
+ default=registered_default,
+ min_value=1,
+ max_value=10,
+ strict_digits=strict_digits,
+ raise_on_validation_error=True,
+ )
+ registry = registry_with(setting)
+ monkeypatch.setenv(setting.env_var, raw)
+
+ expected = registered_default if registered_default is not None else 9
+ assert setting.get_value() == registered_default
+ assert registry.get(setting.key, default=9) == expected
+ assert registry.get_strict(setting.key, default=9) == expected
+
+
+ "raw, expected", [("1", 1), ("10", 10), (" +05 ", 5), ("1_0", 10)]
+)
+def test_valid_integer_and_boundaries_keep_their_values(
+ monkeypatch, raw, expected
+):
+ setting = IntegerSetting(
+ "strict.integer", "integer", default=5, min_value=1, max_value=10
+ )
+ monkeypatch.setenv(setting.env_var, raw)
+ assert registry_with(setting).get_strict(setting.key) == expected
+
+
+ "raw, expected",
+ [
+ ("true", True),
+ (" TRUE ", True),
+ ("1", True),
+ ("yes", True),
+ ("on", True),
+ ("enabled", True),
+ ("false", False),
+ (" FALSE ", False),
+ ("0", False),
+ ("no", False),
+ ("off", False),
+ ("disabled", False),
+ ("", False),
+ ],
+)
+def test_explicit_boolean_tokens(monkeypatch, raw, expected):
+ setting = BooleanSetting("strict.boolean", "boolean", default=not expected)
+ monkeypatch.setenv(setting.env_var, raw)
+ assert registry_with(setting).get_strict(setting.key) is expected
+
+
[email protected]("raw", ["tru", "2", "not-false"])
+def test_unknown_boolean_is_an_error_instead_of_false(monkeypatch, raw):
+ setting = BooleanSetting("strict.boolean", "boolean", default=False)
+ monkeypatch.setenv(setting.env_var, raw)
+ with pytest.raises(SettingsValueError):
+ registry_with(setting).get_strict(setting.key, default=False)
+
+
[email protected]("raw", ["unexpected-sensitive-value", ""])
+def test_invalid_enum_does_not_disclose_value_or_return_default(
+ monkeypatch, raw
+):
+ setting = EnumSetting(
+ "strict.enum", "enum", {"WAL", "DELETE"}, default="WAL"
+ )
+ monkeypatch.setenv(setting.env_var, raw)
+ with pytest.raises(SettingsValueError) as error:
+ registry_with(setting).get_strict(setting.key, default="DELETE")
+
+ assert error.value.__context__ is None
+ assert "InvalidEnvironmentValueError" not in "".join(
+ traceback.format_exception(error.value)
+ )
+ if raw:
+ assert raw not in str(error.value)
+
+
+def test_case_insensitive_enum_keeps_canonical_value(monkeypatch):
+ setting = EnumSetting(
+ "strict.enum", "enum", {"WAL", "DELETE"}, default="DELETE"
+ )
+ monkeypatch.setenv(setting.env_var, "wAl")
+ assert registry_with(setting).get_strict(setting.key) == "WAL"
+
+
[email protected]("setting_type", [StringSetting, SecretSetting])
+def test_missing_required_setting_is_an_error(monkeypatch, setting_type):
+ setting = setting_type("strict.required", "required", required=True)
+ monkeypatch.delenv(setting.env_var, raising=False)
+ with pytest.raises(SettingsValueError) as error:
+ registry_with(setting).get_strict(setting.key, default="caller-default")
+ assert error.value.source == "default"
+
+
[email protected]("setting_type", [StringSetting, SecretSetting])
[email protected]("raw", ["", " keep whitespace "])
+def test_string_values_are_not_reinterpreted(monkeypatch, setting_type, raw):
+ setting = setting_type("strict.string", "string", default="registered")
+ monkeypatch.setenv(setting.env_var, raw)
+ assert registry_with(setting).get_strict(setting.key, "caller") == raw
+
+
+def test_legacy_alias_and_canonical_precedence(monkeypatch):
+ setting = IntegerSetting(
+ "strict.alias", "alias", default=5, deprecated_env_var="LDR_STRICT_OLD"
+ )
+ registry = registry_with(setting)
+ monkeypatch.delenv(setting.env_var, raising=False)
+ monkeypatch.setenv("LDR_STRICT_OLD", "7")
+ assert registry.get_strict(setting.key) == 7
+
+ monkeypatch.setenv(setting.env_var, "9")
+ assert registry.get_strict(setting.key) == 9
+
+ monkeypatch.setenv(setting.env_var, "invalid-canonical")
+ with pytest.raises(SettingsValueError):
+ registry.get_strict(setting.key, default=11)
+
+ assert registry.get_strict(setting.key, check_env=False) == 5
+
+
+def test_invalid_legacy_alias_is_not_replaced_by_a_default(monkeypatch):
+ setting = IntegerSetting(
+ "strict.alias", "alias", default=5, deprecated_env_var="LDR_STRICT_OLD"
+ )
+ monkeypatch.delenv(setting.env_var, raising=False)
+ monkeypatch.setenv("LDR_STRICT_OLD", "invalid-legacy")
+ with pytest.raises(SettingsValueError) as error:
+ registry_with(setting).get_strict(setting.key, default=9)
+ assert error.value.source == "environment"
+
+
[email protected]("raw", ["", " \t"])
+def test_blank_canonical_integer_does_not_select_deprecated_alias(
+ monkeypatch, raw
+):
+ setting = IntegerSetting(
+ "strict.alias", "alias", default=5, deprecated_env_var="LDR_STRICT_OLD"
+ )
+ registry = registry_with(setting)
+ monkeypatch.setenv("LDR_STRICT_OLD", "7")
+ monkeypatch.setenv(setting.env_var, raw)
+
+ assert registry.get_strict(setting.key, default=9) == 5
+ assert registry.get(setting.key, default=9) == 5
+ monkeypatch.delenv(setting.env_var)
+ assert registry.get_strict(setting.key, default=9) == 7
+
+
+def test_optional_and_unknown_missing_values_retain_defaults(monkeypatch):
+ setting = StringSetting("strict.optional", "optional")
+ monkeypatch.delenv(setting.env_var, raising=False)
+ registry = registry_with(setting)
+ sentinel = object()
+ assert registry.get_strict(setting.key) is None
+ assert registry.get_strict(setting.key, sentinel) is sentinel
+ assert registry.get_strict("strict.unknown", sentinel) is sentinel
+
+
+def test_all_shipped_defaults_work_without_reading_environment(monkeypatch):
+ sentinel = object()
+
+ def unexpected_lookup():
+ pytest.fail("check_env=False attempted to read the environment")
+
+ for key in shipped_registry.list_all_settings():
+ setting = shipped_registry.get_setting_object(key)
+ monkeypatch.setattr(setting, "_get_raw_value", unexpected_lookup)
+ expected = setting.default if setting.default is not None else sentinel
+ result = shipped_registry.get_strict(key, sentinel, check_env=False)
+ assert result == expected, key
+ assert type(result) is type(expected), key
+
+
+def test_path_is_not_created_or_read_when_environment_is_disabled(
+ monkeypatch, tmp_path
+):
+ target = tmp_path / "new-directory"
+ setting = PathSetting("strict.path", "path", create_if_missing=True)
+ registry = registry_with(setting)
+ monkeypatch.setenv(setting.env_var, str(target))
+
+ assert registry.get_strict(setting.key, check_env=False) is None
+ assert (
+ registry.get_strict(setting.key, "caller", check_env=False) == "caller"
+ )
+ assert not target.exists()
+
+ assert registry.get_strict(setting.key) == str(target)
+ assert target.is_dir()
+
+
+def test_path_expansion_is_preserved(monkeypatch, tmp_path):
+ setting = PathSetting("strict.path", "path", must_exist=True)
+ monkeypatch.setenv("STRICT_TEST_PATH_BASE", str(tmp_path))
+ monkeypatch.setenv(setting.env_var, "$STRICT_TEST_PATH_BASE")
+ assert registry_with(setting).get_strict(setting.key) == str(tmp_path)
+
+
[email protected]("raw", ["", " "])
+def test_empty_path_is_invalid(monkeypatch, raw):
+ setting = PathSetting("strict.path", "path", create_if_missing=True)
+ monkeypatch.setenv(setting.env_var, raw)
+ with pytest.raises(SettingsValueError):
+ registry_with(setting).get_strict(setting.key, default="caller")
+
+
+def test_missing_required_path_is_not_replaced(monkeypatch, tmp_path):
+ setting = PathSetting("strict.path", "path", must_exist=True)
+ monkeypatch.setenv(setting.env_var, str(tmp_path / "missing-private-path"))
+ with pytest.raises(SettingsValueError) as error:
+ registry_with(setting).get_strict(setting.key, default=str(tmp_path))
+ assert "missing-private-path" not in str(error.value)
+ assert error.value.__context__ is None
+
+
+def test_existing_file_cannot_be_used_as_a_directory(monkeypatch, tmp_path):
+ target = tmp_path / "a-file"
+ target.write_text("data")
+ setting = PathSetting("strict.path", "path", create_if_missing=True)
+ monkeypatch.setenv(setting.env_var, str(target))
+ with pytest.raises(SettingsValueError):
+ registry_with(setting).get_strict(setting.key, default=str(tmp_path))
+ assert target.read_text() == "data"
+
+
[email protected]("failure", ["os", "security"])
+def test_directory_creation_failure_is_explicit_and_safe(
+ monkeypatch, tmp_path, failure
+):
+ from local_deep_research.security import directory_creation
+
+ setting = PathSetting("strict.path", "path", create_if_missing=True)
+ private_path = tmp_path / "private-path-marker"
+ monkeypatch.setenv(setting.env_var, str(private_path))
+
+ def denied(*args, **kwargs):
+ error_type = (
+ PermissionError
+ if failure == "os"
+ else directory_creation.DirectoryCreationSecurityError
+ )
+ raise error_type(f"private-error-marker: {private_path}")
+
+ monkeypatch.setattr(directory_creation, "create_directory", denied)
+ with pytest.raises(SettingsValueError) as error:
+ registry_with(setting).get_strict(setting.key, default=str(tmp_path))
+
+ rendered = "".join(traceback.format_exception(error.value))
+ assert "private-error-marker" not in rendered
+ assert "private-path-marker" not in rendered
+ assert error.value.__cause__ is None
+ assert error.value.__context__ is None
+ assert not private_path.exists()
+
+
+def test_unknown_setting_type_is_rejected_without_invoking_converter(
+ monkeypatch,
+):
+ class UnknownSetting(EnvSetting[str]):
+ def _convert_value(self, raw, **kwargs):
+ pytest.fail("unsupported converter was invoked")
+
+ setting = UnknownSetting("strict.unknown_type", "unknown")
+ monkeypatch.setenv(setting.env_var, "private-value-marker")
+ with pytest.raises(SettingsValueError) as error:
+ registry_with(setting).get_strict(setting.key, default="caller")
+ assert "unsupported" in str(error.value)
+ assert "private-value-marker" not in str(error.value)
+
+
+def test_legacy_bootstrap_reader_keeps_its_existing_contract(monkeypatch):
+ integer = IntegerSetting("strict.integer", "integer", default=5)
+ boolean = BooleanSetting("strict.boolean", "boolean", default=True)
+ registry = SettingsRegistry()
+ registry.register_category("legacy", [integer, boolean])
+ monkeypatch.setenv(integer.env_var, "invalid")
+ monkeypatch.setenv(boolean.env_var, "invalid")
+ assert registry.get(integer.key, default=9) == 5
+ assert registry.get(boolean.key, default=True) is False
diff --git a/tests/settings/test_import_settings_validation.py b/tests/settings/test_import_settings_validation.py
index 77be6355b5..64951af738 100644
--- a/tests/settings/test_import_settings_validation.py
+++ b/tests/settings/test_import_settings_validation.py
@@ -263,6 +263,102 @@ class TestSettingsManagerImportValidation:
assert setting.value == "legacy_stored"
assert setting.options == ["d", "w", "m", "y", "all"]
+ def test_reconciliation_keeps_an_invalid_stored_row_and_continues(
+ self, session, loguru_caplog
+ ):
+ """One invalid stored row must not stop the upgrade reconciliation.
+
+ The strict read of a number row holding a non-number raises
+ SettingsValueError. Login and initialize_default_settings run this
+ import, so it keeps that stored value (neither aborting nor
+ replacing it with the default), still seeds the other defaults,
+ and logs the key without the value.
+ """
+ from local_deep_research.database.models import Setting
+ from local_deep_research.settings.manager import SettingsManager
+
+ planted = "not-a-number-private"
+ manager = SettingsManager(db_session=session)
+ invalid = (
+ session.query(Setting)
+ .filter(Setting.key == "search.iterations")
+ .one()
+ )
+ assert invalid.ui_element == "number"
+ invalid.value = planted
+ # A default shipped by the upgrade has no row yet.
+ session.query(Setting).filter(
+ Setting.key == "search.questions_per_iteration"
+ ).delete()
+ session.commit()
+
+ with loguru_caplog.at_level("WARNING"):
+ manager.import_settings(
+ manager.default_settings,
+ commit=False,
+ overwrite=False,
+ override_locked=True,
+ )
+
+ stored = (
+ session.query(Setting)
+ .filter(Setting.key == "search.iterations")
+ .one()
+ )
+ assert stored.value == planted
+ seeded = (
+ session.query(Setting)
+ .filter(Setting.key == "search.questions_per_iteration")
+ .one()
+ )
+ assert (
+ seeded.value
+ == (
+ manager.default_settings["search.questions_per_iteration"][
+ "value"
+ ]
+ )
+ )
+ assert "'search.iterations'" in loguru_caplog.text
+ assert planted not in loguru_caplog.text
+
+ def test_reconciliation_keeps_a_valid_row_with_an_invalid_child(
+ self, session
+ ):
+ """An invalid child row does not cost the parent its own value."""
+ from local_deep_research.database.models import Setting, SettingType
+ from local_deep_research.settings.exceptions import SettingsValueError
+ from local_deep_research.settings.manager import SettingsManager
+
+ manager = SettingsManager(db_session=session)
+ stored = (
+ session.query(Setting).filter(Setting.key == "llm.provider").one()
+ )
+ stored.value = "openai"
+ session.add(
+ Setting(
+ key="llm.provider.extra",
+ value="not-a-number",
+ type=SettingType.LLM,
+ name="Extra",
+ ui_element="number",
+ )
+ )
+ session.commit()
+ with pytest.raises(SettingsValueError):
+ manager.get_setting("llm.provider", check_env=False)
+
+ manager.import_settings(
+ manager.default_settings, overwrite=False, override_locked=True
+ )
+
+ stored_value = (
+ session.query(Setting.value)
+ .filter(Setting.key == "llm.provider")
+ .scalar()
+ )
+ assert stored_value == "openai"
+
def test_reconciliation_keeps_a_scalar_row_with_child_rows(self, session):
"""Child rows never replace a stored value during reconciliation.
@@ -511,14 +607,7 @@ class TestValidateImportedSettingValueSingleSource:
class TestUnknownUiElementImport:
- """#5674: an unknown ``ui_element`` must not log a default-substitution
- warning on a value the import accepts and stores verbatim.
-
- ``validate_imported_setting_value`` reads ``ui_element`` from the
- current-defaults metadata and uses ``get_typed_setting_value`` only as a
- validity probe, discarding its return. That helper's "returning default
- value" message is therefore false on this path.
- """
+ """Unsupported schemas are rejected without selecting another value."""
UNKNOWN_KEY = "app.future_knob"
UNKNOWN_META = {
@@ -537,50 +626,35 @@ class TestUnknownUiElementImport:
engine = create_engine("sqlite:///:memory:")
Base.metadata.create_all(engine)
- Session = sessionmaker(bind=engine)
- session = Session()
+ session = sessionmaker(bind=engine)()
yield session
session.close()
engine.dispose()
- def test_unknown_ui_element_probe_logs_no_default_warning(
- self, loguru_caplog
- ):
- """The helper under repair, driven directly."""
+ @pytest.mark.parametrize("value", ["user_choice", "shipped_default"])
+ def test_unknown_ui_element_is_rejected(self, value):
from local_deep_research.settings.manager import (
validate_imported_setting_value,
)
- with loguru_caplog.at_level("WARNING"):
- reason = validate_imported_setting_value(
- self.UNKNOWN_KEY, "user_choice", dict(self.UNKNOWN_META)
+ assert (
+ validate_imported_setting_value(
+ self.UNKNOWN_KEY, value, dict(self.UNKNOWN_META)
)
+ == "Unsupported setting type"
+ )
- assert reason is None
- assert "Got unknown type" not in loguru_caplog.text
-
- def test_import_of_unknown_ui_element_default_logs_no_warning(
+ def test_import_reports_unsupported_schema_without_storing_value(
self, session, loguru_caplog
):
- """The same path through ``import_settings``.
-
- The branch is reachable only when the *current defaults* carry a
- ui_element absent from ``UI_ELEMENT_TO_SETTING_TYPE``, since that is
- where ``default_meta`` comes from. Every shipped default uses a known
- element today, so the extra key models a defaults file that has grown
- one ahead of the type map.
- """
from local_deep_research.database.models import Setting
from local_deep_research.settings.manager import SettingsManager
manager = SettingsManager(db_session=session)
- # default_settings is a cached_property; seeding the instance cache
- # adds the key without touching the shipped defaults on disk.
manager.default_settings = {
**manager.default_settings,
self.UNKNOWN_KEY: dict(self.UNKNOWN_META),
}
-
with loguru_caplog.at_level("WARNING"):
manager.import_settings(
{
@@ -592,34 +666,21 @@ class TestUnknownUiElementImport:
overwrite=True,
)
- assert "Got unknown type" not in loguru_caplog.text
- stored = (
- session.query(Setting)
- .filter(Setting.key == self.UNKNOWN_KEY)
- .first()
+ assert "Unsupported setting type" in loguru_caplog.text
+ assert "user_choice" not in loguru_caplog.text
+ assert (
+ session.query(Setting).filter_by(key=self.UNKNOWN_KEY).first()
+ is None
)
- assert stored is not None and stored.value == "user_choice"
- # Stored verbatim and dead on read: get_typed_setting_value has no
- # type for this element, so every read substitutes the default. The
- # message was false about the import, and dropping it does not make
- # the imported value reachable.
- assert manager.get_setting(self.UNKNOWN_KEY) is None
+ def test_unknown_type_read_cannot_return_default(self):
+ from local_deep_research.settings.exceptions import SettingsValueError
+ from local_deep_research.settings.manager import get_typed_setting_value
- def test_get_typed_setting_value_still_warns(self, loguru_caplog):
- """Positive control for the capture path and for the read path.
-
- ``local_deep_research/__init__.py`` disables loguru for the package
- at import time, so a bare negative assertion passes even with the fix
- absent. This also pins that the warning is intact where it is true:
- ``get_typed_setting_value`` really does return the default there.
- """
- from local_deep_research.settings.manager import (
- get_typed_setting_value,
- )
-
- with loguru_caplog.at_level("WARNING"):
- returned = get_typed_setting_value(
+ with pytest.raises(
+ SettingsValueError, match="unsupported setting type"
+ ) as caught:
+ get_typed_setting_value(
key=self.UNKNOWN_KEY,
value="user_choice",
ui_element="future_widget",
@@ -627,8 +688,8 @@ class TestUnknownUiElementImport:
check_env=False,
)
- assert returned == "the_default"
- assert "Got unknown type" in loguru_caplog.text
+ assert "user_choice" not in str(caught.value)
+ assert caught.value.__context__ is None
class TestImportSkipWarningNeverLogsValue:
diff --git a/tests/settings/test_manager_behavior.py b/tests/settings/test_manager_behavior.py
index 795c8f3ceb..b48ee1c244 100644
--- a/tests/settings/test_manager_behavior.py
+++ b/tests/settings/test_manager_behavior.py
@@ -10,6 +10,8 @@ from unittest.mock import patch
import pytest
+from local_deep_research.settings.exceptions import SettingsValueError
+
class TestParseBoolean:
"""Tests for parse_boolean function (HTML checkbox semantics)."""
@@ -309,18 +311,21 @@ class TestGetTypedSettingValue:
)
assert result == "option_a"
- def test_unknown_ui_element_returns_default(self):
- """Unknown ui_element returns default value."""
+ @pytest.mark.parametrize("ui_element", ["unknown_element", None, [], {}])
+ def test_unknown_ui_element_raises(self, ui_element):
+ """Unsupported metadata is an error even with a caller default."""
from local_deep_research.settings.manager import get_typed_setting_value
- result = get_typed_setting_value(
- "test.key",
- "value",
- "unknown_element",
- default="fallback",
- check_env=False,
- )
- assert result == "fallback"
+ with pytest.raises(SettingsValueError) as error:
+ get_typed_setting_value(
+ "test.key",
+ "value",
+ ui_element,
+ default="fallback",
+ check_env=False,
+ )
+ assert error.value.source == "value"
+ assert error.value.reason == "unsupported setting type"
def test_none_value_returns_default(self):
"""None value returns default."""
@@ -340,14 +345,14 @@ class TestGetTypedSettingValue:
)
assert result == 50
- def test_invalid_number_returns_default(self):
- """Invalid number string returns default."""
+ def test_invalid_number_raises(self):
+ """Invalid stored numbers must not select a caller default."""
from local_deep_research.settings.manager import get_typed_setting_value
- result = get_typed_setting_value(
- "test.key", "not_a_number", "number", default=0, check_env=False
- )
- assert result == 0
+ with pytest.raises(SettingsValueError):
+ get_typed_setting_value(
+ "test.key", "not_a_number", "number", default=0, check_env=False
+ )
class TestCheckEnvSetting:
@@ -512,29 +517,29 @@ class TestUIElementToSettingType:
class TestParseNumberEdgeCases:
"""Edge cases for _parse_number that affect real settings."""
- def test_inf_string_returns_float_inf(self):
- """'inf' parses to float — callers must validate range themselves."""
+ def test_inf_string_is_invalid(self):
+ """Infinity cannot be used as a configured numeric value."""
from local_deep_research.settings.manager import _parse_number
- result = _parse_number("inf")
- assert result == float("inf")
- assert isinstance(result, float)
+ with pytest.raises(ValueError):
+ _parse_number("inf")
- def test_negative_inf_string(self):
- """'-inf' parses to negative infinity."""
+ def test_negative_inf_string_is_invalid(self):
+ """Negative infinity is invalid too."""
from local_deep_research.settings.manager import _parse_number
- result = _parse_number("-inf")
- assert result == float("-inf")
-
- def test_nan_string_returns_float_nan(self):
- """'nan' parses to float NaN."""
- import math
+ with pytest.raises(ValueError):
+ _parse_number("-inf")
+ @pytest.mark.parametrize(
+ "value", ["nan", "1e309", float("nan"), float("inf")]
+ )
+ def test_nonfinite_number_is_invalid(self, value):
+ """Reject nonfinite values and text that overflows to infinity."""
from local_deep_research.settings.manager import _parse_number
- result = _parse_number("nan")
- assert math.isnan(result)
+ with pytest.raises(ValueError):
+ _parse_number(value)
def test_int_input_passthrough(self):
"""Direct int input is preserved as int (not round-tripped through float)."""
@@ -572,18 +577,19 @@ class TestParseNumberEdgeCases:
class TestParseMultiselectEdgeCases:
"""Edge cases for _parse_multiselect with non-standard inputs."""
- def test_dict_input_returned_as_is(self):
- """Dict passes through unchanged (not list, not string)."""
+ def test_dict_input_is_invalid(self):
+ """A dictionary cannot replace a multiselect list."""
from local_deep_research.settings.manager import _parse_multiselect
- d = {"key": "value"}
- assert _parse_multiselect(d) is d
+ with pytest.raises(ValueError):
+ _parse_multiselect({"key": "value"})
- def test_int_input_returned_as_is(self):
- """Integer passes through unchanged."""
+ def test_int_input_is_invalid(self):
+ """An integer cannot replace a multiselect list."""
from local_deep_research.settings.manager import _parse_multiselect
- assert _parse_multiselect(42) == 42
+ with pytest.raises(ValueError):
+ _parse_multiselect(42)
def test_none_input_returned_as_is(self):
"""None passes through unchanged."""
@@ -591,15 +597,12 @@ class TestParseMultiselectEdgeCases:
assert _parse_multiselect(None) is None
- def test_json_array_of_non_list_falls_back_to_csv(self):
- """JSON string that parses to non-list falls through to CSV split."""
+ def test_malformed_json_list_is_invalid(self):
+ """A broken JSON list must not become a different CSV value."""
from local_deep_research.settings.manager import _parse_multiselect
- # Starts with '[' but json.loads returns... actually this is a list
- # Use a case where JSON parse succeeds but isn't a list: impossible
- # with '[' prefix. Test that invalid JSON starting with '[' falls to CSV.
- result = _parse_multiselect("[not valid json")
- assert result == ["[not valid json"]
+ with pytest.raises(ValueError):
+ _parse_multiselect("[not valid json")
def test_empty_string_returns_empty_list(self):
"""Empty string returns empty list after CSV split filtering."""
@@ -666,19 +669,58 @@ class TestParseJsonValueEdgeCases:
assert result == {"key": "value"}
-class TestGetTypedSettingValueEnvFallback:
- """Tests for env var → DB fallback path in get_typed_setting_value."""
+class TestGetTypedSettingValueValidation:
+ """The selected value must be valid; lower-priority values cannot replace it."""
- def test_invalid_env_var_falls_back_to_db_value(self):
- """When env var has invalid value for the type, DB value is used."""
+ def test_invalid_env_var_raises_despite_valid_db_and_default(self):
+ """Invalid environment configuration cannot silently select the DB."""
from local_deep_research.settings.manager import get_typed_setting_value
with patch.dict(os.environ, {"LDR_TEST_ITERATIONS": "not_a_number"}):
+ with pytest.raises(SettingsValueError) as error:
+ get_typed_setting_value(
+ "test.iterations", 5, "number", default=0, check_env=True
+ )
+ assert error.value.source == "environment"
+ assert error.value.__context__ is None
+
+ @pytest.mark.parametrize("raw", ["tru", "2", "unexpected-boolean"])
+ def test_invalid_checkbox_env_does_not_select_db_or_default(self, raw):
+ from local_deep_research.settings.manager import get_typed_setting_value
+
+ with patch.dict(os.environ, {"LDR_TEST_CHECKBOX": raw}):
+ with pytest.raises(SettingsValueError) as error:
+ get_typed_setting_value(
+ "test.checkbox", False, "checkbox", default=False
+ )
+ assert error.value.source == "environment"
+ assert error.value.__context__ is None
+
+ @pytest.mark.parametrize(
+ "raw, expected",
+ [
+ ("true", True),
+ (" TRUE ", True),
+ ("1", True),
+ ("yes", True),
+ ("on", True),
+ ("enabled", True),
+ ("false", False),
+ (" FALSE ", False),
+ ("0", False),
+ ("no", False),
+ ("off", False),
+ ("disabled", False),
+ ],
+ )
+ def test_explicit_checkbox_env_tokens(self, raw, expected):
+ from local_deep_research.settings.manager import get_typed_setting_value
+
+ with patch.dict(os.environ, {"LDR_TEST_CHECKBOX": raw}):
result = get_typed_setting_value(
- "test.iterations", 5, "number", default=0, check_env=True
+ "test.checkbox", not expected, "checkbox", default=not expected
)
- # Should fall back to DB value 5, not env "not_a_number"
- assert result == 5
+ assert result is expected
def test_valid_env_var_overrides_db_value(self):
"""When env var is valid, it takes priority over DB value."""
@@ -700,35 +742,26 @@ class TestGetTypedSettingValueEnvFallback:
)
assert result == 5
- def test_env_var_type_error_on_number_does_not_crash(self):
- """TypeError during env var conversion falls through to DB value.
-
- Note: the env path only catches ValueError (line 206), so a TypeError
- would propagate. This documents the current behavior — _parse_number
- with a string always raises ValueError, never TypeError.
- """
+ def test_empty_environment_override_is_treated_as_unset(self):
+ """Retain the documented deployment convention for empty overrides."""
from local_deep_research.settings.manager import get_typed_setting_value
- # _parse_number("") raises ValueError, not TypeError
with patch.dict(os.environ, {"LDR_TEST_NUM": ""}):
result = get_typed_setting_value(
"test.num", 42, "number", default=0, check_env=True
)
assert result == 42
- def test_db_value_type_error_returns_default(self):
- """TypeError during DB value conversion returns default.
-
- This path (line 220) catches both ValueError and TypeError, unlike
- the env path which only catches ValueError.
- """
+ def test_invalid_db_value_type_raises(self):
+ """A stored list cannot be silently replaced by a numeric default."""
from local_deep_research.settings.manager import get_typed_setting_value
- # Passing a type that causes TypeError in float() — e.g. a list
- result = get_typed_setting_value(
- "test.key", [1, 2, 3], "number", default=0, check_env=False
- )
- assert result == 0
+ with pytest.raises(SettingsValueError) as error:
+ get_typed_setting_value(
+ "test.key", [1, 2, 3], "number", default=0, check_env=False
+ )
+ assert error.value.source == "value"
+ assert error.value.__context__ is None
def test_textarea_preserves_multiline_string(self):
"""Textarea ui_element preserves newlines (uses str converter)."""
@@ -740,18 +773,15 @@ class TestGetTypedSettingValueEnvFallback:
)
assert result == multiline
- def test_number_with_bool_input_converts_to_int(self):
- """Bool passed to number field: float(True)=1.0, is_integer()→int 1.
-
- This is a real scenario when frontend sends JSON true for a number field.
- """
+ @pytest.mark.parametrize("value", [True, False])
+ def test_number_with_bool_input_is_invalid(self, value):
+ """JSON booleans are not valid numeric settings."""
from local_deep_research.settings.manager import get_typed_setting_value
- result = get_typed_setting_value(
- "test.key", True, "number", check_env=False
- )
- assert result == 1
- assert isinstance(result, int)
+ with pytest.raises(SettingsValueError):
+ get_typed_setting_value(
+ "test.key", value, "number", check_env=False
+ )
def test_checkbox_with_int_zero(self):
"""Integer 0 sent for a checkbox field returns False."""
diff --git a/tests/settings/test_operational_settings_error_propagation.py b/tests/settings/test_operational_settings_error_propagation.py
new file mode 100644
index 0000000000..6ecb13c362
--- /dev/null
+++ b/tests/settings/test_operational_settings_error_propagation.py
@@ -0,0 +1,219 @@
+"""Invalid configuration stops work before anonymous or default behavior."""
+
+from contextlib import nullcontext
+from unittest.mock import Mock, patch
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import Session
+
+from local_deep_research.api.settings_utils import InMemorySettingsManager
+from local_deep_research.database.models.settings import Setting, SettingType
+from local_deep_research.settings.exceptions import SettingsValueError
+from local_deep_research.web_search_engines.engines.search_engine_nasa_ads import (
+ NasaAdsSearchEngine,
+)
+from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+)
+from local_deep_research.web_search_engines.engines.search_engine_semantic_scholar import (
+ SemanticScholarSearchEngine,
+)
+
+
+ENGINE_CASES = [
+ (OpenAlexSearchEngine, "openalex"),
+ (SemanticScholarSearchEngine, "semantic_scholar"),
+ (NasaAdsSearchEngine, "nasa_ads"),
+]
+
+
+def settings_snapshot():
+ return InMemorySettingsManager().get_all_settings()
+
+
[email protected](("engine_class", "engine_name"), ENGINE_CASES)
[email protected]("through_factory", [False, True])
+def test_scholarly_engine_does_not_replace_invalid_credentials(
+ engine_class, engine_name, through_factory, settings_snapshot, monkeypatch
+):
+ from local_deep_research.security.egress import policy
+ from local_deep_research.web_search_engines import search_engine_factory
+
+ key = f"search.engine.web.{engine_name}.api_key"
+ settings_snapshot[key] = {
+ "value": "invalid-number",
+ "ui_element": "number",
+ }
+ settings_snapshot[
+ f"search.engine.web.{engine_name}.journal_reputation.enabled"
+ ] = False
+
+ if through_factory:
+ # Keep the real constructor and settings reader under the factory's
+ # exception handler; engine discovery and policy are unrelated here.
+ monkeypatch.setattr(
+ search_engine_factory.retriever_registry,
+ "get",
+ lambda *a, **k: None,
+ )
+ monkeypatch.setattr(
+ search_engine_factory,
+ "search_config",
+ lambda **kwargs: {
+ engine_name: {"module_path": ".probe", "class_name": "Probe"}
+ },
+ )
+ monkeypatch.setattr(
+ search_engine_factory,
+ "get_safe_module_class",
+ lambda *a, **k: engine_class,
+ )
+ monkeypatch.setattr(
+ policy,
+ "evaluate_engine",
+ lambda *a, **k: policy.Decision(True, "test_allowed"),
+ )
+
+ with pytest.raises(SettingsValueError, match=key):
+ if through_factory:
+ search_engine_factory.create_search_engine(
+ engine_name,
+ llm=Mock(),
+ settings_snapshot=settings_snapshot,
+ programmatic_mode=True,
+ )
+ else:
+ engine_class(
+ settings_snapshot=settings_snapshot, programmatic_mode=True
+ )
+
+
+def test_openalex_does_not_drop_invalid_optional_email(settings_snapshot):
+ settings_snapshot[
+ "search.engine.web.openalex.journal_reputation.enabled"
+ ] = False
+ settings_snapshot["search.engine.web.openalex.email"] = {
+ "value": "invalid-number",
+ "ui_element": "number",
+ }
+
+ with pytest.raises(SettingsValueError, match="openalex.email"):
+ OpenAlexSearchEngine(
+ settings_snapshot=settings_snapshot, programmatic_mode=True
+ )
+
+
[email protected]("invalid_setting", ["enabled", "threshold"])
+def test_journal_settings_cannot_silently_disable_filtering(
+ invalid_setting, settings_snapshot, monkeypatch
+):
+ from local_deep_research.advanced_search_system.filters import (
+ journal_reputation_filter,
+ )
+
+ if invalid_setting == "enabled":
+ key = "search.engine.web.openalex.journal_reputation.enabled"
+ monkeypatch.setenv(
+ "LDR_SEARCH_ENGINE_WEB_OPENALEX_JOURNAL_REPUTATION_ENABLED",
+ "invalid-boolean",
+ )
+ else:
+ key = "search.journal_reputation.threshold"
+ settings_snapshot[key] = {
+ "value": "invalid-number",
+ "ui_element": "number",
+ }
+
+ with patch.object(
+ journal_reputation_filter, "create_search_engine"
+ ) as engine:
+ with pytest.raises(SettingsValueError, match=key):
+ journal_reputation_filter.JournalReputationFilter.create_default(
+ model=Mock(),
+ engine_name="openalex",
+ settings_snapshot=settings_snapshot,
+ )
+
+ engine.assert_not_called()
+
+
+def test_elasticsearch_invalid_hosts_do_not_become_available(
+ settings_snapshot, monkeypatch
+):
+ from local_deep_research.web_search_engines.engines.search_engine_elasticsearch import (
+ ElasticsearchSearchEngine,
+ )
+
+ monkeypatch.setenv(
+ "LDR_SEARCH_ENGINE_WEB_ELASTICSEARCH_DEFAULT_PARAMS_HOSTS",
+ "[invalid-json",
+ )
+ with patch.object(
+ ElasticsearchSearchEngine, "_probe_hosts_available"
+ ) as probe:
+ with pytest.raises(
+ SettingsValueError, match="elasticsearch.default_params.hosts"
+ ):
+ ElasticsearchSearchEngine.is_available(settings_snapshot)
+
+ probe.assert_not_called()
+
+
+def test_zotero_invalid_interval_does_not_use_default(monkeypatch):
+ from local_deep_research.research_library.zotero import sync_service
+
+ database = create_engine("sqlite:///:memory:")
+ Setting.__table__.create(database)
+ try:
+ with Session(database) as session:
+ session.add(
+ Setting(
+ key="zotero.sync_interval_minutes",
+ name="Sync interval",
+ value=60,
+ type=SettingType.APP,
+ ui_element="number",
+ )
+ )
+ session.commit()
+ monkeypatch.setattr(
+ sync_service,
+ "get_user_db_session",
+ lambda *a: nullcontext(session),
+ )
+ service = sync_service.ZoteroSyncService("alice")
+ assert service.get_config().sync_interval_minutes == 60
+
+ monkeypatch.setenv(
+ "LDR_ZOTERO_SYNC_INTERVAL_MINUTES", "invalid-number"
+ )
+ with pytest.raises(
+ SettingsValueError, match="zotero.sync_interval_minutes"
+ ):
+ service.get_config()
+
+ monkeypatch.delenv("LDR_ZOTERO_SYNC_INTERVAL_MINUTES")
+ assert service.get_config().sync_interval_minutes == 60
+ finally:
+ database.dispose()
+
+
+def test_disabled_journal_filter_remains_optional(settings_snapshot):
+ from local_deep_research.advanced_search_system.filters.journal_reputation_filter import (
+ JournalReputationFilter,
+ )
+
+ settings_snapshot[
+ "search.engine.web.openalex.journal_reputation.enabled"
+ ] = False
+
+ assert (
+ JournalReputationFilter.create_default(
+ model=Mock(),
+ engine_name="openalex",
+ settings_snapshot=settings_snapshot,
+ )
+ is None
+ )
diff --git a/tests/settings/test_parse_edge_cases.py b/tests/settings/test_parse_edge_cases.py
index d0e684ff0c..cb5d4c2c00 100644
--- a/tests/settings/test_parse_edge_cases.py
+++ b/tests/settings/test_parse_edge_cases.py
@@ -40,13 +40,10 @@ class TestParseNumberEdgeCases:
class TestParseMultiselectEdgeCases:
"""Edge cases not covered by test_parse_multiselect.py."""
- def test_json_parses_to_dict_falls_to_comma_split(self):
- """JSON that parses to a dict (not list) falls through to comma split."""
- result = _parse_multiselect('{"a": 1}')
- # JSON parses OK but isinstance(parsed, list) is False
- # Falls through to comma-separated split
- assert isinstance(result, list)
- assert result == ['{"a": 1}']
+ def test_json_object_is_not_reinterpreted_as_comma_separated(self):
+ """An object cannot replace the list a multiselect requires."""
+ with pytest.raises(ValueError):
+ _parse_multiselect('{"a": 1}')
def test_only_commas_returns_empty_list(self):
"""String of only commas → all items strip to empty → filtered out."""
diff --git a/tests/settings/test_parse_multiselect.py b/tests/settings/test_parse_multiselect.py
index ccaf3caf3f..8389592490 100644
--- a/tests/settings/test_parse_multiselect.py
+++ b/tests/settings/test_parse_multiselect.py
@@ -5,6 +5,8 @@ Covers list passthrough, JSON array parsing, comma-separated splitting,
and edge cases (empty, malformed, non-string/list types).
"""
+import pytest
+
from local_deep_research.settings.manager import _parse_multiselect
@@ -38,9 +40,10 @@ class TestParseMultiselect:
def test_empty_string(self):
assert _parse_multiselect("") == []
- def test_malformed_json_falls_back_to_comma(self):
- result = _parse_multiselect('["broken')
- assert result == ['["broken']
+ def test_malformed_json_is_not_reinterpreted_as_comma_separated(self):
+ with pytest.raises(ValueError):
+ _parse_multiselect('["broken')
- def test_non_string_non_list_passthrough(self):
- assert _parse_multiselect(42) == 42
+ def test_non_string_non_list_is_invalid(self):
+ with pytest.raises(ValueError):
+ _parse_multiselect(42)
diff --git a/tests/settings/test_settings_error_propagation.py b/tests/settings/test_settings_error_propagation.py
new file mode 100644
index 0000000000..ffd56e2352
--- /dev/null
+++ b/tests/settings/test_settings_error_propagation.py
@@ -0,0 +1,316 @@
+"""Invalid configured values must stop work at consumer fallback boundaries."""
+
+import json
+from contextlib import nullcontext
+from threading import RLock
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+
+from local_deep_research.settings.exceptions import SettingsValueError
+
+
+def settings_error():
+ return SettingsValueError(
+ "llm.temperature", source="environment", reason="expected a number"
+ )
+
+
[email protected]("source", ["snapshot", "database"])
+def test_search_config_does_not_replace_invalid_settings(
+ monkeypatch, settings_error, source
+):
+ from local_deep_research.web_search_engines import search_engines_config
+
+ reader = Mock(side_effect=settings_error)
+ database_reader = Mock()
+ manager = SimpleNamespace(get_setting=database_reader)
+ manager_factory = Mock(return_value=manager)
+ monkeypatch.setattr(
+ search_engines_config, "get_setting_from_snapshot", reader
+ )
+ monkeypatch.setattr(
+ search_engines_config, "get_settings_manager", manager_factory
+ )
+ if source == "database":
+ database_reader.side_effect = settings_error
+
+ with pytest.raises(SettingsValueError) as raised:
+ search_engines_config._get_setting(
+ "llm.temperature",
+ default_value=0.7,
+ db_session=object(),
+ settings_snapshot={"present": True}
+ if source == "snapshot"
+ else None,
+ )
+
+ assert raised.value is settings_error
+ if source == "snapshot":
+ manager_factory.assert_not_called()
+
+
+def test_availability_probe_does_not_treat_invalid_settings_as_available(
+ monkeypatch, settings_error
+):
+ from local_deep_research.security import module_whitelist
+ from local_deep_research.web_search_engines import search_engines_config
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class InvalidSettingsEngine(BaseSearchEngine):
+ @classmethod
+ def is_available(cls, settings_snapshot=None):
+ raise settings_error
+
+ monkeypatch.setattr(
+ module_whitelist,
+ "get_safe_module_class",
+ lambda *args: InvalidSettingsEngine,
+ )
+
+ with pytest.raises(SettingsValueError) as raised:
+ search_engines_config._engine_class_is_available(
+ "probe",
+ {"module_path": ".probe", "class_name": "Probe"},
+ {"present": True},
+ )
+
+ assert raised.value is settings_error
+
+
+def test_engine_constructor_error_does_not_become_a_default_engine(
+ monkeypatch, settings_error
+):
+ from local_deep_research.security.egress import policy
+ from local_deep_research.web_search_engines import search_engine_factory
+
+ constructions = []
+
+ class InvalidSettingsEngine:
+ def __init__(self, settings_snapshot=None):
+ constructions.append(settings_snapshot)
+ raise settings_error
+
+ monkeypatch.setattr(
+ search_engine_factory.retriever_registry, "get", lambda *a, **k: None
+ )
+ monkeypatch.setattr(
+ search_engine_factory,
+ "search_config",
+ lambda **kwargs: {
+ "probe": {"module_path": ".probe", "class_name": "Probe"}
+ },
+ )
+ monkeypatch.setattr(
+ search_engine_factory,
+ "get_safe_module_class",
+ lambda *args: InvalidSettingsEngine,
+ )
+ monkeypatch.setattr(
+ policy,
+ "evaluate_engine",
+ lambda *args, **kwargs: policy.Decision(True, "test_allowed"),
+ )
+
+ with pytest.raises(SettingsValueError) as raised:
+ search_engine_factory.create_search_engine(
+ "probe", settings_snapshot={"search.tool": "probe"}
+ )
+
+ assert raised.value is settings_error
+ assert len(constructions) == 1
+
+
+def test_full_search_constructor_error_does_not_return_the_base_engine(
+ monkeypatch, settings_error
+):
+ from local_deep_research.web_search_engines import search_engine_factory
+
+ class InvalidSettingsWrapper:
+ def __init__(self, settings_snapshot=None):
+ raise settings_error
+
+ monkeypatch.setattr(
+ search_engine_factory,
+ "get_safe_module_class",
+ lambda *args: InvalidSettingsWrapper,
+ )
+
+ with pytest.raises(SettingsValueError) as raised:
+ search_engine_factory._create_full_search_wrapper(
+ "probe",
+ base_engine=object(),
+ engine_config={
+ "full_search_module": ".probe",
+ "full_search_class": "Probe",
+ },
+ llm=None,
+ params={},
+ settings_snapshot={"present": True},
+ )
+
+ assert raised.value is settings_error
+
+
+ "invalid_key",
+ [
+ "search.cross_engine_max_results",
+ "search.cross_engine_max_context_items",
+ ],
+)
+def test_filter_does_not_replace_invalid_settings_with_limits(
+ monkeypatch, settings_error, invalid_key
+):
+ from local_deep_research.advanced_search_system.filters.cross_engine_filter import (
+ CrossEngineFilter,
+ )
+ from local_deep_research.config import thread_settings
+
+ def read(key, default=None, **kwargs):
+ if key == invalid_key:
+ raise settings_error
+ return default
+
+ monkeypatch.setattr(thread_settings, "get_setting_from_snapshot", read)
+
+ with pytest.raises(SettingsValueError) as raised:
+ CrossEngineFilter(model=Mock(), settings_snapshot={"present": True})
+
+ assert raised.value is settings_error
+
+
[email protected]("allow_default_settings", [False, True])
+def test_api_default_opt_in_does_not_waive_invalid_configuration(
+ monkeypatch, settings_error, allow_default_settings
+):
+ from local_deep_research.web.routers import api_v1
+
+ manager = Mock()
+ manager.get_settings_snapshot.side_effect = settings_error
+ monkeypatch.setattr(
+ api_v1, "get_user_db_session", lambda *args: nullcontext(object())
+ )
+ monkeypatch.setattr(api_v1, "get_settings_manager", lambda *args: manager)
+ params = {}
+
+ refused = api_v1._load_user_context_into_params(
+ params, "alice", allow_default_settings=allow_default_settings
+ )
+
+ # Refused with the repair diagnostic instead of the app-wide generic
+ # 500, and before the opt-in branch could run with an empty snapshot.
+ assert "settings_snapshot" not in params
+ assert refused is not None and refused.status_code == 503
+ body = json.loads(refused.body)
+ assert body["reason"] == "invalid_setting"
+ assert str(settings_error) in body["error"]
+ assert "allow_default_settings does not bypass" in body["how_to_fix"]
+
+
+def test_benchmark_fails_without_launching_a_worker_for_invalid_settings(
+ monkeypatch, settings_error
+):
+ from local_deep_research import settings
+ from local_deep_research.benchmarks.web_api import benchmark_service
+ from local_deep_research.database import session_context
+
+ run = SimpleNamespace(
+ id=1,
+ status=None,
+ error_message=None,
+ config_hash="test-config",
+ datasets_config={},
+ search_config={},
+ evaluation_config={},
+ )
+ session = Mock()
+ session.query.return_value.filter.return_value.first.return_value = run
+ monkeypatch.setattr(
+ session_context,
+ "get_user_db_session",
+ lambda *args: nullcontext(session),
+ )
+ manager = Mock()
+ manager.get_all_settings.side_effect = settings_error
+ monkeypatch.setattr(settings, "SettingsManager", lambda *args: manager)
+ monkeypatch.setattr(
+ "local_deep_research.utilities.request_context.get_current_session_id",
+ lambda: None,
+ )
+ thread = Mock()
+ monkeypatch.setattr(benchmark_service.threading, "Thread", thread)
+ service = benchmark_service.BenchmarkService(socket_service=Mock())
+
+ assert service.start_benchmark(1, username="alice") is False
+
+ assert run.status == benchmark_service.BenchmarkStatus.FAILED
+ assert run.error_message == str(settings_error)
+ assert service.active_runs == {}
+ thread.assert_not_called()
+
+
+def test_scheduler_does_not_cache_or_return_default_configuration(
+ monkeypatch, settings_error
+):
+ from local_deep_research.database import session_context
+ from local_deep_research.scheduler.background import BackgroundJobScheduler
+ from local_deep_research.settings import manager as settings_manager
+
+ scheduler = object.__new__(BackgroundJobScheduler)
+ scheduler._settings_cache_lock = RLock()
+ scheduler._settings_cache = {}
+ scheduler.user_sessions = {"alice": {"active": True}}
+ scheduler._credential_store = Mock()
+ scheduler._credential_store.retrieve.return_value = "test-password"
+ monkeypatch.setattr(
+ session_context,
+ "get_user_db_session",
+ lambda *args: nullcontext(object()),
+ )
+ manager = Mock()
+ manager.get_setting.side_effect = settings_error
+ monkeypatch.setattr(
+ settings_manager, "SettingsManager", lambda *args: manager
+ )
+
+ with pytest.raises(SettingsValueError) as raised:
+ scheduler._get_document_scheduler_settings("alice")
+
+ assert raised.value is settings_error
+ assert scheduler._settings_cache == {}
+
+
+def test_stream_usage_error_does_not_use_model_capability(
+ monkeypatch, settings_error
+):
+ from local_deep_research.config import thread_settings
+ from local_deep_research.config.llm_config import ProcessingLLMWrapper
+
+ reader = Mock(side_effect=settings_error)
+ monkeypatch.setattr(thread_settings, "get_setting_from_snapshot", reader)
+ wrapper = ProcessingLLMWrapper(
+ SimpleNamespace(disable_streaming=False, stream_usage=True),
+ provider="openai_endpoint",
+ settings_snapshot={"present": True},
+ )
+
+ with pytest.raises(SettingsValueError) as raised:
+ wrapper._stream_cancel_allowed()
+
+ assert raised.value is settings_error
+
+
+def test_absent_optional_filter_settings_still_use_documented_defaults():
+ from local_deep_research.advanced_search_system.filters.cross_engine_filter import (
+ CrossEngineFilter,
+ )
+
+ filtering = CrossEngineFilter(model=Mock(), settings_snapshot={})
+
+ assert filtering.max_results == 100
+ assert filtering.max_context_items == 30
diff --git a/tests/settings/test_settings_manager.py b/tests/settings/test_settings_manager.py
index c75cee2ba7..a0ffeabea6 100644
--- a/tests/settings/test_settings_manager.py
+++ b/tests/settings/test_settings_manager.py
@@ -16,6 +16,7 @@ import threading
import pytest
from unittest.mock import MagicMock, patch, PropertyMock
+from local_deep_research.settings.exceptions import SettingsValueError
from local_deep_research.settings.manager import (
SettingsManager,
apply_environment_overrides_to_snapshot,
@@ -1312,15 +1313,14 @@ class TestHelperFunctions:
assert parse_boolean(" ") is False
def test_get_typed_setting_value_unknown_ui_element(self):
- """Test get_typed_setting_value returns default for unknown UI element."""
- result = get_typed_setting_value(
- key="test",
- value="val",
- ui_element="unknown_element",
- default="fallback",
- )
-
- assert result == "fallback"
+ """An unsupported UI element must not silently select a default."""
+ with pytest.raises(SettingsValueError):
+ get_typed_setting_value(
+ key="test",
+ value="val",
+ ui_element="unknown_element",
+ default="fallback",
+ )
def test_get_typed_setting_value_json_passthrough(self):
"""Test get_typed_setting_value passes JSON through unchanged."""
@@ -1333,12 +1333,14 @@ class TestHelperFunctions:
assert result == json_value
def test_get_typed_setting_value_invalid_number(self):
- """Test get_typed_setting_value returns default for invalid number."""
- result = get_typed_setting_value(
- key="test", value="not_a_number", ui_element="number", default=99
- )
-
- assert result == 99
+ """An invalid numeric value must not silently select a default."""
+ with pytest.raises(SettingsValueError):
+ get_typed_setting_value(
+ key="test",
+ value="not_a_number",
+ ui_element="number",
+ default=99,
+ )
def test_get_typed_setting_value_select_returns_string(self):
"""Test get_typed_setting_value returns string for select."""
@@ -2299,9 +2301,10 @@ class TestParseMultiselect:
"""Empty string returns empty list."""
assert _parse_multiselect("") == []
- def test_invalid_json_falls_back_to_comma_split(self):
- """Invalid JSON starting with [ falls back to comma splitting."""
- assert _parse_multiselect("[broken,json") == ["[broken", "json"]
+ def test_invalid_json_is_not_reinterpreted_as_comma_separated(self):
+ """A broken JSON list must not become a different CSV list."""
+ with pytest.raises(ValueError):
+ _parse_multiselect("[broken,json")
def test_whitespace_only_items_filtered(self):
"""Whitespace-only items between commas are filtered out."""
@@ -2365,8 +2368,8 @@ class TestMultiselectEnvVarOverride:
assert result == ["markdown", "latex"]
-class TestEnvVarWithoutDefaultsWarning:
- """Tests for warning when env var override has no type information."""
+class TestEnvVarWithoutDefaultsValidation:
+ """Typed overrides are converted; untyped ones are returned unconverted."""
@pytest.fixture(autouse=True)
def clean_env(self):
@@ -2384,8 +2387,19 @@ class TestEnvVarWithoutDefaultsWarning:
for key, value in original_env.items():
os.environ[key] = value
- def test_env_var_without_defaults_logs_warning(self):
- """Env var override for unknown setting logs a warning."""
+ def test_env_var_without_defaults_passes_through_unconverted(self):
+ """An override for a key with no declared type is returned as is.
+
+ This test used to require a ``SettingsValueError`` here. That
+ premise was wrong: untyped environment-only keys exist in
+ production (``app.api_rate_limit`` and ``app.enable_api`` have no
+ defaults entry and no seeded row), and ``require_api_access`` reads
+ them on every ``/api/v1`` request. Raising turned
+ ``LDR_APP_API_RATE_LIMIT=120`` into a 500 on every API call. With
+ no type there is nothing to validate against, so the raw string is
+ returned, as on main, and the consumer parses it. Typed keys still
+ raise on a value that cannot be converted.
+ """
os.environ["LDR_UNKNOWN_SETTING"] = "some_value"
mock_session = MagicMock()
@@ -2402,8 +2416,9 @@ class TestEnvVarWithoutDefaultsWarning:
assert result == "some_value"
mock_logger.warning.assert_called()
- warning_msg = mock_logger.warning.call_args[0][0]
- assert "not in defaults" in warning_msg
+ assert "not in defaults" in mock_logger.warning.call_args[0][0]
+ # The warning names the key, never the value.
+ assert "some_value" not in str(mock_logger.warning.call_args)
def test_env_var_with_defaults_no_warning(self):
"""Env var override for known setting does not log a warning."""
diff --git a/tests/settings/test_settings_manager_contracts.py b/tests/settings/test_settings_manager_contracts.py
index f2e65ad8d5..a66bb1ea2d 100644
--- a/tests/settings/test_settings_manager_contracts.py
+++ b/tests/settings/test_settings_manager_contracts.py
@@ -76,9 +76,11 @@ result can never come from a broken call.
"""
import ast
+import copy
import functools
import inspect
import shutil
+import traceback
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable, Dict, Optional
@@ -93,6 +95,7 @@ from local_deep_research.api.settings_utils import InMemorySettingsManager
from local_deep_research.database.models import Base, Setting
from local_deep_research.settings.base import ISettingsManager
from local_deep_research.settings.manager import SettingsManager
+from local_deep_research.settings.exceptions import SettingsValueError
_PKG = Path(local_deep_research.__file__).parent
_BACKGROUND_PY = _PKG / "scheduler" / "background.py"
@@ -113,6 +116,7 @@ _ENV_VARS_USED = (
"LDR_TESTING_TEST_MODE",
"LDR_ZZZ_NOT_A_SETTING",
"LDR_BRAND_NEW_KEY",
+ "LDR_CUSTOM_READ_VALUE",
)
@@ -198,6 +202,546 @@ def _make_memory_manager(locked: bool = False) -> InMemorySettingsManager:
return manager
+# ---------------------------------------------------------------------------
+class TestTypedReadsAndSnapshots:
+ @staticmethod
+ def _manager(storage, make_db_manager):
+ return (
+ make_db_manager()
+ if storage == "database"
+ else InMemorySettingsManager()
+ )
+
+ @pytest.mark.parametrize("storage", ["database", "memory"])
+ @pytest.mark.parametrize(
+ "key,env_name,stored",
+ [
+ ("app.port", "LDR_APP_PORT", 6123),
+ ("llm.temperature", "LDR_LLM_TEMPERATURE", 0.35),
+ ],
+ )
+ def test_invalid_numeric_env_raises_in_every_effective_read(
+ self, storage, key, env_name, stored, make_db_manager, monkeypatch
+ ):
+ manager = self._manager(storage, make_db_manager)
+ assert manager.set_setting(key, stored)
+ baseline = manager.get_all_settings(include_environment_overrides=False)
+ monkeypatch.setenv(env_name, "not-a-number")
+
+ for read in (
+ lambda: manager.get_setting(key, default=991),
+ manager.get_all_settings,
+ manager.get_settings_snapshot,
+ lambda: manager.get_setting(key.rsplit(".", 1)[0], default=991),
+ ):
+ _assert_settings_error(read, key, "not-a-number")
+ assert manager.get_setting(key, check_env=False) == stored
+ assert (
+ manager.get_all_settings(include_environment_overrides=False)
+ == baseline
+ )
+
+ @pytest.mark.parametrize("storage", ["database", "memory"])
+ def test_numeric_environment_changes_do_not_replace_the_stored_value(
+ self, storage, make_db_manager, monkeypatch
+ ):
+ manager = self._manager(storage, make_db_manager)
+ key = "llm.temperature"
+ assert manager.set_setting(key, 0.35)
+
+ monkeypatch.setenv("LDR_LLM_TEMPERATURE", "invalid")
+ _assert_settings_error(manager.get_settings_snapshot, key)
+ for raw, expected in [("0.5", 0.5), ("", 0.35)]:
+ monkeypatch.setenv("LDR_LLM_TEMPERATURE", raw)
+ assert manager.get_setting(key) == expected
+ assert manager.get_all_settings()[key]["value"] == expected
+ assert manager.get_settings_snapshot()[key] == expected
+ assert manager.get_setting(key, check_env=False) == 0.35
+
+ monkeypatch.delenv("LDR_LLM_TEMPERATURE")
+ assert manager.get_settings_snapshot()[key] == 0.35
+
+ @pytest.mark.parametrize(
+ "key,env_name",
+ [
+ ("app.port", "LDR_APP_PORT"),
+ ("llm.temperature", "LDR_LLM_TEMPERATURE"),
+ ],
+ )
+ def test_defaults_only_database_snapshot_rejects_invalid_env(
+ self, key, env_name, monkeypatch
+ ):
+ manager = SettingsManager(db_session=None)
+ baseline = manager.get_all_settings(include_environment_overrides=False)
+ expected = baseline[key]["value"]
+ assert isinstance(expected, (int, float))
+ monkeypatch.setenv(env_name, "not-a-number")
+
+ for read in (
+ lambda: manager.get_setting(key, default=991),
+ manager.get_all_settings,
+ manager.get_settings_snapshot,
+ ):
+ _assert_settings_error(read, key, "not-a-number")
+ assert manager.get_setting(key, check_env=False) == expected
+ assert (
+ manager.get_all_settings(include_environment_overrides=False)
+ == baseline
+ )
+
+ @pytest.mark.parametrize("storage", ["database", "memory"])
+ def test_absent_known_key_uses_default_schema_for_environment_value(
+ self, storage, make_db_manager, monkeypatch
+ ):
+ manager = self._manager(storage, make_db_manager)
+ assert manager.delete_setting("app.port")
+ monkeypatch.setenv("LDR_APP_PORT", "8123")
+
+ assert manager.get_setting("app.port", default=42) == 8123
+ assert (
+ manager.get_setting("app.port", default=42, check_env=False) == 42
+ )
+ monkeypatch.setenv("LDR_APP_PORT", "invalid")
+ _assert_settings_error(
+ lambda: manager.get_setting("app.port", default=42), "app.port"
+ )
+
+ @pytest.mark.parametrize("storage", ["database", "memory"])
+ def test_unknown_environment_key_is_returned_unconverted(
+ self, storage, make_db_manager, monkeypatch
+ ):
+ """With no declared type there is nothing to validate against.
+
+ Both stores return the raw override, as SettingsManager did on
+ main: untyped keys such as app.api_rate_limit are read on every
+ /api/v1 request and their consumers parse the string.
+ """
+ manager = self._manager(storage, make_db_manager)
+ key = "zzz.not_a_setting"
+ assert manager.get_setting(key, default="fallback") == "fallback"
+ monkeypatch.setenv("LDR_ZZZ_NOT_A_SETTING", "from-env")
+
+ assert manager.get_setting(key, default="fallback") == "from-env"
+ assert (
+ manager.get_setting(key, default="fallback", check_env=False)
+ == "fallback"
+ )
+ assert key not in manager.get_all_settings()
+ monkeypatch.setenv("LDR_ZZZ_NOT_A_SETTING", "")
+ assert manager.get_setting(key, default="fallback") == "fallback"
+
+ @pytest.mark.parametrize("storage", ["database", "memory"])
+ def test_env_only_keys_keep_registry_typing_and_are_not_store_reads(
+ self, storage, make_db_manager, monkeypatch
+ ):
+ manager = self._manager(storage, make_db_manager)
+ key = "testing.test_mode"
+ monkeypatch.setenv("LDR_TESTING_TEST_MODE", "true")
+
+ assert manager.get_setting(key, default=False) is True
+ # Disabling environment reads uses the registry's declared default.
+ assert manager.get_setting(key, default=True, check_env=False) is False
+ assert manager.get_bool_setting(key) is True
+ monkeypatch.setenv("LDR_TESTING_TEST_MODE", "false")
+ assert manager.get_setting(key, default=True) is False
+
+ @pytest.mark.parametrize("storage", ["database", "memory"])
+ def test_null_read_uses_caller_default_without_rewriting_the_snapshot(
+ self, storage, make_db_manager
+ ):
+ manager = self._manager(storage, make_db_manager)
+ key = "llm.google.api_key"
+ fallback = object()
+
+ assert manager.get_setting(key, default=fallback) is fallback
+ assert manager.get_setting(key) is None
+ assert manager.get_settings_snapshot()[key] is None
+
+ def test_memory_namespace_uses_full_child_keys_for_environment_reads(
+ self, monkeypatch
+ ):
+ manager = InMemorySettingsManager()
+ monkeypatch.setenv("LDR_LLM_GOOGLE_API_KEY", "namespaced-value")
+ monkeypatch.setenv("LDR_API_KEY", "unrelated-value")
+
+ assert manager.get_setting("llm.google") == {
+ "api_key": "namespaced-value"
+ }
+ assert manager.get_setting(
+ "llm.google", default="missing", check_env=False
+ ) == {"api_key": "missing"}
+
+ def test_memory_namespace_ignores_malformed_children_and_nearby_prefixes(
+ self,
+ ):
+ manager = InMemorySettingsManager()
+ for key in (
+ "read_probe.",
+ "read_probe..value",
+ "read_probe. bad",
+ "read_probe2.value",
+ ):
+ manager._settings[key] = {"value": "ignored", "ui_element": "text"}
+ assert (
+ manager.get_setting(
+ "read_probe", default="missing", check_env=False
+ )
+ == "missing"
+ )
+
+ manager._settings["read_probe.value"] = {
+ "value": "7",
+ "ui_element": "number",
+ }
+ assert manager.get_setting("read_probe", check_env=False) == {
+ "value": 7
+ }
+ manager._settings["read_probe"] = {
+ "value": "exact",
+ "ui_element": "text",
+ }
+ assert manager.get_setting("read_probe", check_env=False) == "exact"
+
+ def test_memory_operator_path_does_not_become_a_child_namespace(
+ self, monkeypatch
+ ):
+ manager = InMemorySettingsManager()
+ key = "research_library.storage_path"
+ monkeypatch.delenv("LDR_RESEARCH_LIBRARY_STORAGE_PATH", raising=False)
+ manager._settings.pop(key, None)
+ manager._settings[key + ".child"] = {
+ "value": "child",
+ "ui_element": "text",
+ }
+
+ assert manager.get_setting(key, default="fallback") == "fallback"
+
+ def test_programmatic_snapshot_rejects_invalid_env(self, monkeypatch):
+ from local_deep_research.api.settings_utils import (
+ create_settings_snapshot,
+ extract_setting_value,
+ )
+
+ baseline = create_settings_snapshot()
+ expected = extract_setting_value(baseline, "llm.temperature")
+ assert isinstance(expected, (int, float))
+ monkeypatch.setenv("LDR_LLM_TEMPERATURE", "not-a-number")
+
+ _assert_settings_error(create_settings_snapshot, "llm.temperature")
+ _assert_settings_error(
+ lambda: create_settings_snapshot(temperature=0.6),
+ "llm.temperature",
+ )
+ assert extract_setting_value(baseline, "llm.temperature") == expected
+ monkeypatch.delenv("LDR_LLM_TEMPERATURE")
+ assert (
+ extract_setting_value(
+ create_settings_snapshot(temperature=0.6), "llm.temperature"
+ )
+ == 0.6
+ )
+
+
+def _assert_settings_error(read, key, secret=None):
+ with pytest.raises(SettingsValueError) as raised:
+ read()
+ error = raised.value
+ assert key in str(error)
+ assert error.__cause__ is None
+ assert error.__context__ is None
+ if secret is not None:
+ rendered = (
+ str(error)
+ + repr(error)
+ + repr(error.args)
+ + repr(vars(error))
+ + "".join(traceback.format_exception(error))
+ )
+ assert secret not in rendered
+ return error
+
+
+def _replace_stored(manager, key, **fields):
+ """Model legacy stored state without passing through new write validation."""
+ if isinstance(manager, InMemorySettingsManager):
+ manager._settings[key].update(copy.deepcopy(fields))
+ else:
+ row = manager.db_session.query(Setting).filter(Setting.key == key).one()
+ for name, value in fields.items():
+ setattr(row, name, copy.deepcopy(value))
+ manager.db_session.commit()
+
+
+class TestInvalidStoredReads:
+ @pytest.mark.parametrize("storage", ["database", "memory"])
+ @pytest.mark.parametrize(
+ "value", ["bad-number", "", [1], {"bad": "number"}]
+ )
+ def test_invalid_selected_value_never_uses_default_or_raw_snapshot(
+ self, storage, value, make_db_manager
+ ):
+ manager = TestTypedReadsAndSnapshots._manager(storage, make_db_manager)
+ key = "llm.temperature"
+ _replace_stored(manager, key, value=value)
+ baseline = manager.get_all_settings(include_environment_overrides=False)
+ for read in (
+ lambda: manager.get_setting(key, default=0.8),
+ lambda: manager.get_setting("llm", default=0.8),
+ manager.get_all_settings,
+ manager.get_settings_snapshot,
+ ):
+ _assert_settings_error(read, key)
+ assert (
+ manager.get_all_settings(include_environment_overrides=False)
+ == baseline
+ )
+
+ @pytest.mark.parametrize("storage", ["database", "memory"])
+ def test_valid_environment_wins_over_invalid_lower_priority_store(
+ self, storage, make_db_manager, monkeypatch
+ ):
+ manager = TestTypedReadsAndSnapshots._manager(storage, make_db_manager)
+ key = "llm.temperature"
+ _replace_stored(manager, key, value="bad-number")
+ baseline = manager.get_all_settings(include_environment_overrides=False)
+ monkeypatch.setenv("LDR_LLM_TEMPERATURE", "0.25")
+ assert manager.get_setting(key, default=0.8) == 0.25
+ assert manager.get_all_settings()[key]["value"] == 0.25
+ assert manager.get_settings_snapshot()[key] == 0.25
+ _assert_settings_error(
+ lambda: manager.get_setting(key, check_env=False), key
+ )
+ assert (
+ manager.get_all_settings(include_environment_overrides=False)
+ == baseline
+ )
+
+ @pytest.mark.parametrize("storage", ["database", "memory"])
+ @pytest.mark.parametrize(
+ "key,ui_element,value",
+ [
+ ("llm.temperature", "number", 0),
+ ("app.enable_notifications", "checkbox", False),
+ ("app.host", "text", ""),
+ ("app.host", "json", []),
+ ("app.host", "json", {}),
+ ("app.host", "json", "hello"),
+ ("app.host", "json", ""),
+ ("app.host", "multiselect", []),
+ ],
+ )
+ def test_supported_values_are_not_missing(
+ self, storage, key, ui_element, value, make_db_manager
+ ):
+ manager = TestTypedReadsAndSnapshots._manager(storage, make_db_manager)
+ _replace_stored(manager, key, ui_element=ui_element, value=value)
+ for observed in (
+ manager.get_setting(key, default="not-missing"),
+ manager.get_all_settings()[key]["value"],
+ manager.get_settings_snapshot()[key],
+ ):
+ assert type(observed) is type(value)
+ assert observed == value
+
+ @pytest.mark.parametrize("storage", ["database", "memory"])
+ def test_json_environment_requires_encoding_without_changing_stored_json(
+ self, storage, make_db_manager, monkeypatch
+ ):
+ manager = TestTypedReadsAndSnapshots._manager(storage, make_db_manager)
+ key = "app.host"
+ _replace_stored(manager, key, ui_element="json", value={"stored": 1})
+ baseline = manager.get_all_settings(include_environment_overrides=False)
+ bad_json = "{private-json-sentinel-723"
+ monkeypatch.setenv("LDR_APP_HOST", bad_json)
+ for read in (
+ lambda: manager.get_setting(key, default={"fallback": True}),
+ manager.get_all_settings,
+ manager.get_settings_snapshot,
+ ):
+ _assert_settings_error(read, key, bad_json)
+ assert manager.get_setting(key, check_env=False) == {"stored": 1}
+ for encoded, expected in [
+ ('"hello"', "hello"),
+ ('{"valid": 2}', {"valid": 2}),
+ ]:
+ monkeypatch.setenv("LDR_APP_HOST", encoded)
+ assert manager.get_setting(key) == expected
+ assert manager.get_all_settings()[key]["value"] == expected
+ assert manager.get_settings_snapshot()[key] == expected
+ assert (
+ manager.get_all_settings(include_environment_overrides=False)
+ == baseline
+ )
+
+ @pytest.mark.parametrize("storage", ["database", "memory"])
+ @pytest.mark.parametrize(
+ "ui_element,stored",
+ [
+ ("json", "true"),
+ ("json", "42"),
+ ("json", "[1,2]"),
+ ("json", "hello"),
+ ("number", "42"),
+ ("checkbox", "false"),
+ ("multiselect", "a,b"),
+ ],
+ )
+ def test_validation_preserves_existing_snapshot_representation(
+ self, storage, ui_element, stored, make_db_manager
+ ):
+ manager = TestTypedReadsAndSnapshots._manager(storage, make_db_manager)
+ key = "app.host"
+ _replace_stored(manager, key, ui_element=ui_element, value=stored)
+ original = manager.get_all_settings(
+ include_environment_overrides=False
+ )[key]
+ effective = manager.get_all_settings()[key]
+ assert effective == original
+ assert manager.get_settings_snapshot()[key] == stored
+ assert type(manager.get_settings_snapshot()[key]) is str
+
+ @pytest.mark.parametrize("storage", ["database", "memory"])
+ def test_invalid_lock_allows_raw_export_but_stops_effective_reads(
+ self, storage, make_db_manager, monkeypatch
+ ):
+ manager = TestTypedReadsAndSnapshots._manager(storage, make_db_manager)
+ baseline = manager.get_all_settings(include_environment_overrides=False)
+ monkeypatch.setenv("LDR_APP_LOCK_SETTINGS", "invalid-lock-marker")
+ assert (
+ manager.get_all_settings(include_environment_overrides=False)
+ == baseline
+ )
+ for read in (
+ lambda: manager.get_setting("app.lock_settings", default=False),
+ manager.get_all_settings,
+ manager.get_settings_snapshot,
+ ):
+ _assert_settings_error(
+ read, "app.lock_settings", "invalid-lock-marker"
+ )
+
+ @pytest.mark.parametrize("storage", ["database", "memory"])
+ @pytest.mark.parametrize(
+ "raw", ["NaN", "Infinity", "-Infinity", '{"nested": NaN}']
+ )
+ def test_json_environment_rejects_nonfinite_constants(
+ self, storage, raw, make_db_manager, monkeypatch
+ ):
+ manager = TestTypedReadsAndSnapshots._manager(storage, make_db_manager)
+ key = "app.host"
+ _replace_stored(manager, key, ui_element="json", value={"stored": 1})
+ monkeypatch.setenv("LDR_APP_HOST", raw)
+ for read in (
+ lambda: manager.get_setting(key, default={"fallback": 2}),
+ manager.get_all_settings,
+ manager.get_settings_snapshot,
+ ):
+ _assert_settings_error(read, key, raw)
+ assert manager.get_setting(key, check_env=False) == {"stored": 1}
+
+
+class TestMemoryInvalidTypeReads:
+ @pytest.mark.parametrize("ui_element", ["custom_widget", None])
+ @pytest.mark.parametrize("stored", ["chosen-value", 0, False, None, [], {}])
+ def test_invalid_schema_is_rejected_before_writing(
+ self, ui_element, stored
+ ):
+ manager = InMemorySettingsManager()
+ key = "custom_read.value"
+ baseline = manager.get_all_settings(include_environment_overrides=False)
+ _assert_settings_error(
+ lambda: manager.create_or_update_setting(
+ {"key": key, "value": stored, "ui_element": ui_element}
+ ),
+ key,
+ )
+ assert (
+ manager.get_all_settings(include_environment_overrides=False)
+ == baseline
+ )
+
+ def test_invalid_schema_without_value_is_still_rejected(self):
+ manager = InMemorySettingsManager()
+ key = "custom_read.value"
+ _assert_settings_error(
+ lambda: manager.create_or_update_setting(
+ {"key": key, "ui_element": "custom_widget"}
+ ),
+ key,
+ )
+ assert key not in manager.get_all_settings(
+ include_environment_overrides=False
+ )
+
+ @pytest.mark.parametrize("ui_element", ["custom_widget", None])
+ @pytest.mark.parametrize("override", [None, "", "environment-value"])
+ def test_legacy_invalid_schema_fails_all_reads(
+ self, ui_element, override, monkeypatch
+ ):
+ manager = InMemorySettingsManager()
+ key = "custom_read.value"
+ manager._settings[key] = {
+ "value": "stored-value",
+ "ui_element": ui_element,
+ "editable": True,
+ }
+ baseline = manager.get_all_settings(include_environment_overrides=False)
+ if override is not None:
+ monkeypatch.setenv("LDR_CUSTOM_READ_VALUE", override)
+ for read in (
+ lambda: manager.get_setting(key, default="fallback"),
+ lambda: manager.get_setting(key, check_env=False),
+ lambda: manager.get_setting("custom_read", default="fallback"),
+ manager.get_all_settings,
+ manager.get_settings_snapshot,
+ ):
+ _assert_settings_error(read, key)
+ assert (
+ manager.get_all_settings(include_environment_overrides=False)
+ == baseline
+ )
+
+ def test_exact_entry_does_not_validate_unused_namespace_children(self):
+ manager = InMemorySettingsManager()
+ manager.create_or_update_setting(
+ {"key": "custom_read", "value": "exact", "ui_element": "text"}
+ )
+ manager._settings["custom_read.child"] = {
+ "value": "bad-number",
+ "ui_element": "number",
+ }
+ assert manager.get_setting("custom_read") == "exact"
+
+ @pytest.mark.parametrize(
+ "encoded,expected", [('"hello"', "hello"), ('""', "")]
+ )
+ def test_decoded_json_string_remains_readable_after_write(
+ self, encoded, expected
+ ):
+ manager = InMemorySettingsManager()
+ key = "custom_read.value"
+ manager.create_or_update_setting(
+ {"key": key, "value": encoded, "ui_element": "json"}
+ )
+ assert manager._settings[key]["value"] == expected
+ assert manager.get_setting(key) == expected
+ assert manager.get_all_settings()[key]["value"] == expected
+ assert manager.get_settings_snapshot()[key] == expected
+
+ def test_failed_write_does_not_mutate_stored_value(self, monkeypatch):
+ manager = InMemorySettingsManager()
+ baseline = manager.get_all_settings(include_environment_overrides=False)
+ monkeypatch.setenv("LDR_LLM_TEMPERATURE", "0.25")
+ _assert_settings_error(
+ lambda: manager.set_setting("llm.temperature", "bad-number"),
+ "llm.temperature",
+ )
+ assert (
+ manager.get_all_settings(include_environment_overrides=False)
+ == baseline
+ )
+
+
# ---------------------------------------------------------------------------
# 1. The one memoized value, and the caches that do not exist
# ---------------------------------------------------------------------------
@@ -551,56 +1095,25 @@ SCENARIOS: tuple[Scenario, ...] = (
Scenario(
"namespace_read_returns_a_mapping",
lambda m: m.get_setting("llm.google"),
- diverges=(
- "SettingsManager treats a dotted prefix as a namespace and "
- "returns {subkey: value}; InMemorySettingsManager matches "
- "exact keys only and returns the default. Any caller that "
- "reads a namespace works against one store and silently "
- "returns None against the other."
- ),
),
Scenario(
"env_var_for_a_key_absent_from_the_store",
lambda m: m.get_setting("zzz.not_a_setting", default="DEFAULT"),
env={"LDR_ZZZ_NOT_A_SETTING": "from-env"},
- diverges=(
- "SettingsManager checks the environment before returning the "
- "default argument; InMemorySettingsManager returns the "
- "default without ever looking, so an LDR_* override for a key "
- "it does not carry is dropped."
- ),
),
Scenario(
"env_only_setting",
lambda m: m.get_setting("testing.test_mode", default="DEFAULT"),
env={"LDR_TESTING_TEST_MODE": "true"},
- diverges=(
- "SettingsManager short-circuits env-only keys through "
- "env_registry; InMemorySettingsManager has no notion of the "
- "registry and returns the default."
- ),
),
Scenario(
"stored_null_falls_back_to_the_default_argument",
lambda m: m.get_setting("llm.google.api_key", default="FALLBACK"),
- diverges=(
- "get_typed_setting_value returns the caller's default when "
- "the stored value is null; InMemorySettingsManager._get_typed"
- "_value short-circuits on None and returns None, so every "
- "shipped null default (11 of them, all api_key-shaped) "
- "answers differently."
- ),
),
Scenario(
"unparseable_env_value_on_a_numeric_setting",
lambda m: m.get_setting("llm.temperature", default=0.7),
env={"LDR_LLM_TEMPERATURE": "not-a-number"},
- diverges=(
- "SettingsManager falls back to the stored value when the env "
- "string will not coerce; InMemorySettingsManager returns the "
- "raw string, so a numeric setting comes back as str and "
- "blows up at the arithmetic instead of at the read."
- ),
),
Scenario(
"write_to_an_environment_locked_key",
diff --git a/tests/settings/test_snapshot_stored_values.py b/tests/settings/test_snapshot_stored_values.py
new file mode 100644
index 0000000000..7b0f5628d4
--- /dev/null
+++ b/tests/settings/test_snapshot_stored_values.py
@@ -0,0 +1,57 @@
+"""Strict snapshot validation preserves valid native database representations."""
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import Session
+
+from local_deep_research.database.models.settings import Setting, SettingType
+from local_deep_research.settings.manager import SettingsManager
+
+
+ "stored, direct_value", [("true", True), ("42", 42), ("[1,2]", [1, 2])]
+)
+def test_snapshot_keeps_native_json_string_while_validating(
+ tmp_path, monkeypatch, stored, direct_value
+):
+ """Reading snapshots must not decode an already-native JSON-column string."""
+ monkeypatch.delenv("LDR_TEST_NATIVE_JSON", raising=False)
+ engine = create_engine(f"sqlite:///{tmp_path / 'settings.sqlite'}")
+ Setting.__table__.create(engine)
+ try:
+ with Session(engine) as session:
+ row = Setting(
+ key="test.native_json",
+ value=stored,
+ type=SettingType.APP,
+ name="Stored JSON",
+ ui_element="json",
+ )
+ session.add(row)
+ session.commit()
+ manager = SettingsManager(session, seed_defaults=False)
+ manager.__dict__["default_settings"] = {}
+ try:
+ # The direct getter's existing encoded/native ambiguity is
+ # preserved; it must not spread to the full/flat snapshots.
+ direct = manager.get_setting(row.key)
+ assert direct == direct_value
+ assert type(direct) is type(direct_value)
+
+ full = manager.get_all_settings()
+ flat = manager.get_settings_snapshot()
+ assert full[row.key]["value"] == stored
+ assert isinstance(full[row.key]["value"], str)
+ assert full[row.key]["ui_element"] == "json"
+ assert flat[row.key] == stored
+ assert isinstance(flat[row.key], str)
+
+ session.expire_all()
+ saved = session.query(Setting).filter_by(key=row.key).one()
+ assert saved.value == stored
+ assert isinstance(saved.value, str)
+ assert saved.ui_element == "json"
+ finally:
+ manager.close()
+ finally:
+ engine.dispose()
diff --git a/tests/settings/test_strict_trusted_proxy_setting.py b/tests/settings/test_strict_trusted_proxy_setting.py
new file mode 100644
index 0000000000..9616830d5c
--- /dev/null
+++ b/tests/settings/test_strict_trusted_proxy_setting.py
@@ -0,0 +1,74 @@
+"""Managed reads preserve the shipped trusted-proxy integer contract."""
+
+import traceback
+
+import pytest
+
+from local_deep_research.api.settings_utils import InMemorySettingsManager
+from local_deep_research.settings.exceptions import SettingsValueError
+from local_deep_research.settings.manager import SettingsManager
+
+
+KEY = "server.trusted_proxy_count"
+ENV_VAR = "LDR_SERVER_TRUSTED_PROXY_COUNT"
+
+
[email protected](params=["database", "memory"])
+def read_setting(request):
+ if request.param == "database":
+ manager = SettingsManager(db_session=None)
+ request.addfinalizer(manager.close)
+ else:
+ manager = InMemorySettingsManager()
+ request.addfinalizer(manager._base_manager.close)
+ return manager.get_setting
+
+
+ "raw",
+ ["invalid-proxy-private-marker", "1_0", "+3", "٣", "17", "-1"],
+)
+def test_managed_proxy_count_rejects_invalid_literals_and_ranges(
+ read_setting, monkeypatch, raw
+):
+ monkeypatch.setenv(ENV_VAR, raw)
+
+ with pytest.raises(SettingsValueError) as error:
+ read_setting(KEY, default=9)
+
+ assert error.value.key == KEY
+ assert error.value.source == "environment"
+ assert error.value.__context__ is None
+ assert error.value.__cause__ is None
+ assert raw not in str(error.value)
+ assert "invalid-proxy-private-marker" not in "".join(
+ traceback.format_exception(error.value)
+ )
+
+
+ "raw, expected", [("0", 0), ("-0", 0), ("16", 16), (" 4 ", 4)]
+)
+def test_managed_proxy_count_accepts_plain_ascii_values(
+ read_setting, monkeypatch, raw, expected
+):
+ monkeypatch.setenv(ENV_VAR, raw)
+ assert read_setting(KEY, default=9) == expected
+
+
[email protected]("raw", [None, "", " \t"])
+def test_managed_proxy_count_inherits_registered_default_when_unset(
+ read_setting, monkeypatch, raw
+):
+ if raw is None:
+ monkeypatch.delenv(ENV_VAR, raising=False)
+ else:
+ monkeypatch.setenv(ENV_VAR, raw)
+ assert read_setting(KEY, default=9) == 0
+
+
+def test_managed_proxy_count_can_disable_environment_lookup(
+ read_setting, monkeypatch
+):
+ monkeypatch.setenv(ENV_VAR, "invalid-proxy-private-marker")
+ assert read_setting(KEY, default=9, check_env=False) == 0
diff --git a/tests/test_api_settings_validation.py b/tests/test_api_settings_validation.py
index 95421a8e68..a0b6213583 100644
--- a/tests/test_api_settings_validation.py
+++ b/tests/test_api_settings_validation.py
@@ -8,6 +8,7 @@ from local_deep_research.api.settings_utils import (
create_settings_snapshot,
)
from local_deep_research.api import quick_summary
+from local_deep_research.settings.exceptions import SettingsValueError
class TestSettingsValidation:
@@ -163,21 +164,34 @@ class TestEnvironmentVariableIntegration:
temp = manager.get_setting("llm.temperature")
assert isinstance(temp, float)
assert temp == 0.7
-
- # Note: The current implementation may not convert all types
- # This test documents expected behavior
-
- def test_invalid_environment_variable_values(self, monkeypatch):
- """Test handling of invalid env var values."""
- # Set invalid values
- monkeypatch.setenv("LDR_LLM_TEMPERATURE", "not_a_number")
- monkeypatch.setenv("LDR_SEARCH_MAX_RESULTS", "abc")
-
+ assert manager.get_setting("search.max_results") == 15
+
+ @pytest.mark.parametrize(
+ ("key", "env_var", "stored", "invalid"),
+ [
+ ("llm.temperature", "LDR_LLM_TEMPERATURE", 0.7, "not_a_number"),
+ ("search.max_results", "LDR_SEARCH_MAX_RESULTS", 15, "abc"),
+ ],
+ )
+ def test_invalid_environment_variable_values_raise(
+ self, monkeypatch, key, env_var, stored, invalid
+ ):
+ """An invalid override cannot select a stored value or caller default."""
+ monkeypatch.delenv(env_var, raising=False)
manager = InMemorySettingsManager()
-
- # Should handle gracefully - either use default or store as string
- temp = manager.get_setting("llm.temperature")
- assert temp is not None # Should have some value
+ assert manager.set_setting(key, stored)
+ assert manager.get_setting(key) == stored
+
+ monkeypatch.setenv(env_var, invalid)
+ with pytest.raises(SettingsValueError) as raised:
+ manager.get_setting(key, default=1)
+
+ assert raised.value.key == key
+ assert raised.value.source == "environment"
+ assert invalid not in str(raised.value)
+ assert raised.value.__cause__ is None
+ assert raised.value.__context__ is None
+ assert manager.get_setting(key, check_env=False) == stored
def test_environment_variable_precedence(self, monkeypatch):
"""Test precedence of env vars vs explicit settings."""
diff --git a/tests/test_config_env_var_contracts.py b/tests/test_config_env_var_contracts.py
index 120e477c34..376bec9e65 100644
--- a/tests/test_config_env_var_contracts.py
+++ b/tests/test_config_env_var_contracts.py
@@ -45,6 +45,7 @@ import pytest
from local_deep_research.settings import env_definitions
from local_deep_research.settings.env_registry import registry as env_registry
from local_deep_research.settings.env_settings import BooleanSetting, EnvSetting
+from local_deep_research.settings.exceptions import SettingsValueError
from local_deep_research.settings.manager import (
check_env_setting,
get_typed_setting_value,
@@ -990,7 +991,7 @@ def test_boolean_vocabulary_sweep_found_the_hand_rolled_parsers():
def test_no_truthy_vocabulary_admits_a_falsy_token():
- """``0`` / ``false`` / ``no`` / ``off`` / ``""`` must never enable.
+ """``0`` / ``false`` / ``no`` / ``off`` / ``disabled`` / ``""`` never enable.
The port has at least seven independent string-to-bool implementations
(``to_bool``, ``BooleanSetting``, ``parse_boolean``,
@@ -1002,7 +1003,7 @@ def test_no_truthy_vocabulary_admits_a_falsy_token():
inconsistency is merely confusing. What would be a security defect is
any of them treating a falsy spelling as *yes*. Sweep them all.
"""
- falsy = {"0", "false", "no", "off", ""}
+ falsy = {"0", "false", "no", "off", "disabled", ""}
offenders = [
(rel, line, values)
for rel, line, values in BOOLEAN_VOCABULARIES
@@ -1017,57 +1018,40 @@ def test_no_truthy_vocabulary_admits_a_falsy_token():
)
-def test_env_override_of_a_checkbox_setting_uses_html_form_semantics():
- """``LDR_APP_DEBUG=disabled`` enables debug. This is the sharp edge.
+def test_html_checkbox_parser_keeps_form_semantics():
+ """Form posts keep HTML semantics; environment reads validate tokens.
- Env overrides for ``ui_element="checkbox"`` settings flow through
- ``settings.manager.parse_boolean``, which implements HTML checkbox
- semantics on purpose: only ``off/false/0/""/no`` are falsy and *every
- other non-empty string is True*. That is defensible for form posts,
- but an environment variable is not a form post, and an operator writing
- ``LDR_APP_DEBUG=disabled`` (or ``none``, or a typo like ``flase``) turns
- debug **on**.
-
- ``web/server_config.py`` recognises the hazard and guards exactly one
- variable -- ``LDR_APP_ALLOW_REGISTRATIONS`` gets an explicit
- fail-closed check against a recognised-boolean set. No equivalent
- guard exists for ``app.debug`` or any other checkbox setting.
+ ``parse_boolean`` remains the generic form/stored-value parser, where
+ arbitrary non-empty checkbox values are true. Managed environment
+ overrides are checked separately and must not inherit that permissive
+ behavior.
"""
for spelling in ("off", "false", "0", "no", ""):
assert parse_boolean(spelling) is False
for spelling in ("disabled", "none", "flase", "2"):
- assert parse_boolean(spelling) is True, (
- "parse_boolean tightened; the asymmetry described here is gone"
- )
-
+ assert parse_boolean(spelling) is True
-def test_app_debug_env_override_has_no_fail_closed_guard(monkeypatch):
- """Executable proof of the asymmetry described above.
- ``get_typed_setting_value`` with ``value=None`` short-circuits on the
- environment and never touches a database.
- """
+def test_app_debug_disabled_env_overrides_true_stored_value(monkeypatch):
+ """The explicit false environment token overrides lower-priority true."""
monkeypatch.setenv("LDR_APP_DEBUG", "disabled")
assert check_env_setting("app.debug") == "disabled"
result = get_typed_setting_value(
- "app.debug", None, "checkbox", default=False
- )
- assert result is True, (
- "LDR_APP_DEBUG=disabled no longer enables debug -- a fail-closed "
- "guard was added; update this test"
+ "app.debug", True, "checkbox", default=True
)
+ assert result is False
- guard_source = (SRC_PKG / "web" / "server_config.py").read_text(
- encoding="utf-8"
- )
- assert "_RECOGNIZED_BOOL_VALUES" in guard_source
- assert 'os.getenv("LDR_APP_ALLOW_REGISTRATIONS")' in guard_source, (
- "the only fail-closed env-boolean guard in server_config.py moved"
- )
- assert 'os.getenv("LDR_APP_DEBUG")' not in guard_source, (
- "LDR_APP_DEBUG gained a guard -- the asymmetry is fixed"
- )
+
[email protected]("spelling", ["flase", "none", "2"])
+def test_app_debug_invalid_env_cannot_select_stored_or_default(
+ monkeypatch, spelling
+):
+ monkeypatch.setenv("LDR_APP_DEBUG", spelling)
+ with pytest.raises(SettingsValueError) as error:
+ get_typed_setting_value("app.debug", True, "checkbox", default=True)
+ assert error.value.key == "app.debug"
+ assert error.value.source == "environment"
def test_empty_env_var_is_treated_as_unset_not_as_false(monkeypatch):
diff --git a/tests/test_settings_manager.py b/tests/test_settings_manager.py
index 650b28921f..43a87de4fc 100644
--- a/tests/test_settings_manager.py
+++ b/tests/test_settings_manager.py
@@ -9,6 +9,7 @@ from local_deep_research.settings.manager import (
check_env_setting,
)
from local_deep_research.database.models import Setting, SettingType
+from local_deep_research.settings.exceptions import SettingsValueError
def test_check_env_setting_exists(monkeypatch):
@@ -124,7 +125,7 @@ def test_get_setting_default(mocker):
def test_get_setting_invalid_type(mocker):
"""
Tests that when a setting's value cannot be converted to the type
- specified by the `ui_element`, it will always return the default value.
+ specified by the `ui_element`, it raises instead of selecting a default.
Args:
mocker: The fixture to use for mocking.
@@ -141,10 +142,11 @@ def test_get_setting_invalid_type(mocker):
# Act: Call get_setting with a default value and an invalid type
settings_manager = SettingsManager(db_session=mock_db_session)
- result = settings_manager.get_setting("test.invalid_type", default=10)
-
- # Assert: Check that the default value is returned and not the invalid string
- assert result == 10
+ with pytest.raises(SettingsValueError) as error:
+ settings_manager.get_setting("test.invalid_type", default=10)
+ assert error.value.key == "test.invalid_type"
+ assert error.value.source == "value"
+ assert "not_a_number" not in str(error.value)
# The mocker fixture is automatically available
diff --git a/tests/web/routers/test_api_v1_untyped_env_settings.py b/tests/web/routers/test_api_v1_untyped_env_settings.py
new file mode 100644
index 0000000000..b718a389f5
--- /dev/null
+++ b/tests/web/routers/test_api_v1_untyped_env_settings.py
@@ -0,0 +1,127 @@
+"""Untyped environment overrides reach ``require_api_access`` unconverted.
+
+``app.api_rate_limit`` and ``app.enable_api`` have no defaults entry, and
+nothing seeds a row for either, so a fresh account has none.
+``require_api_access`` reads both on every ``/api/v1`` request. Strict
+settings reads keep an override for such an untyped key as the raw string,
+as main did: raising for it turned every API request into a 500 whenever
+the operator set ``LDR_APP_API_RATE_LIMIT`` or ``LDR_APP_ENABLE_API``.
+"""
+
+import asyncio
+from contextlib import nullcontext
+from types import SimpleNamespace
+
+import pytest
+from fastapi import HTTPException
+from sqlalchemy import create_engine
+from sqlalchemy.orm import Session
+from sqlalchemy.pool import StaticPool
+
+from local_deep_research.database.models.settings import Setting
+from local_deep_research.settings.manager import SettingsManager
+from local_deep_research.web.dependencies import rate_limit
+from local_deep_research.web.dependencies.rate_limit import limiter
+from local_deep_research.web.routers import api_v1
+
+DOCS = "/api/v1/"
+
+
[email protected](autouse=True)
+def _no_untyped_overrides(monkeypatch):
+ for name in ("LDR_APP_API_RATE_LIMIT", "LDR_APP_ENABLE_API"):
+ monkeypatch.delenv(name, raising=False)
+
+
+def rowless_settings(monkeypatch):
+ """A real ``SettingsManager`` over a settings table with no rows.
+
+ ``require_api_access`` reads through ``run_db_sync``, so the manager is
+ built in that worker thread (a manager refuses use from another
+ thread), over one shared in-memory connection.
+ """
+ engine = create_engine(
+ "sqlite://",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ Setting.__table__.create(engine)
+ session = Session(engine)
+ monkeypatch.setattr(
+ api_v1, "get_user_db_session", lambda *a, **k: nullcontext(session)
+ )
+ monkeypatch.setattr(
+ api_v1,
+ "get_settings_manager",
+ lambda *a: SettingsManager(session, seed_defaults=False),
+ )
+ manager = SettingsManager(session, seed_defaults=False)
+ try:
+ assert session.query(Setting).count() == 0
+ yield manager
+ finally:
+ manager.close()
+ session.close()
+ engine.dispose()
+
+
+def _admit():
+ """Run the dependency; return the user and the limit it cached."""
+
+ async def admit():
+ username = await api_v1.require_api_access(SimpleNamespace(), "alice")
+ return username, rate_limit._api_rate_limit_ctx.get()
+
+ return asyncio.run(admit())
+
+
+def test_untyped_rate_limit_override_is_cached_as_on_main(
+ rowless_settings, monkeypatch
+):
+ monkeypatch.setenv("LDR_APP_API_RATE_LIMIT", "120")
+
+ assert rowless_settings.get_setting("app.api_rate_limit", 60) == "120"
+ assert _admit() == ("alice", 120)
+
+
+def test_untyped_enable_api_override_disables_the_api_as_on_main(
+ rowless_settings, monkeypatch
+):
+ monkeypatch.setenv("LDR_APP_ENABLE_API", "false")
+
+ assert rowless_settings.get_bool_setting("app.enable_api", True) is False
+ with pytest.raises(HTTPException) as refused:
+ _admit()
+ assert refused.value.status_code == 403
+
+
+def test_rate_limit_override_applies_to_real_api_requests(
+ authenticated_client, monkeypatch
+):
+ monkeypatch.setenv("LDR_APP_API_RATE_LIMIT", "2")
+ original_enabled = limiter.enabled
+ limiter.enabled = True
+ limiter.reset()
+ try:
+ statuses = [
+ authenticated_client.get(DOCS).status_code for _ in range(4)
+ ]
+ finally:
+ limiter.enabled = original_enabled
+ limiter.reset()
+
+ # Before: SettingsValueError in require_api_access, a 500 every time.
+ assert 500 not in statuses, statuses
+ assert statuses[:2] == [200, 200], statuses
+ assert 429 in statuses, statuses
+
+
+def test_enable_api_override_refuses_real_api_requests(
+ authenticated_client, monkeypatch
+):
+ monkeypatch.setenv("LDR_APP_ENABLE_API", "false")
+
+ response = authenticated_client.get(DOCS)
+
+ assert response.status_code == 403, response.text[:300]
diff --git a/tests/web/routers/test_invalid_setting_responses.py b/tests/web/routers/test_invalid_setting_responses.py
new file mode 100644
index 0000000000..cd3e130c0f
--- /dev/null
+++ b/tests/web/routers/test_invalid_setting_responses.py
@@ -0,0 +1,315 @@
+"""Invalid configured settings reach clients as repair diagnostics.
+
+``SettingsValueError`` names the setting key, its source and a fixed reason.
+The settings loaders and research start return that diagnostic instead of a
+generic error. The engine list is never served without its egress filter,
+and research start never reports a server-side configuration error as a bad
+request field or skips its egress precheck.
+"""
+
+import json
+from contextlib import nullcontext
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+
+from local_deep_research.settings.exceptions import SettingsValueError
+
+_SECRET = "planted-secret-value"
+
+# Every field the start route would otherwise read from settings, so a
+# test controls exactly which settings read runs.
+_FULL_REQUEST = {
+ "query": "q",
+ "model_provider": "ollama",
+ "model": "m",
+ "ollama_url": "http://localhost:11434",
+ "search_engine": "searxng",
+ "iterations": 1,
+ "questions_per_iteration": 1,
+ "strategy": "source-based",
+}
+
+
+def settings_error():
+ return SettingsValueError(
+ "llm.temperature",
+ source="environment",
+ reason="expected a valid number value",
+ )
+
+
+def _body(response):
+ return json.loads(response.body)
+
+
+def _reads_raising(key, error):
+ """A ``get_setting`` that raises ``error`` for ``key`` only."""
+
+ def read(setting_key, default=None, *args, **kwargs):
+ if setting_key == key:
+ raise error
+ return default
+
+ return read
+
+
+def test_diagnostic_is_the_value_free_message(settings_error):
+ assert settings_error.diagnostic == str(settings_error)
+ assert settings_error.diagnostic == (
+ "Invalid setting 'llm.temperature' from environment: "
+ "expected a valid number value"
+ )
+
+
+# ---------------------------------------------------------------------------
+# GET /settings/api/available-search-engines
+# ---------------------------------------------------------------------------
+
+
+def engine_route(monkeypatch):
+ from local_deep_research.web.routers import settings as router
+ from local_deep_research.web_search_engines import search_engines_config
+
+ manager = Mock()
+ manager.get_setting.return_value = []
+ monkeypatch.setattr(
+ router, "get_user_db_session", lambda *a, **k: nullcontext(Mock())
+ )
+ monkeypatch.setattr(router, "get_settings_manager", lambda *a: manager)
+ monkeypatch.setattr(
+ search_engines_config,
+ "search_config",
+ lambda **kwargs: {
+ "probe": {"display_name": "Probe", "requires_api_key": False}
+ },
+ )
+ classify = Mock()
+ overlay = Mock()
+ monkeypatch.setattr(router, "_classify_options_for_egress", classify)
+ monkeypatch.setattr(router, "_apply_guarded_url_overlay", overlay)
+
+ def call(query_params):
+ request = SimpleNamespace(query_params=query_params)
+ return router.api_get_available_search_engines(request, "alice")
+
+ return SimpleNamespace(
+ manager=manager, call=call, classify=classify, overlay=overlay
+ )
+
+
+ "query",
+ [{}, {"egress_scope": "public_only", "primary": "probe"}],
+ ids=["url-overlay-only", "scope-filter"],
+)
+def test_engine_list_is_not_served_unfiltered_for_an_invalid_setting(
+ engine_route, settings_error, query
+):
+ engine_route.manager.get_settings_snapshot.side_effect = settings_error
+
+ response = engine_route.call(query)
+
+ assert response.status_code == 500
+ assert _body(response) == {"error": str(settings_error)}
+ # Neither filter ran on a substitute empty policy.
+ engine_route.classify.assert_not_called()
+ engine_route.overlay.assert_not_called()
+
+
+def test_engine_list_fails_closed_when_the_snapshot_cannot_be_read(
+ engine_route,
+):
+ engine_route.manager.get_settings_snapshot.side_effect = RuntimeError(
+ _SECRET
+ )
+
+ response = engine_route.call({"egress_scope": "private_only"})
+
+ assert response.status_code == 500
+ assert _body(response) == {"error": "Failed to retrieve search engines"}
+ assert _SECRET not in response.body.decode()
+ engine_route.classify.assert_not_called()
+
+
+def test_engine_list_control_valid_snapshot_is_filtered(engine_route):
+ snapshot = {"policy.egress_scope": "adaptive"}
+ engine_route.manager.get_settings_snapshot.return_value = snapshot
+
+ result = engine_route.call({"egress_scope": "public_only"})
+
+ assert [option["value"] for option in result["engine_options"]] == ["probe"]
+ engine_route.classify.assert_called_once()
+ assert engine_route.classify.call_args.kwargs["settings_snapshot"] == (
+ snapshot
+ )
+
+
+# ---------------------------------------------------------------------------
+# GET /settings/api and GET /settings/api/{key}
+# ---------------------------------------------------------------------------
+
+
[email protected]("route", ["all", "single"])
+def test_settings_reads_return_the_repair_diagnostic(
+ monkeypatch, settings_error, route
+):
+ from local_deep_research.web.routers import settings as router
+
+ session = Mock()
+ session.query.return_value.filter.return_value.first.return_value = (
+ SimpleNamespace(
+ key="llm.temperature",
+ value=_SECRET,
+ ui_element="number",
+ editable=True,
+ )
+ )
+ manager = Mock()
+ manager.get_all_settings.side_effect = settings_error
+ monkeypatch.setattr(
+ router, "get_user_db_session", lambda *a, **k: nullcontext(session)
+ )
+ monkeypatch.setattr(router, "get_settings_manager", lambda *a: manager)
+ request = SimpleNamespace(query_params={})
+
+ if route == "all":
+ response = router.api_get_all_settings(request, "alice")
+ else:
+ response = router.api_get_db_setting(
+ request, "llm.temperature", "alice"
+ )
+
+ assert response.status_code == 500
+ assert _body(response) == {"error": str(settings_error)}
+ assert _SECRET not in response.body.decode()
+
+
+# ---------------------------------------------------------------------------
+# Research start
+# ---------------------------------------------------------------------------
+
+
+def research_route(monkeypatch):
+ from local_deep_research import settings as settings_package
+ from local_deep_research.web.routers import research
+
+ monkeypatch.delenv("LDR_POLICY_EGRESS_SCOPE", raising=False)
+ manager = Mock()
+ monkeypatch.setattr(
+ research, "get_user_db_session", lambda *a, **k: nullcontext(Mock())
+ )
+ monkeypatch.setattr(
+ settings_package, "SettingsManager", lambda *a, **k: manager
+ )
+ return SimpleNamespace(research=research, manager=manager)
+
+
+def test_invalid_setting_is_not_reported_as_a_bad_request_field(
+ research_route,
+):
+ error = SettingsValueError(
+ "search.iterations",
+ source="environment",
+ reason="expected a valid number value",
+ )
+ research_route.manager.get_setting.side_effect = _reads_raising(
+ "search.iterations", error
+ )
+ data = {k: v for k, v in _FULL_REQUEST.items() if k != "iterations"}
+
+ response = research_route.research._start_research_sync(
+ data, "alice", "http://testserver", None
+ )
+
+ # Before: 400 "iterations must be an integer between ...", a request
+ # field the client never sent.
+ assert response.status_code == 500
+ assert _body(response) == {
+ "status": "error",
+ "message": str(error),
+ }
+
+
+def test_invalid_concurrency_limit_does_not_skip_admission(
+ research_route, monkeypatch
+):
+ research = research_route.research
+ error = SettingsValueError(
+ "app.max_concurrent_researches",
+ source="value",
+ reason="expected a valid number value",
+ )
+ research_route.manager.get_setting.side_effect = _reads_raising(
+ "app.max_concurrent_researches", error
+ )
+ monkeypatch.setattr(
+ research, "_precheck_engine_policy", Mock(return_value=None)
+ )
+ monkeypatch.setattr(
+ research,
+ "_precheck_collection_agent_enabled",
+ Mock(return_value=None),
+ )
+ monkeypatch.setattr(
+ research, "user_research_start_gate", lambda *a: nullcontext()
+ )
+ password = Mock(return_value=(None, True))
+ monkeypatch.setattr(research, "resolve_user_password", password)
+
+ response = research._start_research_sync(
+ dict(_FULL_REQUEST), "alice", "http://testserver", None
+ )
+
+ assert response.status_code == 500
+ assert _body(response)["message"] == str(error)
+ # Before: the error became should_queue=False and the start continued.
+ password.assert_not_called()
+
+
+def test_precheck_refuses_instead_of_skipping_for_an_invalid_snapshot(
+ settings_error,
+):
+ from local_deep_research.web.routers.research import (
+ _precheck_engine_policy,
+ )
+
+ manager = Mock()
+ manager.get_settings_snapshot.side_effect = settings_error
+
+ response = _precheck_engine_policy(manager, {}, "searxng", "alice")
+
+ # Before: None, so the run started without the egress precheck.
+ assert response is not None
+ assert response.status_code == 500
+ assert _body(response)["message"] == str(settings_error)
+
+
+def test_precheck_reports_a_settings_error_raised_by_policy_evaluation(
+ monkeypatch, settings_error
+):
+ from local_deep_research.security.egress import policy
+ from local_deep_research.web.routers.research import (
+ _precheck_engine_policy,
+ )
+
+ monkeypatch.delenv("LDR_POLICY_EGRESS_SCOPE", raising=False)
+ monkeypatch.setattr(
+ policy, "context_from_snapshot", Mock(side_effect=settings_error)
+ )
+ manager = Mock()
+ manager.get_settings_snapshot.return_value = {
+ "policy.egress_scope": "adaptive",
+ "search.tool": "searxng",
+ }
+
+ response = _precheck_engine_policy(manager, {}, "searxng", "alice")
+
+ # Before: 400 "Egress policy refused this run due to an invalid policy
+ # configuration", whichever setting was invalid.
+ assert response.status_code == 500
+ assert _body(response)["message"] == str(settings_error)
diff --git a/tests/web/routers/test_rag_invalid_settings.py b/tests/web/routers/test_rag_invalid_settings.py
new file mode 100644
index 0000000000..f53aff303f
--- /dev/null
+++ b/tests/web/routers/test_rag_invalid_settings.py
@@ -0,0 +1,142 @@
+"""Invalid indexing settings must not schedule work with substitute values."""
+
+from contextlib import nullcontext
+from importlib import import_module
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.orm import Session
+
+from local_deep_research.database.models.queue import TaskMetadata
+from local_deep_research.database.models.settings import Setting, SettingType
+from local_deep_research.settings.exceptions import SettingsValueError
+from local_deep_research.settings.manager import SettingsManager
+
+
+def indexing_settings(monkeypatch):
+ from local_deep_research.database import session_context
+ from local_deep_research.utilities import db_utils
+ from local_deep_research.web.routers import rag
+
+ # Indexing lazily imports this package, whose sibling deletion services
+ # bind get_user_db_session at import time. Load them before patching the
+ # shared helper so later HTTP tests cannot inherit this fixture's session.
+ import_module(
+ "local_deep_research.research_library.deletion.utils.cascade_helper"
+ )
+
+ monkeypatch.delenv("LDR_RAG_INDEXING_MAX_PARALLEL_DOCS", raising=False)
+ monkeypatch.delenv("LDR_RESEARCH_LIBRARY_AUTO_INDEX_ENABLED", raising=False)
+ engine = create_engine("sqlite:///:memory:")
+ Setting.__table__.create(engine)
+ TaskMetadata.__table__.create(engine)
+ try:
+ with Session(engine) as session:
+ row = Setting(
+ key="rag.indexing_max_parallel_docs",
+ name="Parallel documents",
+ value=1,
+ type=SettingType.APP,
+ ui_element="number",
+ )
+ session.add(row)
+ session.commit()
+ manager = SettingsManager(session, seed_defaults=False)
+ monkeypatch.setattr(
+ session_context,
+ "get_user_db_session",
+ lambda *args: nullcontext(session),
+ )
+ monkeypatch.setattr(
+ db_utils, "get_settings_manager", lambda *args: manager
+ )
+ monkeypatch.setattr(
+ rag, "get_settings_manager", lambda *args: manager
+ )
+ monkeypatch.setattr(rag, "get_rag_service", Mock())
+ executor = Mock()
+ monkeypatch.setattr(
+ rag, "_get_auto_index_executor", lambda: executor
+ )
+ reserve_slot = Mock(return_value=True)
+ monkeypatch.setattr(
+ rag, "_try_reserve_auto_index_slot", reserve_slot
+ )
+ thread = Mock()
+ monkeypatch.setattr(rag.threading, "Thread", thread)
+ try:
+ yield SimpleNamespace(
+ rag=rag,
+ session=session,
+ row=row,
+ executor=executor,
+ reserve_slot=reserve_slot,
+ thread=thread,
+ )
+ finally:
+ manager.close()
+ finally:
+ engine.dispose()
+
+
[email protected]("source", ["environment", "value"])
+ "entrypoint",
+ ["index_all", "index_collection", "auto", "background", "background_force"],
+)
+def test_invalid_parallelism_stops_before_scheduling(
+ indexing_settings, monkeypatch, source, entrypoint
+):
+ state = indexing_settings
+ invalid = "invalid-parallelism"
+ if source == "environment":
+ monkeypatch.setenv("LDR_RAG_INDEXING_MAX_PARALLEL_DOCS", invalid)
+ else:
+ state.row.value = invalid
+ state.session.commit()
+
+ if entrypoint in ("index_all", "index_collection"):
+ request = SimpleNamespace(
+ query_params={"collection_id": "collection"}, session={}
+ )
+ with pytest.raises(SettingsValueError) as raised:
+ if entrypoint == "index_all":
+ state.rag.index_all(request, "test-user")
+ else:
+ state.rag.index_collection(request, "collection", "test-user")
+ assert raised.value.key == "rag.indexing_max_parallel_docs"
+ assert raised.value.source == source
+ elif entrypoint == "auto":
+ # Automatic indexing logs the configuration error and aborts.
+ state.rag.trigger_auto_index(
+ ["document"], "collection", "test-user", None
+ )
+ else:
+ response = state.rag._start_background_index_sync(
+ "collection", "test-user", None, entrypoint == "background_force"
+ )
+ assert response.status_code == 500
+
+ state.executor.submit.assert_not_called()
+ state.reserve_slot.assert_not_called()
+ state.thread.assert_not_called()
+ assert state.session.query(TaskMetadata).count() == 0
+ state.session.refresh(state.row)
+ assert state.row.value == (1 if source == "environment" else invalid)
+
+
[email protected]("override, expected", [(None, 1), ("2", 2)])
+def test_auto_index_keeps_configured_parallelism(
+ indexing_settings, monkeypatch, override, expected
+):
+ state = indexing_settings
+ if override is not None:
+ monkeypatch.setenv("LDR_RAG_INDEXING_MAX_PARALLEL_DOCS", override)
+ state.rag.trigger_auto_index(["document"], "collection", "test-user", None)
+ state.executor.submit.assert_called_once()
+ assert state.executor.submit.call_args.args[-1] == expected
+ state.session.refresh(state.row)
+ assert state.row.value == 1
diff --git a/tests/web/routers/test_request_path_settings_errors.py b/tests/web/routers/test_request_path_settings_errors.py
new file mode 100644
index 0000000000..2d2a00eeb3
--- /dev/null
+++ b/tests/web/routers/test_request_path_settings_errors.py
@@ -0,0 +1,184 @@
+"""Request paths must report an invalid setting, not work around it.
+
+A strict settings read raises ``SettingsValueError`` for an invalid
+configured value. These request paths used to catch every exception and
+render defaults, skip the subscription egress check, or (the root page, see
+tests/web/test_root_route_failure_recovery.py) log the user out. Each now
+lets the error reach the app's handler, which answers with the value-free
+diagnostic, or refuses the operation naming the setting.
+"""
+
+from contextlib import nullcontext
+from types import SimpleNamespace
+from unittest.mock import MagicMock, Mock, patch
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from starlette.requests import Request
+
+from local_deep_research.settings.exceptions import SettingsValueError
+
+SETTINGS_MANAGER = "local_deep_research.utilities.db_utils.get_settings_manager"
+
+
+def _error(key="search.iterations", source="value"):
+ return SettingsValueError(
+ key, source=source, reason="expected a valid number value"
+ )
+
+
+# ---------------------------------------------------------------------------
+# The app's SettingsValueError handler
+# ---------------------------------------------------------------------------
+
+
[email protected](scope="module")
+def handler_client():
+ from local_deep_research.web.fastapi_app import (
+ _register_exception_handlers,
+ )
+
+ mini = FastAPI()
+ _register_exception_handlers(mini)
+
+ @mini.get("/api/settings-boom")
+ async def api_boom():
+ raise _error()
+
+ @mini.get("/page-boom")
+ async def page_boom():
+ raise _error(source="environment")
+
+ @mini.get("/api/plain-value-error")
+ async def plain_value_error():
+ raise ValueError("internal detail")
+
+ return TestClient(mini, raise_server_exceptions=False)
+
+
+def test_api_request_gets_the_diagnostic(handler_client):
+ response = handler_client.get("/api/settings-boom")
+
+ assert response.status_code == 500
+ assert response.json() == {"error": str(_error())}
+
+
+def test_page_request_gets_the_diagnostic(handler_client):
+ response = handler_client.get("/page-boom", headers={"accept": "text/html"})
+
+ assert response.status_code == 500
+ assert "search.iterations" in response.text
+ assert "from environment" in response.text
+ assert "expected a valid number value" in response.text
+
+
+def test_other_value_errors_keep_the_generic_body(handler_client):
+ response = handler_client.get("/api/plain-value-error")
+
+ assert response.status_code == 500
+ assert response.json() == {"error": "Server error"}
+
+
+# ---------------------------------------------------------------------------
+# Pages that rendered defaults
+# ---------------------------------------------------------------------------
+
+
+def test_library_page_does_not_render_defaults_for_an_invalid_setting():
+ from local_deep_research.web.routers import library
+
+ manager = Mock()
+ manager.get_setting.side_effect = _error(
+ "research_library.shared_library", "environment"
+ )
+ with (
+ patch.object(
+ library,
+ "get_user_db_session",
+ lambda *a, **k: nullcontext(Mock()),
+ ),
+ patch.object(library, "get_settings_manager", return_value=manager),
+ pytest.raises(SettingsValueError) as raised,
+ ):
+ library.library_page(SimpleNamespace(query_params={}), "alice")
+
+ assert raised.value.key == "research_library.shared_library"
+
+
+def test_subscription_form_is_not_prefilled_with_defaults():
+ from local_deep_research.web.routers import news_pages
+
+ settings = {"iterations": 3}
+ manager = Mock()
+ manager.get_setting.side_effect = _error()
+ with (
+ patch(SETTINGS_MANAGER, return_value=manager),
+ pytest.raises(SettingsValueError),
+ ):
+ news_pages._load_user_settings(settings, MagicMock(), "alice")
+
+ assert settings == {"iterations": 3}
+
+
+def test_edit_subscription_page_does_not_report_a_loading_error():
+ from local_deep_research.web.routers import news_pages
+
+ request = Request(
+ {
+ "type": "http",
+ "method": "GET",
+ "path": "/news/subscriptions/s1/edit",
+ "headers": [],
+ "session": {"username": "alice"},
+ }
+ )
+ with (
+ patch.object(news_pages, "_load_user_settings", side_effect=_error()),
+ patch(
+ "local_deep_research.news.api.get_subscription",
+ return_value={"id": "s1"},
+ ),
+ patch(
+ "local_deep_research.database.session_context.get_user_db_session",
+ lambda *a, **k: nullcontext(MagicMock()),
+ ),
+ patch.object(news_pages.templates, "TemplateResponse") as render,
+ pytest.raises(SettingsValueError),
+ ):
+ news_pages.edit_subscription_page(request, "s1", username="alice")
+
+ render.assert_not_called()
+
+
+# ---------------------------------------------------------------------------
+# News subscription egress pre-check
+# ---------------------------------------------------------------------------
+
+
+def test_subscription_is_refused_naming_the_invalid_setting():
+ from local_deep_research.news.api import _validate_subscription_policy
+
+ manager = Mock()
+ manager.get_settings_snapshot.side_effect = _error("policy.egress_scope")
+ with patch(SETTINGS_MANAGER, return_value=manager):
+ reason = _validate_subscription_policy(Mock(), "alice", "arxiv", None)
+
+ assert reason == str(_error("policy.egress_scope"))
+
+
+def test_invalid_setting_is_not_reported_as_a_misconfigured_policy():
+ from local_deep_research.news.api import _validate_subscription_policy
+
+ manager = Mock()
+ manager.get_settings_snapshot.return_value = {"search.tool": "arxiv"}
+ with (
+ patch(SETTINGS_MANAGER, return_value=manager),
+ patch(
+ "local_deep_research.security.egress.policy.context_from_snapshot",
+ side_effect=_error("llm.provider"),
+ ),
+ ):
+ reason = _validate_subscription_policy(Mock(), "alice", "arxiv", None)
+
+ assert reason == str(_error("llm.provider"))
diff --git a/tests/web/routers/test_settings_bulk_response_atomicity.py b/tests/web/routers/test_settings_bulk_response_atomicity.py
new file mode 100644
index 0000000000..499abbab18
--- /dev/null
+++ b/tests/web/routers/test_settings_bulk_response_atomicity.py
@@ -0,0 +1,315 @@
+"""The bulk settings response must be prepared before its writes commit."""
+
+from contextlib import contextmanager
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+import pytest
+from sqlalchemy import create_engine
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.orm import Session
+
+from local_deep_research.database.models.settings import Setting, SettingType
+from local_deep_research.settings.exceptions import SettingsValueError
+from local_deep_research.settings.manager import SettingsManager
+from local_deep_research.web.dependencies.auth import require_auth
+from local_deep_research.web.routers import settings
+
+
+_SECRET = "private-test-api-key"
+_URL = "/settings/save_all_settings"
+
+
+def bulk_settings(tmp_path, monkeypatch):
+ for name in (
+ "LDR_APP_LOCK_SETTINGS",
+ "LDR_LLM_MODEL",
+ "LDR_LLM_TEMPERATURE",
+ "LDR_LLM_OPENAI_API_KEY",
+ "LDR_SEARCH_ITERATIONS",
+ ):
+ monkeypatch.delenv(name, raising=False)
+ engine = create_engine(f"sqlite:///{tmp_path / 'settings.db'}")
+ Setting.__table__.create(engine)
+ defaults_manager = SettingsManager()
+ defaults = defaults_manager.default_settings
+ try:
+ with Session(engine) as session:
+ for key, value in (
+ ("llm.model", "old-model"),
+ ("llm.temperature", 0.7),
+ ("llm.openai.api_key", _SECRET),
+ ):
+ metadata = defaults[key]
+ session.add(
+ Setting(
+ key=key,
+ value=value,
+ name=metadata["name"],
+ type=SettingType.LLM,
+ ui_element=metadata["ui_element"],
+ options=metadata.get("options"),
+ min_value=metadata.get("min_value"),
+ max_value=metadata.get("max_value"),
+ editable=True,
+ )
+ )
+ session.commit()
+
+ @contextmanager
+ def session_scope(*args, **kwargs):
+ # Real sessions/managers are created in the route's worker. A
+ # failed request closes its uncommitted transaction here.
+ with Session(engine) as session:
+ yield session
+
+ monkeypatch.setattr(settings, "get_user_db_session", session_scope)
+ effects = {
+ name: Mock()
+ for name in (
+ "invalidate_settings_caches",
+ "reschedule_document_jobs_if_needed",
+ "reschedule_zotero_jobs_if_needed",
+ )
+ }
+ for name, effect in effects.items():
+ monkeypatch.setattr(settings, name, effect)
+ emit = Mock()
+ monkeypatch.setattr(
+ SettingsManager, "emit_settings_changed_after_commit", emit
+ )
+
+ app = FastAPI()
+ app.include_router(settings.router)
+ app.dependency_overrides[require_auth] = lambda: "bulk-response-user"
+
+ def stored(key):
+ # Verify committed state with a new Session, not the request's
+ # identity map or pending transaction.
+ with Session(engine) as fresh:
+ return fresh.query(Setting.value).filter_by(key=key).scalar()
+
+ def corrupt_temperature():
+ with Session(engine) as session:
+ setting = (
+ session.query(Setting)
+ .filter_by(key="llm.temperature")
+ .one()
+ )
+ setting.value = "needs-repair"
+ session.commit()
+
+ with TestClient(app, raise_server_exceptions=False) as client:
+ yield SimpleNamespace(
+ client=client,
+ stored=stored,
+ corrupt_temperature=corrupt_temperature,
+ emit=emit,
+ effects=effects,
+ )
+ finally:
+ defaults_manager.close()
+ engine.dispose()
+
+
+def _no_post_commit_effects(state):
+ state.emit.assert_not_called()
+ for effect in state.effects.values():
+ effect.assert_not_called()
+
+
+def test_invalid_unrelated_environment_overlay_does_not_commit(
+ bulk_settings, monkeypatch
+):
+ state = bulk_settings
+ invalid = "invalid-number-private"
+ monkeypatch.setenv("LDR_LLM_TEMPERATURE", invalid)
+
+ response = state.client.post(_URL, json={"llm.model": "llama3.1:8b"})
+
+ assert response.status_code == 500
+ assert state.stored("llm.model") == "old-model"
+ assert state.stored("llm.temperature") == 0.7
+ _no_post_commit_effects(state)
+ assert "Invalid setting 'llm.temperature' from environment" in response.text
+ assert "expected a valid range value" in response.text
+ assert invalid not in response.text
+ assert _SECRET not in response.text
+
+
+def test_invalid_override_on_a_declared_key_without_a_row_does_not_commit(
+ bulk_settings, monkeypatch
+):
+ state = bulk_settings
+ # search.iterations is a declared default with no saved row here.
+ assert state.stored("search.iterations") is None
+ invalid = "invalid-iterations-private"
+ monkeypatch.setenv("LDR_SEARCH_ITERATIONS", invalid)
+
+ response = state.client.post(_URL, json={"llm.model": "llama3.1:8b"})
+
+ assert response.status_code == 500
+ assert state.stored("llm.model") == "old-model"
+ _no_post_commit_effects(state)
+ assert (
+ "Invalid setting 'search.iterations' from environment" in response.text
+ )
+ assert invalid not in response.text
+
+
+def test_valid_override_on_a_declared_key_without_a_row_still_commits(
+ bulk_settings, monkeypatch
+):
+ state = bulk_settings
+ monkeypatch.setenv("LDR_SEARCH_ITERATIONS", "4")
+
+ response = state.client.post(_URL, json={"llm.model": "llama3.1:8b"})
+
+ assert response.status_code == 200
+ assert state.stored("llm.model") == "llama3.1:8b"
+
+
+def test_settings_error_after_commit_is_reported_as_committed(
+ bulk_settings, monkeypatch
+):
+ state = bulk_settings
+ warnings = Mock(
+ side_effect=SettingsValueError(
+ "llm.temperature", source="value", reason="test reason"
+ )
+ )
+ monkeypatch.setattr(settings, "calculate_warnings", warnings)
+
+ response = state.client.post(_URL, json={"llm.provider": "ollama"})
+
+ warnings.assert_called_once()
+ # The batch committed before the raise, so the response must not claim
+ # the save was refused.
+ assert response.status_code == 200
+ assert response.json()["status"] == "success"
+ assert state.stored("llm.provider") == "ollama"
+ state.emit.assert_called_once_with(["llm.provider"])
+
+
+def test_valid_overlay_commits_and_redacts_the_effective_response(
+ bulk_settings, monkeypatch
+):
+ state = bulk_settings
+ monkeypatch.setenv("LDR_LLM_TEMPERATURE", "0.4")
+
+ response = state.client.post(_URL, json={"llm.model": "llama3.1:8b"})
+
+ assert response.status_code == 200
+ assert state.stored("llm.model") == "llama3.1:8b"
+ assert state.stored("llm.temperature") == 0.7
+ assert state.stored("llm.openai.api_key") == _SECRET
+ body = response.json()
+ assert body["status"] == "success"
+ assert body["settings"]["llm.temperature"]["value"] == 0.4
+ assert body["settings"]["llm.temperature"]["editable"] is False
+ assert body["settings"]["llm.openai.api_key"]["value"] == "[REDACTED]"
+ assert _SECRET not in response.text
+ state.emit.assert_called_once_with(["llm.model"])
+ for effect in state.effects.values():
+ effect.assert_called_once()
+
+
+def test_new_setting_is_committed_and_included_in_the_response(bulk_settings):
+ state = bulk_settings
+ key = "llm.custom_limit"
+ assert state.stored(key) is None
+
+ response = state.client.post(_URL, json={key: 5})
+
+ assert response.status_code == 200
+ assert state.stored(key) == 5
+ body = response.json()
+ assert body["created"] == [key]
+ assert body["settings"][key]["value"] == 5
+ assert body["settings"][key]["ui_element"] == "number"
+ state.emit.assert_called_once_with([key])
+ for effect in state.effects.values():
+ effect.assert_called_once()
+
+
+def test_invalid_unrelated_overlay_rolls_back_a_pending_new_setting(
+ bulk_settings, monkeypatch
+):
+ state = bulk_settings
+ key = "llm.custom_limit"
+ monkeypatch.setenv("LDR_LLM_TEMPERATURE", "invalid-number-private")
+
+ response = state.client.post(_URL, json={key: 5})
+
+ assert response.status_code == 500
+ assert state.stored(key) is None
+ assert state.stored("llm.temperature") == 0.7
+ _no_post_commit_effects(state)
+ assert "Invalid setting 'llm.temperature' from environment" in response.text
+ assert "invalid-number-private" not in response.text
+
+
+def test_a_malformed_stored_target_can_still_be_repaired(bulk_settings):
+ state = bulk_settings
+ state.corrupt_temperature()
+
+ response = state.client.post(_URL, json={"llm.temperature": 0.6})
+
+ assert response.status_code == 200
+ assert state.stored("llm.temperature") == 0.6
+ assert response.json()["settings"]["llm.temperature"]["value"] == 0.6
+ assert "needs-repair" not in response.text
+ state.emit.assert_called_once_with(["llm.temperature"])
+
+
+def test_an_unrelated_stored_error_does_not_prevent_a_targeted_write(
+ bulk_settings,
+):
+ state = bulk_settings
+ state.corrupt_temperature()
+
+ response = state.client.post(_URL, json={"llm.model": "new-model"})
+
+ # The existing response echoes stored values for repair. It must not
+ # become a new strict read of every unrelated stored setting.
+ assert response.status_code == 200
+ assert state.stored("llm.model") == "new-model"
+ assert state.stored("llm.temperature") == "needs-repair"
+ assert response.json()["settings"]["llm.temperature"]["value"] == (
+ "needs-repair"
+ )
+
+
+def test_invalid_request_still_rolls_back_the_whole_json_batch(bulk_settings):
+ state = bulk_settings
+
+ response = state.client.post(
+ _URL, json={"llm.model": "new-model", "llm.temperature": -1}
+ )
+
+ assert response.status_code == 400
+ assert state.stored("llm.model") == "old-model"
+ assert state.stored("llm.temperature") == 0.7
+ _no_post_commit_effects(state)
+
+
+def test_commit_failure_does_not_publish_success_or_effects(
+ bulk_settings, monkeypatch
+):
+ state = bulk_settings
+ detail = "private-database-failure"
+ monkeypatch.setattr(
+ Session, "commit", Mock(side_effect=SQLAlchemyError(detail))
+ )
+
+ response = state.client.post(_URL, json={"llm.model": "new-model"})
+
+ assert response.status_code == 500
+ assert response.json()["status"] == "error"
+ assert detail not in response.text
+ assert _SECRET not in response.text
+ assert state.stored("llm.model") == "old-model"
+ _no_post_commit_effects(state)
diff --git a/tests/web/routers/test_settings_form_post_null_option.py b/tests/web/routers/test_settings_form_post_null_option.py
index 8f607005e0..444e191887 100644
--- a/tests/web/routers/test_settings_form_post_null_option.py
+++ b/tests/web/routers/test_settings_form_post_null_option.py
@@ -15,6 +15,8 @@ form performs. The JSON route is unaffected -- it sends a real null -- which is
why only the no-JS path showed it.
"""
+import json
+
# allow: no-sut-import — this module drives the settings write path over HTTP
# through the `authenticated_client` fixture rather than importing a symbol from
@@ -43,6 +45,11 @@ def _post_all_settings(client, caplog):
form[key] = "on" if value else ""
elif value is None:
form[key] = "" # exactly what a browser posts for a null option
+ elif isinstance(value, (list, dict)):
+ # settings.js::processSettings serializes structured values as
+ # JSON before rendering the inputs. Python repr is not the form
+ # payload and must still be rejected by the strict list parser.
+ form[key] = json.dumps(value, indent=2)
else:
form[key] = str(value)
@@ -113,6 +120,13 @@ class TestNullOptionSelectsRoundTrip:
how this one survived long enough to be found by a browser test rather
than by validation.
"""
+ original = authenticated_client.get(
+ "/settings/api/report.export_formats"
+ )
+ assert original.status_code == 200, original.text
+ original_formats = original.json()["value"]
+ assert isinstance(original_formats, list) and original_formats
+
failures = _post_all_settings(authenticated_client, loguru_caplog_full)
assert not failures, (
@@ -124,3 +138,7 @@ class TestNullOptionSelectsRoundTrip:
"dynamically-generated option list, or a type does not survive the "
"HTML form round-trip."
)
+
+ saved = authenticated_client.get("/settings/api/report.export_formats")
+ assert saved.status_code == 200, saved.text
+ assert saved.json()["value"] == original_formats
diff --git a/tests/web/routers/test_settings_routes_save_validation_coverage_port.py b/tests/web/routers/test_settings_routes_save_validation_coverage_port.py
index 00f669d520..607abda550 100644
--- a/tests/web/routers/test_settings_routes_save_validation_coverage_port.py
+++ b/tests/web/routers/test_settings_routes_save_validation_coverage_port.py
@@ -422,14 +422,20 @@ class TestCoerceSettingForWriteVariousTypes:
assert coerce_setting_for_write("app.theme", "dark", "select") == "dark"
- def test_unknown_ui_element_returns_none(self):
+ def test_unknown_ui_element_is_preserved_for_explicit_validation_error(
+ self,
+ ):
from local_deep_research.web.routers.settings import (
coerce_setting_for_write,
+ validate_setting,
)
- assert (
- coerce_setting_for_write("foo.bar", "value", "unknown_widget")
- is None
+ value = coerce_setting_for_write("foo.bar", "value", "unknown_widget")
+ assert value == "value"
+ setting = _make_setting(key="foo.bar", ui_element="unknown_widget")
+ assert validate_setting(setting, value) == (
+ False,
+ "unsupported setting type",
)
diff --git a/tests/web/routers/test_settings_validation_edge_cases_port.py b/tests/web/routers/test_settings_validation_edge_cases_port.py
index 78d491a13f..96c7267b1e 100644
--- a/tests/web/routers/test_settings_validation_edge_cases_port.py
+++ b/tests/web/routers/test_settings_validation_edge_cases_port.py
@@ -168,14 +168,14 @@ class TestValidateSettingSelect:
class TestValidateSettingUnknownElement:
- """Unknown ui_element types pass through."""
+ """Unknown ui_element types fail explicitly."""
- def test_unknown_ui_element_passes(self):
- """Unknown ui_element like 'custom_widget' -> (True, None)."""
+ def test_unknown_ui_element_is_rejected(self):
+ """An unsupported schema cannot silently accept an arbitrary value."""
setting = _make_setting("custom_widget")
valid, msg = validate_setting(setting, "any value")
- assert valid is True
- assert msg is None
+ assert valid is False
+ assert msg == "unsupported setting type"
# ---------------------------------------------------------------------------
diff --git a/tests/web/routers/test_settings_write_matches_strict_read.py b/tests/web/routers/test_settings_write_matches_strict_read.py
new file mode 100644
index 0000000000..9a675bea65
--- /dev/null
+++ b/tests/web/routers/test_settings_write_matches_strict_read.py
@@ -0,0 +1,156 @@
+"""Settings writes must not store a row that the strict read rejects.
+
+Every effective settings read validates each row, so one stored row with an
+unsupported ui_element, or a value its type cannot convert, makes the
+settings page, research start and the /api/v1 endpoints fail for the whole
+account. The write routes therefore apply the read's own rules (supported
+type, convertible value) to the row exactly as it will be stored, and
+answer 400 naming the key.
+"""
+
+import json
+from contextlib import contextmanager
+from types import SimpleNamespace
+from unittest.mock import MagicMock, Mock, patch
+
+import pytest
+
+from local_deep_research.settings.manager import UI_ELEMENT_TO_SETTING_TYPE
+
+S = "local_deep_research.web.routers.settings"
+KEY = "llm.custom_knob"
+
+
+def _patched_db(existing=None):
+ """A user DB whose single-row lookup returns ``existing``."""
+ query = MagicMock()
+ query.all.return_value = []
+ query.first.return_value = existing
+ query.filter.return_value = query
+ query.filter_by.return_value = query
+ session = MagicMock()
+ session.query.return_value = query
+
+ @contextmanager
+ def fake_db_session(*args, **kwargs):
+ yield session
+
+ return patch(f"{S}.get_user_db_session", side_effect=fake_db_session)
+
+
+def _put(key, data, existing=None, created=None):
+ from local_deep_research.web.routers.settings import (
+ _api_update_setting_sync,
+ )
+
+ with (
+ _patched_db(existing),
+ patch(f"{S}.create_or_update_setting", return_value=created) as create,
+ patch(f"{S}.set_setting", return_value=True) as write,
+ ):
+ response = _api_update_setting_sync(data, key, "alice")
+ return response, create, write
+
+
+ "ui_element", ["slider", "color", "date", "file", "Number", 7]
+)
+def test_new_key_with_an_unsupported_type_is_rejected(ui_element):
+ response, create, _ = _put(KEY, {"value": 0.5, "ui_element": ui_element})
+
+ assert response.status_code == 400
+ assert json.loads(response.body) == {
+ "error": f"Invalid value for setting {KEY}: unsupported setting type"
+ }
+ create.assert_not_called()
+
+
+ "data",
+ [
+ {"value": "abc", "ui_element": "number"},
+ {"value": "", "ui_element": "range"},
+ {"value": True, "ui_element": "number"},
+ {"value": 10**400, "ui_element": "number"},
+ {"value": float("inf")},
+ {"value": float("nan")},
+ ],
+ ids=["text", "blank", "boolean", "overflow", "infinity", "nan-inferred"],
+)
+def test_new_key_with_a_value_its_type_cannot_convert_is_rejected(data):
+ response, create, _ = _put(KEY, data)
+
+ assert response.status_code == 400
+ assert json.loads(response.body) == {
+ "error": (
+ f"Invalid value for setting {KEY}: expected a valid "
+ f"{data.get('ui_element', 'number')} value"
+ )
+ }
+ create.assert_not_called()
+
+
+def test_new_key_with_a_convertible_value_is_still_created():
+ created = Mock(key=KEY, value="5", ui_element="number")
+ created.type = Mock(value="LLM")
+ created.name = "Custom Knob"
+
+ response, create, _ = _put(
+ KEY, {"value": "5", "ui_element": "number"}, created=created
+ )
+
+ assert response.status_code == 201
+ create.assert_called_once()
+ assert create.call_args.args[0]["ui_element"] == "number"
+
+
+def test_update_cannot_turn_a_text_row_into_an_invalid_number_row():
+ """set_setting() re-infers a text row's type from a numeric value."""
+ row = SimpleNamespace(
+ key=KEY,
+ value="old",
+ ui_element="text",
+ editable=True,
+ options=None,
+ min_value=None,
+ max_value=None,
+ )
+
+ response, _, write = _put(KEY, {"value": float("nan")}, existing=row)
+
+ assert response.status_code == 400
+ assert json.loads(response.body) == {
+ "error": f"Invalid value for setting {KEY}: expected a valid number value"
+ }
+ write.assert_not_called()
+
+
+def test_bulk_save_does_not_create_an_invalid_number_row():
+ from local_deep_research.web.routers.settings import (
+ _save_all_settings_sync,
+ )
+
+ with (
+ _patched_db(),
+ patch(f"{S}.create_or_update_setting") as create,
+ patch(f"{S}.set_setting"),
+ ):
+ response = _save_all_settings_sync({KEY: float("inf")}, "alice")
+
+ assert response.status_code == 400
+ assert json.loads(response.body)["errors"] == [
+ {
+ "key": KEY,
+ "name": "Custom Knob",
+ "error": "expected a valid number value",
+ }
+ ]
+ create.assert_not_called()
+
+
+def test_ui_elements_lists_only_types_the_read_supports():
+ from local_deep_research.web.routers.settings import api_get_ui_elements
+
+ body = api_get_ui_elements(Mock(), "alice")
+
+ assert sorted(body["ui_elements"]) == sorted(UI_ELEMENT_TO_SETTING_TYPE)
diff --git a/tests/web/services/test_settings_manager_extended.py b/tests/web/services/test_settings_manager_extended.py
index 4e12ea979e..7847470104 100644
--- a/tests/web/services/test_settings_manager_extended.py
+++ b/tests/web/services/test_settings_manager_extended.py
@@ -18,6 +18,8 @@ import json
import pytest
from unittest.mock import Mock, MagicMock, patch
+from local_deep_research.settings.exceptions import SettingsValueError
+
class MockSetting:
"""Mock Setting model for testing."""
@@ -325,8 +327,8 @@ class TestUIElementTypeConversion:
assert result == json_value
- def test_unknown_ui_element_returns_default(self):
- """Unknown ui_element returns default value."""
+ def test_unknown_ui_element_raises_instead_of_returning_default(self):
+ """Unsupported metadata must be repaired before the row can be read."""
from local_deep_research.settings.manager import (
SettingsManager,
)
@@ -340,18 +342,24 @@ class TestUIElementTypeConversion:
mock_session.query.return_value = mock_query
manager = SettingsManager(db_session=mock_session)
- result = manager.get_setting(
- "app.unknown", default="default_val", check_env=False
- )
+ with pytest.raises(SettingsValueError) as raised:
+ manager.get_setting(
+ "app.unknown", default="default_val", check_env=False
+ )
- assert result == "default_val"
+ assert raised.value.key == "app.unknown"
+ assert raised.value.source == "value"
+ assert raised.value.reason == "unsupported setting type"
+
+ mock_setting.ui_element = "text"
+ assert manager.get_setting("app.unknown", check_env=False) == "test"
class TestEnvironmentVariableEdgeCases:
"""Tests for environment variable handling edge cases."""
- def test_env_override_invalid_number(self):
- """Invalid number in env var falls back to DB value."""
+ def test_env_override_invalid_number_raises(self, monkeypatch):
+ """Invalid numeric overrides cannot select the DB value or default."""
from local_deep_research.settings.manager import (
SettingsManager,
)
@@ -364,15 +372,20 @@ class TestEnvironmentVariableEdgeCases:
mock_query.filter.return_value.all.return_value = [mock_setting]
mock_session.query.return_value = mock_query
- os.environ["LDR_LLM_TEMPERATURE"] = "not_a_number"
- try:
- manager = SettingsManager(db_session=mock_session)
- result = manager.get_setting("llm.temperature", check_env=True)
-
- # Should fall back to DB value
- assert result == 0.7
- finally:
- del os.environ["LDR_LLM_TEMPERATURE"]
+ manager = SettingsManager(db_session=mock_session)
+ monkeypatch.setenv("LDR_LLM_TEMPERATURE", "not_a_number")
+ with pytest.raises(SettingsValueError) as raised:
+ manager.get_setting("llm.temperature", default=0.2, check_env=True)
+
+ assert raised.value.key == "llm.temperature"
+ assert raised.value.source == "environment"
+ assert "not_a_number" not in str(raised.value)
+ assert raised.value.__cause__ is None
+ assert raised.value.__context__ is None
+ assert manager.get_setting("llm.temperature", check_env=False) == 0.7
+
+ monkeypatch.setenv("LDR_LLM_TEMPERATURE", "0.4")
+ assert manager.get_setting("llm.temperature", check_env=True) == 0.4
def test_env_override_empty_string(self):
"""Empty string env var is treated as unset (Docker/Unraid templates create blank entries)."""
diff --git a/tests/web/test_root_route_failure_recovery.py b/tests/web/test_root_route_failure_recovery.py
index 1db62930a3..d315744bd2 100644
--- a/tests/web/test_root_route_failure_recovery.py
+++ b/tests/web/test_root_route_failure_recovery.py
@@ -49,3 +49,45 @@ def test_root_settings_failure_logs_out_and_clears_the_signed_session(
check = authenticated_client.get("/auth/check", follow_redirects=False)
assert check.status_code == 401
assert check.json()["authenticated"] is False
+
+
+def test_root_invalid_setting_shows_the_diagnostic_and_keeps_the_session(
+ authenticated_client,
+):
+ """An invalid configured setting must not log the user out.
+
+ Clearing the session here is a login loop: login redirects back to the
+ root page, whose settings read fails again. The page shows the
+ value-free diagnostic instead, and the user stays signed in.
+ """
+ from local_deep_research.settings.exceptions import SettingsValueError
+
+ before = authenticated_client.get("/auth/check")
+ assert before.status_code == 200
+ error = SettingsValueError(
+ "search.iterations",
+ source="environment",
+ reason="expected a valid number value",
+ )
+
+ with patch(
+ "local_deep_research.settings.manager.SettingsManager.get_setting",
+ side_effect=error,
+ ):
+ response = authenticated_client.get("/", follow_redirects=False)
+
+ assert response.status_code == 500
+ assert "location" not in response.headers
+ assert "search.iterations" in response.text
+ assert "expected a valid number value" in response.text
+ assert not [
+ value
+ for key, value in response.headers.raw
+ if key.lower() == b"set-cookie"
+ and value.decode().startswith("session=")
+ and "expires=Thu, 01 Jan 1970" in value.decode()
+ ]
+
+ check = authenticated_client.get("/auth/check", follow_redirects=False)
+ assert check.status_code == 200
+ assert check.json()["authenticated"] is True
diff --git a/tests/web/test_server_config_gaps.py b/tests/web/test_server_config_gaps.py
index 515f938c3b..1d9c9a9457 100644
--- a/tests/web/test_server_config_gaps.py
+++ b/tests/web/test_server_config_gaps.py
@@ -3,6 +3,9 @@
import json
from unittest.mock import patch
+import pytest
+
+from local_deep_research.settings.exceptions import SettingsValueError
from local_deep_research.web.server_config import (
_DEFAULTS,
_load_legacy_config,
@@ -181,11 +184,13 @@ class TestLoadServerConfig:
config = load_server_config()
assert config["port"] in (5000, _DEFAULTS["port"])
- def test_unrecognized_allow_registrations_env_defaults_false(self):
+ @pytest.mark.parametrize("legacy_value", [None, False, True])
+ def test_unrecognized_allow_registrations_env_raises(self, legacy_value):
+ """An invalid override must not select a default or legacy value."""
with (
patch(
"local_deep_research.web.server_config._load_legacy_config",
- return_value={},
+ return_value={"allow_registrations": legacy_value},
),
patch.dict(
"os.environ",
@@ -193,10 +198,16 @@ class TestLoadServerConfig:
clear=False,
),
):
- config = load_server_config()
- assert config["allow_registrations"] is False
+ with pytest.raises(SettingsValueError) as raised:
+ load_server_config()
+
+ assert raised.value.key == "app.allow_registrations"
+ assert raised.value.source == "environment"
- def test_recognized_allow_registrations_env_passes(self):
+ @pytest.mark.parametrize(
+ ("value", "expected"), [("true", True), ("false", False)]
+ )
+ def test_recognized_allow_registrations_env_passes(self, value, expected):
with (
patch(
"local_deep_research.web.server_config._load_legacy_config",
@@ -204,13 +215,12 @@ class TestLoadServerConfig:
),
patch.dict(
"os.environ",
- {"LDR_APP_ALLOW_REGISTRATIONS": "true"},
+ {"LDR_APP_ALLOW_REGISTRATIONS": value},
clear=False,
),
):
config = load_server_config()
- # Should be True (recognized value)
- assert config["allow_registrations"] is True
+ assert config["allow_registrations"] is expected
def test_legacy_unrecognized_allow_registrations_string(self):
with (