~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
refactor(settings): remove obsolete corrupted-settings repair (#5145)
LearningCircuitfc6aae99bab8
diff --git a/changelog.d/+remove-fix-corrupted-settings.removal.md b/changelog.d/+remove-fix-corrupted-settings.removal.mdnew file mode 100644index 0000000000..8ea09dcd28--- /dev/null+++ b/changelog.d/+remove-fix-corrupted-settings.removal.md@@ -0,0 +1 @@+Removed the obsolete **Fix Corrupted Settings** button and endpoint. A one-time upgrade migration deduplicates legacy settings, restores key uniqueness, and repairs unambiguous sentinel values with frozen packaged defaults. Password metadata is preserved across duplicate cleanup, including intentional clears, and notification service URLs receive the same credential protection as API keys. Valid identifiers, hostnames and unrelated settings remain unchanged. Bulk saves from the settings page now report failed writes, roll back the entire batch and notify clients only after a successful commit; the no-JavaScript form fallback keeps its per-key reporting.diff --git a/src/local_deep_research/database/migrations/versions/0031_reconcile_corrupted_settings.py b/src/local_deep_research/database/migrations/versions/0031_reconcile_corrupted_settings.pynew file mode 100644index 0000000000..db3422da61--- /dev/null+++ b/src/local_deep_research/database/migrations/versions/0031_reconcile_corrupted_settings.py@@ -0,0 +1,470 @@+"""Reconcile legacy corrupted setting values with current defaults.++The removed ``fix_corrupted_settings`` endpoint repaired a small set of+well-known settings whose values had been replaced by browser/JSON sentinel+values such as ``"undefined"`` or ``"[object Object]"``. Read-time coercion+does not reject those strings for select and text settings, so affected user+databases need a one-time data migration before the manual endpoint disappears.++Some encrypted databases created before model-declared indexes were emitted+could also retain duplicate setting keys if migration 0007 could not create+the unique key index. This migration keeps the newest usable row for each key+(falling back to the newest row when every candidate is corrupted) and restores+the uniqueness invariant before repairing values.++This migration intentionally uses an exact key allowlist and exact raw JSON+encodings. It does not overwrite password settings, valid free-form or+registry-backed identifiers or hostnames, JSON settings, unknown ``report.*``+keys, empty lists, or near-matching strings. When legacy duplicates include a+password/API credential, it only prefers an older row when the newer candidate+is an exact corruption sentinel. Replacement values are a frozen snapshot of+the packaged defaults at this revision.++Revision ID: 0031+Revises: 0030+"""++from __future__ import annotations++import json++import sqlalchemy as sa+from alembic import op+from loguru import logger+from sqlalchemy import inspect++revision = "0031"+down_revision = "0030"+branch_labels = None+depends_on = None++_SETTINGS_KEY_INDEX = "ix_settings_key"+_DELETE_BATCH_SIZE = 500+_SENSITIVE_KEY_LEAVES = frozenset(+ {+ "api_key",+ "apikey",+ "password",+ "secret",+ "access_token",+ "refresh_token",+ "private_key",+ "auth_token",+ "session_token",+ "csrf_token",+ "client_secret",+ "secret_key",+ "bearer_token",+ "api_secret",+ "app_secret",+ "service_url",+ }+)++# Frozen copy of the runtime secret-key normalization at this revision.+# Several default-ignorable Unicode characters pass setting-key validation and+# can visually disguise a sensitive leaf, so raw suffix matching is not enough.+_PRINTABLE_DEFAULT_IGNORABLES = (+ frozenset({0x034F})+ | frozenset(range(0x115F, 0x1161))+ | frozenset(range(0x17B4, 0x17B6))+ | frozenset(range(0x180B, 0x1810))+ | frozenset({0x3164, 0xFFA0})+ | frozenset(range(0xFE00, 0xFE10))+ | frozenset(range(0xE0100, 0xE01F0))+)+_PRINTABLE_BLANKS = frozenset(+ {+ 0x2800,+ 0x13441,+ 0x13442,+ 0x1D159,+ }+)+++REPAIR_DEFAULTS = {+ "app.debug": False,+ "app.enable_notifications": True,+ "app.enable_web": True,+ "app.host": "0.0.0.0", # noqa: S104 - frozen packaged default+ "app.port": 5000,+ "app.theme": "system",+ "app.web_interface": True,+ "llm.max_tokens": 30000,+ "llm.model": "",+ "llm.provider": "ollama",+ "llm.temperature": 0.7,+ "report.searches_per_section": 2,+ "search.max_results": 50,+ "search.questions_per_iteration": 1,+ "search.region": "us",+ "search.safe_search": True,+ "search.search_language": "English",+ "search.searches_per_section": 2,+ "search.skip_relevance_filter": True,+ "search.tool": "searxng",+}++_STRING_SENTINEL_JSON_VALUES = frozenset(+ json.dumps(value)+ for value in (+ "{",+ "[",+ "{}",+ "[]",+ "[object Object]",+ "null",+ "undefined",+ )+)+_STRUCTURAL_CORRUPTION_JSON_VALUES = frozenset(+ json.dumps(value) for value in (None, {})+)+_CORRUPTED_JSON_VALUES = (+ _STRING_SENTINEL_JSON_VALUES | _STRUCTURAL_CORRUPTION_JSON_VALUES+)+_SENSITIVE_CORRUPTED_JSON_VALUES = (+ _STRING_SENTINEL_JSON_VALUES+ | _STRUCTURAL_CORRUPTION_JSON_VALUES.difference({json.dumps(None)})+ | frozenset({json.dumps("[REDACTED]")})+)++# Some sentinel-looking strings remain valid for free-form and registry-backed+# settings. Model, provider, search-tool, and theme identifiers are unrestricted,+# while "undefined" and "null" are syntactically valid DNS hostnames. The+# removed endpoint required explicit user activation; an automatic migration+# must preserve these ambiguous values.+_AMBIGUOUS_STRING_JSON_VALUES_BY_KEY = {+ "app.host": frozenset(json.dumps(value) for value in ("null", "undefined")),+ "app.theme": _STRING_SENTINEL_JSON_VALUES,+ "llm.model": _STRING_SENTINEL_JSON_VALUES,+ "llm.provider": _STRING_SENTINEL_JSON_VALUES,+ "search.tool": _STRING_SENTINEL_JSON_VALUES,+}+++def _unambiguous_corrupted_json_values(key: str) -> frozenset[str]:+ """Return exact corrupt encodings that are not valid for ``key``."""+ return _CORRUPTED_JSON_VALUES.difference(+ _AMBIGUOUS_STRING_JSON_VALUES_BY_KEY.get(key, ())+ )+++def _visible_sensitive_leaf(key: str) -> str:+ """Return the visible normalized final segment of a setting key."""+ leaf = key.rsplit(".", 1)[-1]+ leaf = "".join(+ character+ for character in leaf+ if character.isprintable()+ and ord(character) not in _PRINTABLE_DEFAULT_IGNORABLES+ and ord(character) not in _PRINTABLE_BLANKS+ )+ return leaf.strip().lower()+++def _is_sensitive_setting(key: object, ui_element: object) -> bool:+ """Frozen credential predicate for this historical migration.++ Uses case- and whitespace-insensitive matching for the ``ui_element``+ field so that legacy or imported rows with values like ``"Password"`` or+ ``" password "`` are correctly classified as sensitive. This mirrors+ the normalization the runtime ``is_password_ui_element`` helper applies.+ """+ if isinstance(ui_element, str) and ui_element.strip().lower() == "password":+ return True+ if not isinstance(key, str):+ return False+ raw_leaf = key.rsplit(".", 1)[-1].lower()+ return (+ raw_leaf in _SENSITIVE_KEY_LEAVES+ or _visible_sensitive_leaf(key) in _SENSITIVE_KEY_LEAVES+ )+++def _raw_json_text(value: object) -> str | None:+ """Normalize equivalent SQLite TEXT/BLOB values for exact comparison."""+ if isinstance(value, str):+ return value+ if isinstance(value, (bytes, bytearray, memoryview)):+ try:+ return bytes(value).decode("utf-8")+ except UnicodeDecodeError:+ return None+ return None+++def _is_unambiguous_corruption(+ key: object,+ value: object,+ ui_element: object,+ *,+ sensitive_override: bool | None = None,+) -> bool:+ """Whether a duplicate candidate is certainly less useful than a valid row.++ Unknown non-sensitive keys retain newest-row semantics because their+ sentinel-looking strings may be intentional. Packaged repair targets apply+ the same per-key ambiguity rules as the value repair below. Credentials are+ never rewritten, but an exact browser/JSON sentinel must not displace an+ older usable secret during automatic deduplication.+ """+ is_sensitive = (+ _is_sensitive_setting(key, ui_element)+ if sensitive_override is None+ else sensitive_override+ )+ is_repair_target = isinstance(key, str) and key in REPAIR_DEFAULTS+ if not is_sensitive and not is_repair_target:+ return False+ if value is None:+ # NULL is a supported "credential unset" value. Never resurrect an+ # older secret by treating a newer intentional clear as corruption.+ return not is_sensitive++ raw_value = _raw_json_text(value)+ if raw_value is None:+ return False+ if is_sensitive:+ return raw_value in _SENSITIVE_CORRUPTED_JSON_VALUES+ return raw_value in _unambiguous_corrupted_json_values(key)+++# Untyped columns preserve the JSON column's raw on-disk representation.+# Attaching sa.JSON here would encode the already-encoded comparison values a+# second time. This follows the data-migration pattern in revisions 0013/0019.+_settings = sa.table(+ "settings",+ sa.column("id"),+ sa.column("key"),+ sa.column("value"),+ sa.column("updated_at"),+ sa.column("ui_element"),+)+++def _duplicate_ids_for_key_group(+ rows: list[tuple[int, object, object, object]],+) -> list[int]:+ """Choose one survivor after classifying sensitivity for the whole key."""+ if not rows:+ return []++ group_is_sensitive = any(+ _is_sensitive_setting(key, ui_element) for _, key, _, ui_element in rows+ )+ survivor_id, survivor_key, survivor_value, survivor_ui_element = rows[0]+ survivor_is_corrupted = _is_unambiguous_corruption(+ survivor_key,+ survivor_value,+ survivor_ui_element,+ sensitive_override=group_is_sensitive,+ )+ duplicate_ids: list[int] = []++ for row_id, key, value, ui_element in rows[1:]:+ candidate_is_corrupted = _is_unambiguous_corruption(+ key,+ value,+ ui_element,+ sensitive_override=group_is_sensitive,+ )+ if survivor_is_corrupted and not candidate_is_corrupted:+ duplicate_ids.append(survivor_id)+ survivor_id = row_id+ survivor_is_corrupted = False+ else:+ duplicate_ids.append(row_id)++ return duplicate_ids+++def _deduplicate_settings(conn) -> int:+ """Keep the newest usable row for every setting key.++ A small release window produced encrypted databases without model-declared+ indexes. If duplicate keys existed, migration 0007's best-effort unique+ index creation failed and deliberately continued. Rows remain ordered by+ ``updated_at`` and then ``id`` so normal duplicates keep the newest row and+ ties are deterministic. If that row is an unambiguous corruption sentinel,+ however, prefer the newest older usable candidate instead of automatically+ deleting recoverable user data or credentials.+ """+ column_names = {+ column["name"] for column in inspect(conn).get_columns("settings")+ }+ if not {"id", "key"}.issubset(column_names):+ return 0++ order_by = [_settings.c.key.asc()]+ if "updated_at" in column_names:+ order_by.append(_settings.c.updated_at.desc())+ order_by.append(_settings.c.id.desc())+ ui_element = (+ _settings.c.ui_element+ if "ui_element" in column_names+ else sa.literal(None).label("ui_element")+ )++ rows = conn.execute(+ sa.select(+ _settings.c.id,+ _settings.c.key,+ _settings.c.value,+ ui_element,+ ).order_by(*order_by)+ )+ duplicate_ids: list[int] = []+ password_metadata_ids: list[int] = []++ def collect_group(group):+ removed = _duplicate_ids_for_key_group(group)+ duplicate_ids.extend(removed)+ if not any(+ isinstance(ui, str) and ui.strip().lower() == "password"+ for _, _, _, ui in group+ ):+ return+ removed_ids = set(removed)+ survivor = next(row for row in group if row[0] not in removed_ids)+ if survivor[3] != "password":+ password_metadata_ids.append(survivor[0])++ key_group: list[tuple[int, object, object, object]] = []+ for row_id, key, value, setting_ui_element in rows:+ if key_group and key != key_group[0][1]:+ collect_group(key_group)+ key_group = []+ key_group.append((row_id, key, value, setting_ui_element))++ collect_group(key_group)++ # The selected row must retain a group's password classification even+ # after the older metadata-bearing duplicate disappears. Otherwise a+ # later upgrade would reinterpret its intentional clear as corruption.+ # Key-based secrets such as notification textareas keep their UI type.+ for offset in range(0, len(password_metadata_ids), _DELETE_BATCH_SIZE):+ batch = password_metadata_ids[offset : offset + _DELETE_BATCH_SIZE]+ conn.execute(+ sa.update(_settings)+ .where(_settings.c.id.in_(batch))+ .values(ui_element="password")+ )++ for offset in range(0, len(duplicate_ids), _DELETE_BATCH_SIZE):+ batch = duplicate_ids[offset : offset + _DELETE_BATCH_SIZE]+ conn.execute(sa.delete(_settings).where(_settings.c.id.in_(batch)))++ return len(duplicate_ids)+++def _ensure_unique_settings_key_index(conn) -> None:+ """Restore the unique key index when migration 0007 could not."""+ indexes = inspect(conn).get_indexes("settings")+ existing = next(+ (index for index in indexes if index["name"] == _SETTINGS_KEY_INDEX),+ None,+ )+ if existing and existing.get("unique"):+ return+ if existing:+ op.drop_index(_SETTINGS_KEY_INDEX, table_name="settings")++ op.create_index(+ _SETTINGS_KEY_INDEX,+ "settings",+ ["key"],+ unique=True,+ if_not_exists=True,+ )+++def _sensitive_setting_keys(conn) -> set[str]:+ """Freeze whole-key sensitivity before duplicate rows are removed."""+ column_names = {+ column["name"] for column in inspect(conn).get_columns("settings")+ }+ ui_element = (+ _settings.c.ui_element+ if "ui_element" in column_names+ else sa.literal(None).label("ui_element")+ )+ return {+ key+ for key, setting_ui_element in conn.execute(+ sa.select(_settings.c.key, ui_element)+ )+ if isinstance(key, str)+ and _is_sensitive_setting(key, setting_ui_element)+ }+++def _repair_corrupted_values(+ conn, sensitive_keys: set[str] | None = None+) -> int:+ if sensitive_keys is None:+ sensitive_keys = _sensitive_setting_keys(conn)+ # SQLite's legacy driver starts a transaction for DML, not SELECT or+ # index DDL. Start it even when every repair target is sensitive and+ # the loop below skips all updates. The false predicate changes no row.+ conn.execute(sa.update(_settings).where(sa.false()).values(value=None))+ repaired_count = 0+ # Normalize equivalent SQLite TEXT/BLOB storage classes for exact matches.+ # The JSON encoding itself remains unchanged and malformed values stay out.+ value_as_text = sa.cast(_settings.c.value, sa.Text)++ for key, default_value in REPAIR_DEFAULTS.items():+ if key in sensitive_keys:+ continue+ corrupted_values = _unambiguous_corrupted_json_values(key)+ result = conn.execute(+ sa.update(_settings)+ .where(_settings.c.key == key)+ .where(+ sa.or_(+ _settings.c.value.is_(None),+ value_as_text.in_(tuple(corrupted_values)),+ )+ )+ .values(value=json.dumps(default_value))+ )+ if result.rowcount and result.rowcount > 0:+ repaired_count += result.rowcount++ return repaired_count+++def upgrade() -> None:+ conn = op.get_bind()+ if not inspect(conn).has_table("settings"):+ return++ # A discarded older row can hold the only password metadata for a key.+ # Retain that classification so repair cannot overwrite a newer clear.+ sensitive_keys = _sensitive_setting_keys(conn)+ duplicate_count = _deduplicate_settings(conn)+ # Keep index DDL after a guaranteed DML statement. SQLite/SQLCipher legacy+ # transaction control does not emit a driver-level BEGIN for SELECT or DDL,+ # while repair explicitly issues a zero-row UPDATE even if every target+ # is skipped. This makes index replacement participate in Alembic's rollback.+ repaired_count = _repair_corrupted_values(conn, sensitive_keys)+ _ensure_unique_settings_key_index(conn)++ if duplicate_count:+ logger.info(+ "Removed {} legacy duplicate setting row(s) before restoring key "+ "uniqueness.",+ duplicate_count,+ )++ if repaired_count:+ logger.info(+ "Reconciled {} legacy corrupted setting value(s) with packaged "+ "defaults.",+ repaired_count,+ )+++def downgrade() -> None:+ """No-op: restoring duplicate rows or corrupted sentinels recreates bad state."""diff --git a/src/local_deep_research/web/routers/settings.py b/src/local_deep_research/web/routers/settings.pyindex 6260039d5d..0a11572385 100644--- a/src/local_deep_research/web/routers/settings.py+++ b/src/local_deep_research/web/routers/settings.py@@ -2020,6 +2020,16 @@ def _save_all_settings_sync(form_data: dict, username: str):)if success:updated_settings.append(key)+ else:+ db_session.rollback()+ logger.error("Failed to persist setting {}", key)+ return JSONResponse(+ {+ "status": "error",+ "message": "Failed to save setting.",+ },+ status_code=500,+ )# Track settings by type for exportingif current_setting.type not in settings_by_type:@@ -2138,6 +2148,11 @@ def _save_all_settings_sync(form_data: dict, username: str):# 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(@@ -4043,188 +4058,6 @@ def open_file_location(# CSRF token is injected globally via fastapi_app template globals[email protected]("/fix_corrupted_settings")-@settings_limit-def fix_corrupted_settings(- request: Request,- username: Annotated[str, Depends(require_auth)],-):- """Fix corrupted settings in the database"""- try:- with get_user_db_session(username) as db_session:- # Track fixed and removed settings- fixed_settings = []- removed_duplicate_settings = []- # First, find and remove duplicate settings with the same key- # This happens because of errors in settings import/export- from sqlalchemy import func as sql_func-- # Find keys with duplicates- duplicate_keys = (- db_session.query(Setting.key)- .group_by(Setting.key)- .having(sql_func.count(Setting.key) > 1)- .all()- )- duplicate_keys = [key[0] for key in duplicate_keys]-- # For each duplicate key, keep the latest updated one and remove others- for key in duplicate_keys:- dupe_settings = (- db_session.query(Setting)- .filter(Setting.key == key)- .order_by(Setting.updated_at.desc())- .all()- )-- # Keep the first one (most recently updated) and delete the rest- for i, setting in enumerate(dupe_settings):- if i > 0: # Skip the first one (keep it)- db_session.delete(setting)- removed_duplicate_settings.append(key)-- # Check for settings with corrupted values- all_settings = db_session.query(Setting).all()- for setting in all_settings:- # Check different types of corruption- is_corrupted = False-- if (- setting.value is None- or (- isinstance(setting.value, str)- and setting.value- in [- "{",- "[",- "{}",- "[]",- "[object Object]",- "null",- "undefined",- ]- )- or (- isinstance(setting.value, dict)- and len(setting.value) == 0- )- ):- is_corrupted = True-- # Skip if not corrupted- if not is_corrupted:- continue-- # Get default value from migrations- # Import commented out as it's not directly used- # from ...database.migrations import setup_predefined_settings-- default_value: Any = None-- # Try to find a matching default setting based on key- if setting.key.startswith("llm."):- if setting.key == "llm.model":- default_value = ""- elif setting.key == "llm.provider":- default_value = "ollama"- elif setting.key == "llm.temperature":- default_value = 0.7- elif setting.key == "llm.max_tokens":- default_value = 1024- elif setting.key.startswith("search."):- if setting.key == "search.tool":- default_value = DEFAULT_SEARCH_TOOL- elif setting.key == "search.max_results":- default_value = 10- elif setting.key == "search.region":- default_value = "us"- elif setting.key == "search.questions_per_iteration":- default_value = 3- elif setting.key == "search.searches_per_section":- default_value = 2- elif setting.key == "search.skip_relevance_filter":- default_value = False- elif setting.key == "search.safe_search":- default_value = True- elif setting.key == "search.search_language":- default_value = "English"- elif setting.key.startswith("report."):- if setting.key == "report.searches_per_section":- default_value = 2- elif setting.key.startswith("app."):- if (- setting.key == "app.theme"- or setting.key == "app.default_theme"- ):- # Keep in step with default_settings.json and the- # reset path above — three copies of this default- # exist and they drifted from the theme registry- # together.- default_value = "system"- elif setting.key == "app.enable_notifications" or (- setting.key == "app.enable_web"- or setting.key == "app.web_interface"- ):- default_value = True- elif setting.key == "app.host":- # noqa justified: this is the DEFAULT VALUE of a- # host setting being rendered, not a bind address.- default_value = "0.0.0.0" # noqa: S104- elif setting.key == "app.port":- default_value = 5000- elif setting.key == "app.debug":- default_value = True-- # Update the setting with the default value if found- if default_value is not None:- setting.value = default_value- fixed_settings.append(setting.key)- else:- # If no default found but it's a corrupted JSON, set to empty object- if setting.key.startswith("report."):- setting.value = {}- fixed_settings.append(setting.key)-- # Commit changes- if fixed_settings or removed_duplicate_settings:- try:- db_session.commit()- logger.info(- f"Fixed {len(fixed_settings)} corrupted settings: {', '.join(fixed_settings)}"- )- if removed_duplicate_settings:- logger.info(- f"Removed {len(removed_duplicate_settings)} duplicate settings"- )- except Exception:- db_session.rollback()- raise- invalidate_settings_caches(username)- changed_settings = list(- dict.fromkeys(fixed_settings + removed_duplicate_settings)- )- reschedule_document_jobs_if_needed(username, changed_settings)- reschedule_zotero_jobs_if_needed(username, changed_settings)-- # Return success- return {- "status": "success",- "message": f"Fixed {len(fixed_settings)} corrupted settings, removed {len(removed_duplicate_settings)} duplicates",- "fixed_settings": fixed_settings,- "removed_duplicates": removed_duplicate_settings,- }-- except Exception:- logger.exception("Error fixing corrupted settings")- return JSONResponse(- {- "status": "error",- "message": "An internal error occurred while fixing corrupted settings. Please try again later.",- },- status_code=500,- )--@router.get("/api/warnings")def api_get_warnings(request: Request, username: Annotated[str, Depends(require_auth)]diff --git a/src/local_deep_research/web/static/css/settings.css b/src/local_deep_research/web/static/css/settings.cssindex f021482970..a84d1f29de 100644--- a/src/local_deep_research/web/static/css/settings.css+++ b/src/local_deep_research/web/static/css/settings.css@@ -1138,18 +1138,6 @@filter: brightness(0.85);}-/* Add styling for Fix Corrupted Settings button */-#fix-corrupted-button {- margin-left: 10px;- background-color: var(--accent-primary);- color: var(--bg-primary);- border: none;-}--#fix-corrupted-button:hover {- background-color: var(--accent-secondary);-}-.ldr-settings-item .ldr-checkbox-label {margin-top: 8px;padding-left: 0;diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.jsindex b1c39dc67c..4738fcbc15 100644--- a/src/local_deep_research/web/static/js/components/settings.js+++ b/src/local_deep_research/web/static/js/components/settings.js@@ -4278,35 +4278,6 @@return window.api ? window.api.getCsrfToken() : '';}- /**- * Handle the fix corrupted settings button click- */- function handleFixCorruptedSettings() {- // Call the fix corrupted settings API- window.api.fetchWithErrorHandling(URLS.SETTINGS_API.FIX_CORRUPTED_SETTINGS, {- method: 'POST'- })- .then(data => {- if (data.status === 'success') {- if (data.fixed_settings && data.fixed_settings.length > 0) {- showAlert(`Fixed ${data.fixed_settings.length} corrupted settings. Reloading page...`, 'success');-- // Reload the page after a brief delay to show the success message- setTimeout(() => {- window.location.reload();- }, 1500);- } else {- showAlert('No corrupted settings were found.', 'info');- }- } else {- showAlert('Error fixing corrupted settings: ' + data.message, 'error');- }- })- .catch(error => {- showAlert('Error fixing corrupted settings: ' + error, 'error');- });- }-/*** Check if Ollama service is running* @returns {Promise<boolean>} True if Ollama is running@@ -5029,19 +5000,6 @@resetToDefaultsButton.addEventListener('click', handleResetToDefaults);}- // Add a fix corrupted settings button- const fixCorruptedButton = document.createElement('button');- fixCorruptedButton.setAttribute('type', 'button');- fixCorruptedButton.setAttribute('id', 'fix-corrupted-button');- fixCorruptedButton.className = 'btn btn-info';- fixCorruptedButton.innerHTML = '<i class="fas fa-wrench"></i> Fix Corrupted Settings';- fixCorruptedButton.addEventListener('click', handleFixCorruptedSettings);-- // Insert it after the reset to defaults button- if (resetToDefaultsButton) {- resetToDefaultsButton.insertAdjacentElement('afterend', fixCorruptedButton);- }-// Handle raw config toggleif (rawConfigToggle) {rawConfigToggle.addEventListener('click', toggleRawConfig);diff --git a/src/local_deep_research/web/static/js/config/urls.js b/src/local_deep_research/web/static/js/config/urls.jsindex fd0b0dbfec..230ac6f980 100644--- a/src/local_deep_research/web/static/js/config/urls.js+++ b/src/local_deep_research/web/static/js/config/urls.js@@ -95,8 +95,7 @@ if (typeof URLS !== 'undefined') {SEARCH_FAVORITES: '/settings/api/search-favorites',SEARCH_FAVORITES_TOGGLE: '/settings/api/search-favorites/toggle',SAVE_ALL_SETTINGS: '/settings/save_all_settings',- RESET_TO_DEFAULTS: '/settings/reset_to_defaults',- FIX_CORRUPTED_SETTINGS: '/settings/fix_corrupted_settings'+ RESET_TO_DEFAULTS: '/settings/reset_to_defaults'},// Metrics API routesdiff --git a/tests/database/test_alembic_migrations.py b/tests/database/test_alembic_migrations.pyindex 3ac1ff1c39..dd134fdb95 100644--- a/tests/database/test_alembic_migrations.py+++ b/tests/database/test_alembic_migrations.py@@ -697,6 +697,9 @@ class TestMigrationChain:"0026_add_app_logs_export_index.py","0027_disable_legacy_unprotected_egress.py","0028_expand_rag_index_identity.py",+ "0029_gate_filesystem_pdf_storage.py",+ "0030_default_time_period_all.py",+ "0031_reconcile_corrupted_settings.py",]for filename in expected_files:@@ -6155,6 +6158,9 @@ class TestMigrationSafetyGuards:# downgrade cannot know which rows were originally 'filesystem'. Same# rationale as 0019/0027. No-op by design."0029_gate_filesystem_pdf_storage.py",+ # 0031: restoring duplicate rows or legacy corruption sentinels would+ # recreate invalid settings, with no reliable way to recover prior rows.+ "0031_reconcile_corrupted_settings.py",}# Migrations whose downgrade is intentionally NotImplementedErrordiff --git a/tests/database/test_migration_0031_reconcile_corrupted_settings.py b/tests/database/test_migration_0031_reconcile_corrupted_settings.pynew file mode 100644index 0000000000..0f112a980d--- /dev/null+++ b/tests/database/test_migration_0031_reconcile_corrupted_settings.py@@ -0,0 +1,763 @@+"""Tests for migration 0031's targeted legacy-settings reconciliation."""++import json+import shutil+from importlib import import_module++import pytest+from alembic import command+from alembic.migration import MigrationContext+from alembic.operations import Operations+from sqlalchemy import create_engine, inspect, text+from sqlalchemy.exc import IntegrityError++from local_deep_research.database.alembic_runner import get_alembic_config+++MIGRATION = import_module(+ "local_deep_research.database.migrations.versions."+ "0031_reconcile_corrupted_settings"+)++# Frozen defaults at revision 0031. This is deliberately a historical+# snapshot: future default changes must not rewrite an already-shipped+# migration.+EXPECTED_DEFAULTS = {+ "app.debug": False,+ "app.enable_notifications": True,+ "app.enable_web": True,+ "app.host": "0.0.0.0",+ "app.port": 5000,+ "app.theme": "system",+ "app.web_interface": True,+ "llm.max_tokens": 30000,+ "llm.model": "",+ "llm.provider": "ollama",+ "llm.temperature": 0.7,+ "report.searches_per_section": 2,+ "search.max_results": 50,+ "search.questions_per_iteration": 1,+ "search.region": "us",+ "search.safe_search": True,+ "search.search_language": "English",+ "search.searches_per_section": 2,+ "search.skip_relevance_filter": True,+ "search.tool": "searxng",+}++STRING_SENTINELS = (+ "{",+ "[",+ "{}",+ "[]",+ "[object Object]",+ "null",+ "undefined",+)+LEGACY_SENTINELS = (+ None,+ *STRING_SENTINELS,+ {},+)+REGISTRY_BACKED_KEYS = (+ "app.theme",+ "llm.provider",+ "search.tool",+)+AMBIGUOUS_STRING_KEYS = {+ "app.host",+ "app.theme",+ "llm.model",+ "llm.provider",+ "search.tool",+}+++def _migrate(engine, revision, downgrade=False):+ config = get_alembic_config(engine)+ with engine.begin() as conn:+ config.attributes["connection"] = conn+ (command.downgrade if downgrade else command.upgrade)(config, revision)+++def _seed_raw(engine, key, raw_value):+ with engine.begin() as conn:+ conn.execute(+ text(+ "INSERT INTO settings "+ "(key, value, type, name, ui_element, visible, editable) "+ "VALUES (:key, :value, 'app', :key, 'text', 1, 1)"+ ),+ {"key": key, "value": raw_value},+ )+++def _seed(engine, key, value):+ _seed_raw(engine, key, json.dumps(value))+++def _seed_legacy_duplicates(engine, rows):+ with engine.begin() as conn:+ conn.execute(text("DROP INDEX ix_settings_key"))+ conn.execute(+ text(+ "INSERT INTO settings "+ "(key, value, type, name, ui_element, visible, editable, "+ "created_at, updated_at) "+ "VALUES (:key, :value, 'APP', :key, :ui_element, 1, 1, "+ ":updated_at, :updated_at)"+ ),+ rows,+ )+++def _read_raw(engine, key):+ with engine.begin() as conn:+ row = conn.execute(+ text("SELECT value FROM settings WHERE key = :key"), {"key": key}+ ).one_or_none()+ return None if row is None else row[0]+++def _read(engine, key):+ raw_value = _read_raw(engine, key)+ if raw_value is None or not isinstance(raw_value, (str, bytes, bytearray)):+ return raw_value+ return json.loads(raw_value)++[email protected](scope="module")+def database_at_0025(tmp_path_factory):+ database_path = tmp_path_factory.mktemp("migration_0031") / "base.db"+ engine = create_engine(f"sqlite:///{database_path}")+ _migrate(engine, "0025")+ engine.dispose()+ return database_path+++def engine_at_0025(database_at_0025, tmp_path):+ database_path = tmp_path / "migration_0031.db"+ shutil.copyfile(database_at_0025, database_path)+ engine = create_engine(f"sqlite:///{database_path}")+ yield engine+ engine.dispose()+++def test_upgrade_repairs_every_target_with_frozen_current_default(+ engine_at_0025,+):+ assert MIGRATION.REPAIR_DEFAULTS == EXPECTED_DEFAULTS++ for key in EXPECTED_DEFAULTS:+ # Ambiguous identifier strings are valid for these keys, so exercise+ # their unambiguous native-object repair path instead.+ value = {} if key in AMBIGUOUS_STRING_KEYS else "undefined"+ _seed(engine_at_0025, key, value)++ _migrate(engine_at_0025, "0031")++ assert {+ key: _read(engine_at_0025, key) for key in EXPECTED_DEFAULTS+ } == EXPECTED_DEFAULTS+++def test_upgrade_deduplicates_legacy_rows_and_restores_unique_index(+ engine_at_0025,+):+ legacy_rows = (+ # Newest timestamp wins for a packaged key.+ {+ "key": "llm.provider",+ "value": json.dumps("older-provider"),+ "updated_at": "2026-01-01 00:00:00",+ },+ {+ "key": "llm.provider",+ "value": json.dumps("newer-provider"),+ "updated_at": "2026-01-02 00:00:00",+ },+ # Highest id wins when timestamps tie, including for custom keys.+ {+ "key": "custom.plugin.setting",+ "value": json.dumps("lower-id"),+ "updated_at": "2026-01-03 00:00:00",+ },+ {+ "key": "custom.plugin.setting",+ "value": json.dumps("higher-id"),+ "updated_at": "2026-01-03 00:00:00",+ },+ # A newer corruption sentinel must not displace an older usable value.+ {+ "key": "search.region",+ "value": json.dumps("de"),+ "updated_at": "2026-01-01 00:00:00",+ },+ {+ "key": "search.region",+ "value": json.dumps("undefined"),+ "updated_at": "2026-01-02 00:00:00",+ },+ )+ with engine_at_0025.begin() as conn:+ conn.execute(text("DROP INDEX ix_settings_key"))+ conn.execute(+ text(+ "INSERT INTO settings "+ "(key, value, type, name, ui_element, visible, editable, "+ "created_at, updated_at) "+ "VALUES (:key, :value, 'APP', :key, 'text', 1, 1, "+ ":updated_at, :updated_at)"+ ),+ legacy_rows,+ )++ assert not any(+ index["name"] == "ix_settings_key"+ for index in inspect(engine_at_0025).get_indexes("settings")+ )++ _migrate(engine_at_0025, "0031")++ assert _read(engine_at_0025, "llm.provider") == "newer-provider"+ assert _read(engine_at_0025, "custom.plugin.setting") == "higher-id"+ assert _read(engine_at_0025, "search.region") == "de"+ with engine_at_0025.connect() as conn:+ duplicate_count = conn.execute(+ text(+ "SELECT COUNT(*) FROM ("+ "SELECT key FROM settings GROUP BY key HAVING COUNT(*) > 1"+ ")"+ )+ ).scalar_one()+ assert duplicate_count == 0++ key_index = next(+ index+ for index in inspect(engine_at_0025).get_indexes("settings")+ if index["name"] == "ix_settings_key"+ )+ assert key_index["unique"]++ with pytest.raises(IntegrityError):+ with engine_at_0025.begin() as conn:+ conn.execute(+ text(+ "INSERT INTO settings "+ "(key, value, type, name, ui_element, visible, editable) "+ "VALUES ('llm.provider', '\"duplicate\"', 'APP', "+ "'Provider', 'text', 1, 1)"+ )+ )++[email protected]("sentinel", ("undefined", "[REDACTED]"))[email protected]("ui_element", ("password", "text"))+def test_deduplication_preserves_older_valid_credential(+ engine_at_0025,+ ui_element,+ sentinel,+):+ legacy_rows = (+ {+ "key": "llm.openai.api_key",+ "value": json.dumps("valid-credential"),+ "updated_at": "2026-01-01 00:00:00",+ "ui_element": ui_element,+ },+ {+ "key": "llm.openai.api_key",+ "value": json.dumps(sentinel),+ "updated_at": "2026-01-02 00:00:00",+ "ui_element": ui_element,+ },+ )+ _seed_legacy_duplicates(engine_at_0025, legacy_rows)++ _migrate(engine_at_0025, "0031")++ assert _read(engine_at_0025, "llm.openai.api_key") == "valid-credential"+++def test_deduplication_uses_password_metadata_from_the_whole_key_group(+ engine_at_0025,+):+ key = "llm.custom.credential"+ _seed_legacy_duplicates(+ engine_at_0025,+ (+ {+ "key": key,+ "value": json.dumps("valid-credential"),+ "updated_at": "2026-01-01 00:00:00",+ "ui_element": "password",+ },+ {+ "key": key,+ "value": json.dumps("undefined"),+ "updated_at": "2026-01-02 00:00:00",+ "ui_element": "text",+ },+ ),+ )++ _migrate(engine_at_0025, "0031")++ assert _read(engine_at_0025, key) == "valid-credential"++[email protected]("ui_variant", ("Password", " password ", "PASSWORD"))+def test_deduplication_recognizes_noncanonical_password_metadata(+ engine_at_0025,+ ui_variant,+):+ """Legacy/imported rows may carry non-canonical ui_element variants.++ A key whose leaf is not in _SENSITIVE_KEY_LEAVES (e.g. 'credential') must+ still be treated as sensitive when ui_element is a case/whitespace variant+ of 'password'. Otherwise the migration could keep a corruption sentinel+ and delete the only valid credential.+ """+ key = "llm.custom.credential"+ _seed_legacy_duplicates(+ engine_at_0025,+ (+ {+ "key": key,+ "value": json.dumps("valid-credential"),+ "updated_at": "2026-01-01 00:00:00",+ "ui_element": ui_variant,+ },+ {+ "key": key,+ "value": json.dumps("undefined"),+ "updated_at": "2026-01-02 00:00:00",+ "ui_element": ui_variant,+ },+ ),+ )++ _migrate(engine_at_0025, "0031")++ assert _read(engine_at_0025, key) == "valid-credential"++[email protected]("padding", ("\u200b", "\u034f"))+def test_deduplication_normalizes_invisible_sensitive_key_padding(+ engine_at_0025,+ padding,+):+ key = f"llm.openai.api_key{padding}"+ _seed_legacy_duplicates(+ engine_at_0025,+ (+ {+ "key": key,+ "value": json.dumps("valid-credential"),+ "updated_at": "2026-01-01 00:00:00",+ "ui_element": "text",+ },+ {+ "key": key,+ "value": json.dumps("undefined"),+ "updated_at": "2026-01-02 00:00:00",+ "ui_element": "text",+ },+ ),+ )++ _migrate(engine_at_0025, "0031")++ assert _read(engine_at_0025, key) == "valid-credential"++[email protected]("cleared_raw_value", (None, json.dumps(None)))+def test_deduplication_preserves_newer_intentionally_cleared_credential(+ engine_at_0025,+ cleared_raw_value,+):+ key = "llm.xai.api_key"+ _seed_legacy_duplicates(+ engine_at_0025,+ (+ {+ "key": key,+ "value": json.dumps("old-credential"),+ "updated_at": "2026-01-01 00:00:00",+ "ui_element": "password",+ },+ {+ "key": key,+ "value": cleared_raw_value,+ "updated_at": "2026-01-02 00:00:00",+ "ui_element": "password",+ },+ ),+ )++ _migrate(engine_at_0025, "0031")++ assert _read_raw(engine_at_0025, key) == cleared_raw_value+++def test_index_replacement_rolls_back_with_the_migration(+ engine_at_0025,+ monkeypatch,+):+ _seed(engine_at_0025, "search.region", "undefined")+ with engine_at_0025.begin() as conn:+ conn.execute(text("DROP INDEX ix_settings_key"))+ conn.execute(text("CREATE INDEX ix_settings_key ON settings (key)"))++ conn = engine_at_0025.connect()+ transaction = conn.begin()+ migration_op = Operations(MigrationContext.configure(conn))+ monkeypatch.setattr(MIGRATION, "op", migration_op)+ try:+ MIGRATION.upgrade()+ migrated_index = next(+ index+ for index in inspect(conn).get_indexes("settings")+ if index["name"] == "ix_settings_key"+ )+ assert migrated_index["unique"]+ finally:+ transaction.rollback()+ conn.close()++ rolled_back_index = next(+ index+ for index in inspect(engine_at_0025).get_indexes("settings")+ if index["name"] == "ix_settings_key"+ )+ assert not rolled_back_index["unique"]+ assert _read(engine_at_0025, "search.region") == "undefined"++[email protected]("sentinel", LEGACY_SENTINELS)+def test_upgrade_repairs_each_legacy_sentinel(engine_at_0025, sentinel):+ _seed(engine_at_0025, "search.region", sentinel)++ _migrate(engine_at_0025, "0031")++ assert _read(engine_at_0025, "search.region") == "us"+++def test_upgrade_repairs_defensive_sql_null(engine_at_0025):+ _seed_raw(engine_at_0025, "llm.provider", None)++ _migrate(engine_at_0025, "0031")++ assert _read(engine_at_0025, "llm.provider") == "ollama"+++def test_upgrade_repairs_blob_encoded_json_sentinel(engine_at_0025):+ _seed_raw(+ engine_at_0025,+ "search.region",+ json.dumps("undefined").encode("utf-8"),+ )++ with engine_at_0025.begin() as conn:+ storage_type = conn.execute(+ text(+ "SELECT typeof(value) FROM settings WHERE key = 'search.region'"+ )+ ).scalar_one()+ assert storage_type == "blob"++ _migrate(engine_at_0025, "0031")++ assert _read(engine_at_0025, "search.region") == "us"+++ "model_name",+ STRING_SENTINELS,+)+def test_upgrade_preserves_ambiguous_free_form_model_names(+ engine_at_0025,+ model_name,+):+ _seed(engine_at_0025, "llm.model", model_name)++ _migrate(engine_at_0025, "0031")++ assert _read(engine_at_0025, "llm.model") == model_name++[email protected]("key", REGISTRY_BACKED_KEYS)[email protected]("identifier", STRING_SENTINELS)[email protected]("storage_class", ("text", "blob"))+def test_upgrade_preserves_ambiguous_registry_identifiers(+ engine_at_0025,+ key,+ identifier,+ storage_class,+):+ raw_value = json.dumps(identifier)+ if storage_class == "blob":+ raw_value = raw_value.encode("utf-8")+ _seed_raw(engine_at_0025, key, raw_value)++ _migrate(engine_at_0025, "0031")++ assert _read(engine_at_0025, key) == identifier++[email protected]("key", REGISTRY_BACKED_KEYS)[email protected]("structural_value", (None, {}))+def test_upgrade_repairs_structural_corruption_for_registry_settings(+ engine_at_0025,+ key,+ structural_value,+):+ _seed(engine_at_0025, key, structural_value)++ _migrate(engine_at_0025, "0031")++ assert _read(engine_at_0025, key) == EXPECTED_DEFAULTS[key]++[email protected]("hostname", ("null", "undefined"))[email protected]("storage_class", ("text", "blob"))+def test_upgrade_preserves_ambiguous_valid_hostnames(+ engine_at_0025,+ hostname,+ storage_class,+):+ raw_value = json.dumps(hostname)+ if storage_class == "blob":+ raw_value = raw_value.encode("utf-8")+ _seed_raw(engine_at_0025, "app.host", raw_value)++ _migrate(engine_at_0025, "0031")++ assert _read(engine_at_0025, "app.host") == hostname+++ "invalid_hostname",+ ("{", "[", "{}", "[]", "[object Object]"),+)+def test_upgrade_repairs_unambiguous_invalid_host_sentinels(+ engine_at_0025,+ invalid_hostname,+):+ _seed(engine_at_0025, "app.host", invalid_hostname)++ _migrate(engine_at_0025, "0031")++ assert _read(engine_at_0025, "app.host") == "0.0.0.0"+++def test_upgrade_preserves_valid_target_values_and_unrelated_settings(+ engine_at_0025,+):+ preserved = {+ "llm.provider": "openai",+ "app.host": "127.0.0.1",+ "search.safe_search": False,+ # Native empty lists were never classified as corruption.+ "llm.model": [],+ # Sentinel-like values outside the exact key allowlist stay untouched.+ "llm.openai.api_key": "undefined",+ "llm.allowed_local_hostnames": {},+ "policy.trusted_search_engines": [],+ "report.unknown": "[object Object]",+ "app.default_theme": "null",+ }+ for key, value in preserved.items():+ _seed(engine_at_0025, key, value)++ _migrate(engine_at_0025, "0031")++ assert {key: _read(engine_at_0025, key) for key in preserved} == preserved+++ "near_match",+ ("", " undefined ", "Undefined", ["undefined"], {"value": "undefined"}),+)+def test_upgrade_preserves_near_matches(engine_at_0025, near_match):+ _seed(engine_at_0025, "llm.provider", near_match)++ _migrate(engine_at_0025, "0031")++ assert _read(engine_at_0025, "llm.provider") == near_match++[email protected]("raw_value", ("undefined", b"undefined"))+def test_upgrade_leaves_malformed_raw_json_untouched(+ engine_at_0025,+ raw_value,+):+ _seed_raw(engine_at_0025, "llm.provider", raw_value)++ _migrate(engine_at_0025, "0031")++ assert _read_raw(engine_at_0025, "llm.provider") == raw_value+++def test_repair_is_value_idempotent(engine_at_0025):+ _seed(engine_at_0025, "search.region", "undefined")+ _migrate(engine_at_0025, "0031")++ with engine_at_0025.begin() as conn:+ assert MIGRATION._repair_corrupted_values(conn) == 0++ assert _read(engine_at_0025, "search.region") == "us"+++def test_downgrade_is_noop_for_repaired_values(engine_at_0025):+ _seed(engine_at_0025, "search.region", "undefined")+ _migrate(engine_at_0025, "0031")++ _migrate(engine_at_0025, "0025", downgrade=True)++ assert _read(engine_at_0025, "search.region") == "us"+++def test_0031_chains_to_0030():+ from alembic.config import Config+ from alembic.script import ScriptDirectory++ from local_deep_research.database.alembic_runner import get_migrations_dir++ config = Config()+ config.set_main_option("script_location", str(get_migrations_dir()))+ script = ScriptDirectory.from_config(config)+ assert script.get_revision("0031").down_revision == "0030"++[email protected]("ui_element", ("password", " Password ", "PASSWORD"))[email protected]("key", ("app.theme", "search.region"))+def test_repair_preserves_password_metadata_on_allowlisted_keys(+ engine_at_0025, ui_element, key+):+ """A repair allowlist must not override a legacy row's secret metadata."""+ _seed_raw(engine_at_0025, key, None)+ with engine_at_0025.begin() as conn:+ conn.execute(+ text("UPDATE settings SET ui_element=:ui WHERE key=:key"),+ {"ui": ui_element, "key": key},+ )++ _migrate(engine_at_0025, "0031")++ assert _read_raw(engine_at_0025, key) is None+++def test_repair_retains_sensitive_metadata_from_discarded_duplicate(+ engine_at_0025,+):+ """Deleting an older row must not turn a newer intentional clear into a default."""+ _seed_legacy_duplicates(+ engine_at_0025,+ (+ {+ "key": "app.theme",+ "value": json.dumps("older-secret"),+ "updated_at": "2026-01-01 00:00:00",+ "ui_element": "password",+ },+ {+ "key": "app.theme",+ "value": None,+ "updated_at": "2026-01-02 00:00:00",+ "ui_element": "text",+ },+ ),+ )++ _migrate(engine_at_0025, "0031")++ assert _read_raw(engine_at_0025, "app.theme") is None+ with engine_at_0025.connect() as conn:+ assert (+ conn.execute(+ text("SELECT COUNT(*) FROM settings WHERE key='app.theme'")+ ).scalar_one()+ == 1+ )+ assert (+ conn.execute(+ text("SELECT ui_element FROM settings WHERE key='app.theme'")+ ).scalar_one()+ == "password"+ )++ # A no-op downgrade followed by re-upgrade must retain the same clear.+ _migrate(engine_at_0025, "0030", downgrade=True)+ _migrate(engine_at_0025, "0031")+ assert _read_raw(engine_at_0025, "app.theme") is None++[email protected]("sentinel", ("[REDACTED]", "undefined"))+def test_deduplication_preserves_usable_notification_service_url(+ engine_at_0025, sentinel+):+ """The notification URL is a credential even though its input is a textarea."""+ value = "mailto://synthetic-user:[email protected]"+ _seed_legacy_duplicates(+ engine_at_0025,+ (+ {+ "key": "notifications.service_url",+ "value": json.dumps(value),+ "updated_at": "2026-01-01 00:00:00",+ "ui_element": "textarea",+ },+ {+ "key": "notifications.service_url",+ "value": json.dumps(sentinel),+ "updated_at": "2026-01-02 00:00:00",+ "ui_element": "textarea",+ },+ ),+ )++ _migrate(engine_at_0025, "0031")++ assert _read(engine_at_0025, "notifications.service_url") == value+++def test_index_failure_rolls_back_when_all_repair_targets_are_sensitive(+ engine_at_0025, monkeypatch+):+ """Skipping all value repairs must still open a driver transaction for DDL."""+ for key in EXPECTED_DEFAULTS:+ _seed_raw(engine_at_0025, key, None)+ with engine_at_0025.begin() as conn:+ conn.execute(text("UPDATE settings SET ui_element='password'"))+ conn.execute(text("DROP INDEX ix_settings_key"))+ conn.execute(text("CREATE INDEX ix_settings_key ON settings (key)"))++ conn = engine_at_0025.connect()+ transaction = conn.begin()+ migration_op = Operations(MigrationContext.configure(conn))+ monkeypatch.setattr(MIGRATION, "op", migration_op)++ def fail_index_creation(*args, **kwargs):+ raise RuntimeError("synthetic index creation failure")++ monkeypatch.setattr(migration_op, "create_index", fail_index_creation)+ try:+ with pytest.raises(+ RuntimeError, match="synthetic index creation failure"+ ):+ MIGRATION.upgrade()+ finally:+ transaction.rollback()+ conn.close()++ restored_index = next(+ index+ for index in inspect(engine_at_0025).get_indexes("settings")+ if index["name"] == "ix_settings_key"+ )+ assert not restored_index["unique"]+ assert all(+ _read_raw(engine_at_0025, key) is None for key in EXPECTED_DEFAULTS+ )diff --git a/tests/js/components/settings-dashboard-runtime.test.js b/tests/js/components/settings-dashboard-runtime.test.jsindex 53f1f408b0..d3201dc52a 100644--- a/tests/js/components/settings-dashboard-runtime.test.js+++ b/tests/js/components/settings-dashboard-runtime.test.js@@ -183,7 +183,6 @@ it('renders aliased policy settings, clears a redacted secret, and recovers from};const saveBodies = [];let resetShouldFail = false;- let fixCorruptedSettings = false;const fetchMock = vi.fn((url, options = {}) => {if (url === URLS.SETTINGS_API.BASE) {return Promise.resolve(jsonResponse({ status: 'success', settings }));@@ -232,12 +231,6 @@ it('renders aliased policy settings, clears a redacted secret, and recovers fromdetail: '<img src=x onerror=alert(1)> reset denied',}, 422));}- if (url === URLS.SETTINGS_API.FIX_CORRUPTED_SETTINGS && fixCorruptedSettings) {- return Promise.resolve(jsonResponse({- status: 'success',- fixed_settings: [],- }));- }throw new Error(`Unexpected request: ${url}`);});vi.stubGlobal('fetch', fetchMock);@@ -488,14 +481,7 @@ it('renders aliased policy settings, clears a redacted secret, and recovers from);expect(document.getElementById('settings-alert').querySelector('img')).toBeNull();- fixCorruptedSettings = true;- document.getElementById('fix-corrupted-button').click();- await flushPromises();- expect(fetchMock).toHaveBeenCalledWith(- URLS.SETTINGS_API.FIX_CORRUPTED_SETTINGS,- expect.objectContaining({ method: 'POST' }),- );- expect(document.getElementById('settings-alert').textContent).toContain(- 'No corrupted settings were found.',- );+ // Upgrade migration 0031 replaces the manual corruption-repair control.+ expect(document.getElementById('fix-corrupted-button')).toBeNull();+ expect(URLS.SETTINGS_API.FIX_CORRUPTED_SETTINGS).toBeUndefined();});diff --git a/tests/js/components/settings-fetch-error-handling.test.js b/tests/js/components/settings-fetch-error-handling.test.jsindex b0ab5930c3..52f401439a 100644--- a/tests/js/components/settings-fetch-error-handling.test.js+++ b/tests/js/components/settings-fetch-error-handling.test.js@@ -44,14 +44,13 @@ afterEach(() => {});describe('settings request error handling', () => {- it('routes exactly the seven target requests through the shared helper', () => {+ it('routes exactly the six target requests through the shared helper', () => {const handledPatterns = ['window.api.fetchWithErrorHandling(URLS.SETTINGS_API.BASE)',"window.api.fetchWithErrorHandling('/settings/api/data-location')",'window.api.fetchWithErrorHandling(URLS.SETTINGS_API.BACKUP_STATUS)','window.api.fetchWithErrorHandling(URLS.SETTINGS_API.SAVE_ALL_SETTINGS, {','window.api.fetchWithErrorHandling(URLS.SETTINGS_API.RESET_TO_DEFAULTS, {',- 'window.api.fetchWithErrorHandling(URLS.SETTINGS_API.FIX_CORRUPTED_SETTINGS, {',"window.api.fetchWithErrorHandling('/settings/api/notifications/test-url', {",];const excludedPatterns = [@@ -70,14 +69,14 @@ describe('settings request error handling', () => {excludedPatterns.forEach(pattern => {expect(SETTINGS_SOURCE).toContain(pattern);});- expect(handledCalls).toHaveLength(7);+ expect(handledCalls).toHaveLength(6);expect(rawCalls).toHaveLength(3);});it('preserves the settings domain success and failure checks', () => {expect(SETTINGS_SOURCE.match(/if \(data\.status === 'success'\)/g) || []- ).toHaveLength(4);+ ).toHaveLength(3);expect(SETTINGS_SOURCE.match(/if \(data\.success\)/g) || []).toHaveLength(1);});diff --git a/tests/settings/test_settings_defaults_integrity.py b/tests/settings/test_settings_defaults_integrity.pyindex 13818f3cec..4fdfd3980e 100644--- a/tests/settings/test_settings_defaults_integrity.py+++ b/tests/settings/test_settings_defaults_integrity.py@@ -41,8 +41,11 @@ ENUM_SETTINGS = {KNOWN_UNUSED = {# Truly unused / dead code (candidates for future removal)"report.export_formats",+ # Retained defaults whose last Python consumer was the obsolete repair route.+ "report.searches_per_section","research_library.confirm_deletions","search.quality_check_urls",+ "search.searches_per_section",# Only ever consumed by the iterdrag/standard strategies, which were# removed when the experimental strategies were dropped. The setting and# its KnowledgeAccumulationApproach enum are now dead; left in defaultsdiff --git a/tests/settings/test_settings_manager_contracts.py b/tests/settings/test_settings_manager_contracts.pyindex 42679f6e81..ab59e2af40 100644--- a/tests/settings/test_settings_manager_contracts.py+++ b/tests/settings/test_settings_manager_contracts.py@@ -45,8 +45,8 @@ as a whole rather than one method:both implementations, across the ui_element types whose coerciondiffers.-DELIBERATELY NOT COVERED -- filed upstream, do not duplicate: #5735-(``fix_corrupted_settings`` writes while locked), #5737 (``import_settings``+DELIBERATELY NOT COVERED -- filed upstream, do not duplicate: #5737+(``import_settings``lock refusal is a silent no-op / ``load_from_defaults_file`` logs a falsesuccess), #5738 (``override_locked`` missing from the ABC and from thein-memory implementation), #5739 (``settings_locked`` fails open, latentdiff --git a/tests/settings/test_shipped_defaults_contracts.py b/tests/settings/test_shipped_defaults_contracts.pyindex 1def87b13a..4a6e074d80 100644--- a/tests/settings/test_shipped_defaults_contracts.py+++ b/tests/settings/test_shipped_defaults_contracts.py@@ -38,7 +38,6 @@ broken, and the day it is fixed this test turns red until the marker isdeleted". Each carries the defect in its ``reason``."""-import astimport functoolsimport jsonimport os@@ -75,7 +74,6 @@ from local_deep_research.web import server_configREPO_ROOT = Path(__file__).resolve().parent.parent.parentSRC_DIR = REPO_ROOT / "src" / "local_deep_research"DEFAULTS_DIR = SRC_DIR / "defaults"-SETTINGS_ROUTER = SRC_DIR / "web" / "routers" / "settings.py"# Floors. A sweep that loads nothing and passes is the failure mode these# guard against: every test below asserts against one of them so an empty@@ -1430,89 +1428,13 @@ class TestRegistryConsistency:f"in src/: {orphans[:20]}")- @pytest.mark.xfail(- strict=True,- reason=(- "DEFECT: the /settings 'fix corrupted settings' repair path in "- "web/routers/settings.py keeps a fourth hardcoded copy of the "- "defaults, and five entries have drifted from the shipped "- "JSON. The security-relevant one is app.debug, which the "- "repair path restores to True while the shipped default is "- "False -- repairing a null app.debug row turns debug logging "- "on and feeds uvicorn's debug flag. The rest are behavioural: "- "llm.max_tokens 1024 vs 30000, search.max_results 10 vs 50, "- "search.questions_per_iteration 3 vs 1, "- "search.skip_relevance_filter False vs True. app.default_theme "- "is repaired to a value that has no shipped default at all. "- "Fix by reading SettingsManager().default_settings instead of "- "restating the values."- ),- )- def test_repair_path_defaults_match_the_shipped_defaults(self):- repair = _extract_repair_defaults()- assert len(repair) >= 15, (- f"only {len(repair)} repair defaults extracted from "- f"{SETTINGS_ROUTER}; the AST walk is not finding the block"- )- defaults = raw_defaults()- drift = {}- for key, value in sorted(repair.items()):- if key not in defaults:- drift[key] = (value, "<no shipped default>")- elif defaults[key]["value"] != value:- drift[key] = (value, defaults[key]["value"])- assert not drift, (- "the settings repair path restores values that differ from "- "the shipped defaults (key: (repair value, shipped value)): "- + repr(drift)- )--[email protected]_cache(maxsize=1)-def _extract_repair_defaults() -> Dict[str, Any]:- """Read the repair block's ``setting.key == "x" -> default_value = y``- pairs out of the router's AST.-- Parsed from the production source rather than transcribed, so this- cannot drift into asserting against a private copy of the same logic.- """- tree = ast.parse(SETTINGS_ROUTER.read_text(encoding="utf-8"))- found: Dict[str, Any] = {}-- def keys_of(test: ast.expr) -> List[str]:- if isinstance(test, ast.BoolOp) and isinstance(test.op, ast.Or):- out: List[str] = []- for value in test.values:- out.extend(keys_of(value))- return out- if (- isinstance(test, ast.Compare)- and len(test.ops) == 1- and isinstance(test.ops[0], ast.Eq)- and isinstance(test.left, ast.Attribute)- and test.left.attr == "key"- and isinstance(test.left.value, ast.Name)- and test.left.value.id == "setting"- and isinstance(test.comparators[0], ast.Constant)- and isinstance(test.comparators[0].value, str)- ):- return [test.comparators[0].value]- return []-- for node in ast.walk(tree):- if not isinstance(node, ast.If):- continue- keys = keys_of(node.test)- if not keys:- continue- for statement in node.body:- if (- isinstance(statement, ast.Assign)- and len(statement.targets) == 1- and isinstance(statement.targets[0], ast.Name)- and statement.targets[0].id == "default_value"- and isinstance(statement.value, ast.Constant)- ):- for key in keys:- found[key] = statement.value.value- return found+ # test_repair_path_defaults_match_the_shipped_defaults used to live+ # here: it AST-walked the /settings "fix corrupted settings" repair+ # block (via the private helper _extract_repair_defaults) to catch+ # drift between that block's hardcoded defaults and the shipped+ # JSON. Both the repair path and the endpoint were removed in favour+ # of migration 0031 (src/local_deep_research/database/migrations/+ # versions/0031_reconcile_corrupted_settings.py), and the same+ # drift-against-shipped-defaults contract is now pinned by+ # tests/database/test_migration_0031_reconcile_corrupted_settings.py+ # ::test_upgrade_repairs_every_target_with_frozen_current_default.diff --git a/tests/test_advertised_but_dead_sweep.py b/tests/test_advertised_but_dead_sweep.pyindex 838b90b67a..11540580a7 100644--- a/tests/test_advertised_but_dead_sweep.py+++ b/tests/test_advertised_but_dead_sweep.py@@ -370,18 +370,14 @@ def test_no_advertised_route_is_unreachable():# ``app.warnings.dismiss_``, ``news.scheduler.``,# ``search.engine.web.``) marks every key under it as possibly read;# * migrations, ``env_definitions`` and the defaults themselves are not-# readers, and neither is ``fix_corrupted_settings`` — that endpoint-# names keys only to coerce a corrupted stored value back to a scalar,-# which is repair, not consumption.+# readers: repairing stored values does not consume configuration.# ---------------------------------------------------------------------------SETTINGS_SOURCE_EXCLUDED_DIRS = {"defaults", "migrations", "env_definitions"}# (path relative to the package root, function name) whose body names setting# keys without ever acting on their values.-SETTINGS_NON_READER_FUNCTIONS = {- ("web/routers/settings.py", "fix_corrupted_settings"),-}+SETTINGS_NON_READER_FUNCTIONS: set[tuple[str, str]] = set()@functools.cachediff --git a/tests/ui_tests/test_settings_save.js b/tests/ui_tests/test_settings_save.jsindex b540137446..d48d4f52aa 100644--- a/tests/ui_tests/test_settings_save.js+++ b/tests/ui_tests/test_settings_save.js@@ -3,10 +3,13 @@** Tests the settings auto-save workflow by monitoring network requests,* console messages, and response handling. Specifically tests the- * save_all_settings endpoint and validates that no bulk-submit button is shown.+ * save_all_settings endpoint, retains Reset to Defaults, and omits Fix+ * Corrupted Settings alongside the bulk-submit button.** What this tests:* - Save All Settings button is absent+ * - Reset to Defaults button is present+ * - Fix Corrupted Settings button is absent* - Per-setting auto-save functionality* - Network request monitoring for save operations* - API response validation (200 vs 4xx/5xx errors)@@ -58,6 +61,16 @@ async function testSettingsSave() {throw new Error('Save All Settings button should not be present');}+ const resetToDefaultsButton = await page.$('#reset-to-defaults-button');+ if (!resetToDefaultsButton) {+ throw new Error('Reset to Defaults button should be present');+ }++ const fixCorruptedButton = await page.$('#fix-corrupted-button');+ if (fixCorruptedButton) {+ throw new Error('Fix Corrupted Settings button should not be present');+ }+// Settings sections start collapsed on every viewport now, so the// checkbox is rendered inside a `display: none` body. Open its// section before clicking, or the click has no box to land on.@@ -65,6 +78,11 @@ async function testSettingsSave() {await expandSettingsSectionFor(page, checkboxSelector, { timeout: 15000 });const checkbox = await page.$(checkboxSelector);+ const checkboxState = await checkbox.evaluate(element => ({+ key: element.name,+ value: element.checked,+ }));+ const expectedValue = !checkboxState.value;const responsePromise = page.waitForResponse(r => r.url().includes('/save_all_settings'),{ timeout: 15000 }@@ -75,6 +93,34 @@ async function testSettingsSave() {if (!response.ok()) {throw new Error(`Auto-save failed with HTTP ${response.status()}`);}+ const responseData = await response.json();+ if (responseData.status !== 'success') {+ throw new Error(`Auto-save returned status ${responseData.status}`);+ }+ if (!responseData.updated?.includes(checkboxState.key)) {+ throw new Error(`Auto-save did not update ${checkboxState.key}`);+ }+ if (responseData.settings?.[checkboxState.key]?.value !== expectedValue) {+ throw new Error(+ `Auto-save response did not contain the new value for ${checkboxState.key}`+ );+ }++ const persisted = await page.evaluate(async key => {+ const persistedResponse = await fetch(`/settings/api/${encodeURIComponent(key)}`);+ return {+ ok: persistedResponse.ok,+ status: persistedResponse.status,+ data: await persistedResponse.json(),+ };+ }, checkboxState.key);+ if (!persisted.ok) {+ throw new Error(`Could not read saved setting: HTTP ${persisted.status}`);+ }+ if (persisted.data.value !== expectedValue) {+ throw new Error(`Auto-save did not persist ${checkboxState.key}`);+ }+console.log('✅ Per-setting auto-save completed without a bulk-submit button');diff --git a/tests/web/routers/test_router_sibling_consistency.py b/tests/web/routers/test_router_sibling_consistency.pyindex 7b480312da..9dea058530 100644--- a/tests/web/routers/test_router_sibling_consistency.py+++ b/tests/web/routers/test_router_sibling_consistency.py@@ -514,7 +514,6 @@ SETTINGS_VALUE_MUTATION_LIMITED = {("POST", "/settings/reset_to_defaults"),("POST", "/settings/save_settings"),("POST", "/settings/api/import"),- ("POST", "/settings/fix_corrupted_settings"),("PUT", "/settings/api/{key}"),("DELETE", "/settings/api/{key}"),# Both search-favorites writers were missing @settings_limit whilediff --git a/tests/web/routers/test_settings_api.py b/tests/web/routers/test_settings_api.pyindex e1d0cdebf3..084772e272 100644--- a/tests/web/routers/test_settings_api.py+++ b/tests/web/routers/test_settings_api.py@@ -459,3 +459,9 @@ class TestNoJsSaveSettingsFeedback:assert "Settings saved" in page.text, ("no-JS save must flash a visible confirmation on /settings/")+++def test_manual_corruption_repair_endpoint_is_removed(auth_client):+ """Migration 0031 replaces the authenticated manual repair operation."""+ response = auth_client.post("/settings/fix_corrupted_settings")+ assert response.status_code == 404diff --git a/tests/web/routers/test_settings_persistence_contracts.py b/tests/web/routers/test_settings_persistence_contracts.pyindex 25c0ed7a02..660df819c4 100644--- a/tests/web/routers/test_settings_persistence_contracts.py+++ b/tests/web/routers/test_settings_persistence_contracts.py@@ -58,8 +58,7 @@ one is currently proved for *some* of the routes that can write:it is also the part of this file that still runs when the HTTP harnesscannot.-DELIBERATELY NOT COVERED (filed upstream, do not duplicate): #5735-(``fix_corrupted_settings`` writes while locked), #5737+DELIBERATELY NOT COVERED (filed upstream, do not duplicate): #5737(``import_settings``' lock refusal is a silent no-op at the manager),#5739 (``settings_locked`` fails open / latent recursion), #5740(inconsistent lock-vs-env ordering). ``reset_to_defaults`` preserving@@ -1145,10 +1144,8 @@ def _lock_guard_census(source: str) -> dict:# entries are #5659's guards; the JSON save/favorites/update entries extend# the same explicit-403 contract. Every ``False`` is a route where a locked# instance still runs the handler and only stops at the manager -- safe for-# the data, wrong in the answer unless the route carries an explicit guard, except-# ``fix_corrupted_settings``, which writes ``setting.value`` straight-# through the ORM session and so is not stopped at the manager either-# (filed upstream as #5735 -- not retested here).+# the data, wrong in the answer unless the route carries an explicit guard.+# The former manual corruption-repair endpoint is replaced by migration 0031.## This mapping is a tripwire, not an endorsement: adding a settings-writing# route, or adding/removing a guard, fails this test until the inventory is@@ -1160,7 +1157,6 @@ EXPECTED_LOCK_GUARD_CENSUS = {("POST", "/api/import"): True,("PUT", "/api/search-favorites"): True,("POST", "/api/search-favorites/toggle"): True,- ("POST", "/fix_corrupted_settings"): False,("PUT", "/api/{key}"): True,("DELETE", "/api/{key}"): True,}diff --git a/tests/web/routers/test_settings_routes_corrupted_coverage_port.py b/tests/web/routers/test_settings_routes_corrupted_coverage_port.pyindex 680cbce105..88ddf0af4d 100644--- a/tests/web/routers/test_settings_routes_corrupted_coverage_port.py+++ b/tests/web/routers/test_settings_routes_corrupted_coverage_port.py@@ -1,47 +1,8 @@-"""Port of ``tests/web/routes/test_settings_routes_corrupted_coverage.py``.--The original drove main's Flask ``settings_bp`` through a test client. On-this branch the same handlers live in-``src/local_deep_research/web/routers/settings.py`` and the write paths were-split into plain synchronous helpers-(``_save_all_settings_sync`` / ``_save_settings_sync`` /-``_api_update_setting_sync``) that take ``username`` explicitly, so the ports-below drive those directly — the pattern already established by-``tests/web/routers/test_settings_cache_invalidation.py``.--Covered areas (unchanged from the original):-- ``_save_all_settings_sync``: corrupted-value detection (``[``, ``]``, ``{}``,- ``[object Object]``), ``report.*`` -> ``{}``, ``search.tool`` / ``app.theme``- defaults, new-setting creation with automatic UI-element detection- (checkbox / number / textarea) and the creation-failure path.-- ``fix_corrupted_settings``: duplicate-key detection/removal, per-key default- assignment, ``report.*`` unknown-key fallback to ``{}``, empty-dict- corruption detection, and the 500 error path with rollback.-- ``_save_settings_sync``: per-setting exception handling with ``failed_count``.-- ``_api_update_setting_sync``: new-setting creation (201) and failure (500).-- ``api_get_data_location``: platform detection (Windows / macOS / Linux).--Two deliberate divergences from the original assertions, both verified to be-intentional branch improvements rather than losses:--1. ``app.theme``'s corrupted-value repair default is ``"system"`` here, not- main's ``"dark"``. Branch-only commit 741193b30 ("fix(settings): the- shipped default theme named a theme that no longer exists") changed it in- both ``_save_all_settings_sync`` and ``fix_corrupted_settings`` because the- theme registry no longer serves ``dark``. The shipped default moved with- it: ``defaults/default_settings.json``'s ``app.theme.value`` is ``"system"``- on this branch and ``"dark"`` on main, so the two sides are internally- consistent. Asserting ``"dark"`` would pin a bug main still has.--2. The 500 path of ``fix_corrupted_settings`` no longer calls- ``db_session.rollback()`` in its own ``except`` block (main did, at- ``web/routes/settings_routes.py:2733``). The branch delegates that to the- ``get_user_db_session`` context manager, which calls- ``safe_rollback(session, "get_user_db_session")`` when the ``with`` body- raises (``database/session_context.py:191-201``). To pin the *behaviour*- rather than a fake, ``test_fix_corrupted_settings_exception_rolls_back``- runs the REAL context manager with only ``get_metrics_session`` stubbed,- so the rollback it asserts is the production one.+"""Settings save, normalization, creation and error-path regression coverage.++Legacy corruption repair now runs once in migration 0031; the manual repair+endpoint and its endpoint-only cases have been removed. Bulk and per-setting+save validation, raw JSON handling and creation failure cases remain covered."""import json@@ -347,166 +308,6 @@ class TestSaveAllSettingsNewSettingCreationFailure:assert mock_create.call_args[0][0]["ui_element"] == expected_ui_element-class TestFixCorruptedSettingsDuplicatesAndDefaults:- """fix_corrupted_settings: duplicate removal and per-key default values."""-- def _call(self, mock_session):- from local_deep_research.web.routers.settings import (- fix_corrupted_settings,- )-- # ``fix_corrupted_settings`` is wrapped by the ``settings_limit``- # slowapi decorator, which rejects a call whose first argument is not- # a real starlette Request. Unwrap to the route body — same technique- # as tests/web/routers/test_settings_cache_invalidation.py.- handler = fix_corrupted_settings.__wrapped__-- @contextmanager- def fake_db_session(*a, **kw):- yield mock_session-- with (- patch(f"{S}.get_user_db_session", side_effect=fake_db_session),- patch(f"{S}.invalidate_settings_caches"),- ):- return handler(Mock(), username="testuser")-- def test_duplicates_removed_and_corrupted_values_fixed(self):- """Duplicate keys are removed; corrupted values get per-key defaults."""- from datetime import UTC, datetime-- now = datetime.now(UTC)-- dupe1 = _make_setting(- key="search.max_results", value=10, updated_at=now- )- dupe2 = _make_setting(key="search.max_results", value=5, updated_at=now)-- corrupted_search_region = _make_setting(- key="search.region", value="null"- )- corrupted_search_tool = _make_setting(- key="search.tool", value="[object Object]"- )- corrupted_app_theme = _make_setting(key="app.theme", value="{}")- corrupted_app_port = _make_setting(key="app.port", value=None)- corrupted_report_unknown = _make_setting(- key="report.custom_layout", value="undefined"- )- corrupted_empty_dict = _make_setting(- key="search.questions_per_iteration", value={}- )- clean_setting = _make_setting(key="llm.model", value="gpt-4")-- all_settings = [- corrupted_search_region,- corrupted_search_tool,- corrupted_app_theme,- corrupted_app_port,- corrupted_report_unknown,- corrupted_empty_dict,- clean_setting,- ]-- mock_dupe_key = MagicMock()- mock_dupe_key.__getitem__ = Mock(return_value="search.max_results")-- mock_session = MagicMock()-- mock_group_query = MagicMock()- mock_group_query.group_by.return_value.having.return_value.all.return_value = [- mock_dupe_key- ]-- mock_filter_query = MagicMock()- mock_filter_query.filter.return_value.order_by.return_value.all.return_value = [- dupe1,- dupe2,- ]-- mock_all_query = MagicMock()- mock_all_query.all.return_value = all_settings-- mock_session.query.side_effect = [- mock_group_query, # duplicate key detection- mock_filter_query, # fetch duplicates for removal- mock_all_query, # all settings for corruption check- ]-- result = self._call(mock_session)-- assert result["status"] == "success"- # Duplicate should have been deleted (the most recent row is kept)- mock_session.delete.assert_called_once_with(dupe2)- assert result["removed_duplicates"] == ["search.max_results"]- # Corrupted values should be fixed with defaults- assert corrupted_search_region.value == "us"- assert corrupted_search_tool.value == DEFAULT_SEARCH_TOOL- # main repaired app.theme to "dark"; the branch repairs to "system"- # (741193b30) — see this module's docstring.- assert corrupted_app_theme.value == "system"- assert corrupted_app_port.value == 5000- # search.questions_per_iteration (empty dict -> corrupted)- assert corrupted_empty_dict.value == 3- # report.custom_layout has no known default -> fallback to empty dict- assert corrupted_report_unknown.value == {}- # A clean value is left alone- assert clean_setting.value == "gpt-4"- assert set(result["fixed_settings"]) == {- "search.region",- "search.tool",- "app.theme",- "app.port",- "report.custom_layout",- "search.questions_per_iteration",- }- mock_session.commit.assert_called_once()-- def test_fix_corrupted_settings_exception_returns_500(self):- """When an exception occurs, return 500 with status 'error'."""- mock_session = MagicMock()- mock_session.query.side_effect = RuntimeError("db failure")-- resp = self._call(mock_session)-- assert resp.status_code == 500- assert _body(resp)["status"] == "error"-- def test_fix_corrupted_settings_exception_rolls_back(self):- """The failed transaction is rolled back, not left dirty.-- Main rolled back inside the route's own ``except``- (``web/routes/settings_routes.py:2733``). The branch delegates it to- ``get_user_db_session`` (``database/session_context.py:191-201``), so- this test runs the REAL context manager with only- ``get_metrics_session`` stubbed — asserting production rollback on- both exception handling and scope exit.- """- from local_deep_research.web.routers.settings import (- fix_corrupted_settings,- )-- handler = fix_corrupted_settings.__wrapped__-- mock_session = MagicMock()- mock_session.query.side_effect = RuntimeError("db failure")-- with (- patch(- "local_deep_research.database.thread_local_session"- ".get_metrics_session",- return_value=mock_session,- ),- patch(f"{SC}.db_manager") as mock_db_manager,- patch(f"{S}.invalidate_settings_caches"),- ):- mock_db_manager.has_encryption = False- resp = handler(Mock(), username="testuser")-- assert resp.status_code == 500- assert mock_session.rollback.call_count == 2--class TestSaveSettingsExceptionInLoop:"""_save_settings_sync (POST fallback): exception inside the loop."""@@ -690,3 +491,95 @@ class TestApiGetDataLocationPlatform:def test_windows_platform(self):data = self._call_data_location("Windows")assert data["platform"] == "Windows"+++class TestSaveAllSettingsAtomicPersistence:+ """False writes must roll back; notifications follow the single commit."""++ @pytest.mark.parametrize("outcomes", ((False,), (True, False)))+ def test_false_write_rolls_back_without_post_commit_effects(self, outcomes):+ from local_deep_research.web.routers.settings import (+ _save_all_settings_sync,+ )++ settings = [+ _make_setting(key="app.alpha", value="old-alpha"),+ _make_setting(key="app.beta", value="old-beta"),+ ]+ db_session, db_patch = _patched_db(all_settings=settings)+ manager = MagicMock(settings_locked=False)+ with (+ db_patch,+ patch(f"{S}.get_settings_manager", return_value=manager),+ patch(f"{S}.set_setting", side_effect=outcomes) as persist,+ patch(f"{S}.validate_setting", return_value=(True, None)),+ patch(+ f"{S}.coerce_setting_for_write",+ side_effect=lambda key, value, ui_element: value,+ ),+ patch(f"{S}.invalidate_settings_caches") as invalidate,+ patch(f"{S}.reschedule_document_jobs_if_needed") as documents,+ patch(f"{S}.reschedule_zotero_jobs_if_needed") as zotero,+ ):+ response = _save_all_settings_sync(+ {"app.alpha": "new-alpha", "app.beta": "new-beta"}, "testuser"+ )++ assert response.status_code == 500+ assert _body(response) == {+ "status": "error",+ "message": "Failed to save setting.",+ }+ assert persist.call_count == len(outcomes)+ assert all(+ call.kwargs["commit"] is False for call in persist.call_args_list+ )+ db_session.rollback.assert_called_once_with()+ db_session.commit.assert_not_called()+ manager.emit_settings_changed_after_commit.assert_not_called()+ invalidate.assert_not_called()+ documents.assert_not_called()+ zotero.assert_not_called()++ def test_success_commits_before_one_notification(self):+ from local_deep_research.web.routers.settings import (+ _save_all_settings_sync,+ )++ settings = [+ _make_setting(key="app.alpha", value="old-alpha"),+ _make_setting(key="app.beta", value="old-beta"),+ ]+ db_session, db_patch = _patched_db(all_settings=settings)+ manager = MagicMock(settings_locked=False)+ events = []+ db_session.commit.side_effect = lambda: events.append("commit")+ manager.emit_settings_changed_after_commit.side_effect = lambda keys: (+ events.append(("notify", keys))+ )+ with (+ db_patch,+ patch(f"{S}.get_settings_manager", return_value=manager),+ patch(f"{S}.set_setting", return_value=True) as persist,+ patch(f"{S}.validate_setting", return_value=(True, None)),+ patch(+ f"{S}.coerce_setting_for_write",+ side_effect=lambda key, value, ui_element: value,+ ),+ _quiet_side_effects(),+ ):+ response = _save_all_settings_sync(+ {"app.alpha": "new-alpha", "app.beta": "new-beta"}, "testuser"+ )++ assert response["status"] == "success"+ assert persist.call_count == 2+ assert all(+ call.kwargs["commit"] is False for call in persist.call_args_list+ )+ assert events == ["commit", ("notify", ["app.alpha", "app.beta"])]+ db_session.commit.assert_called_once_with()+ db_session.rollback.assert_not_called()+ manager.emit_settings_changed_after_commit.assert_called_once_with(+ ["app.alpha", "app.beta"]+ )diff --git a/tests/web/routers/test_settings_routes_coverage_port.py b/tests/web/routers/test_settings_routes_coverage_port.pyindex 6282ca84b0..c369b996f5 100644--- a/tests/web/routers/test_settings_routes_coverage_port.py+++ b/tests/web/routers/test_settings_routes_coverage_port.py@@ -913,110 +913,6 @@ class TestSaveSettings:)-# ===========================================================================-# POST /settings/fix_corrupted_settings-#-# (c) NOT SUPERSEDED — the only branch reference is-# test_router_sibling_consistency.py:518 (a route-shape sweep). Nothing-# pins the repair table, the duplicate removal, or the 500 path.-# ===========================================================================---def _fix(mock_session):- from local_deep_research.web.routers.settings import (- fix_corrupted_settings,- )-- with _patch_session(mock_session):- return fix_corrupted_settings.__wrapped__(_request(), username="u")---def _fix_session(all_settings, duplicate_keys=(), dupe_rows=()):- s = MagicMock()- s.query.return_value.group_by.return_value.having.return_value.all.return_value = list(- duplicate_keys- )- s.query.return_value.all.return_value = list(all_settings)- s.query.return_value.filter.return_value.order_by.return_value.all.return_value = list(- dupe_rows- )- return s---class TestFixCorruptedSettings:- def test_no_corruption(self, no_side_effects):- """No corrupted or duplicate settings."""- setting = _make_setting(key="llm.model", value="gpt-4")- result = _fix(_fix_session([setting]))- assert _status(result) == 200- assert _body(result)["status"] == "success"- assert _body(result)["fixed_settings"] == []-- def test_fixes_corrupted_llm_model(self, no_side_effects):- """Corrupted llm.model gets fixed to default."""- setting = _make_setting(key="llm.model", value="[object Object]")- result = _fix(_fix_session([setting]))- assert _status(result) == 200- assert "llm.model" in _body(result)["fixed_settings"]-- def test_fixes_corrupted_search_settings(self, no_side_effects):- """Corrupted search settings get fixed."""- settings = [- _make_setting(key="search.tool", value="null"),- _make_setting(key="search.max_results", value="undefined"),- _make_setting(key="search.region", value=None),- ]- result = _fix(_fix_session(settings))- assert _status(result) == 200- fixed = _body(result)["fixed_settings"]- assert {"search.tool", "search.max_results", "search.region"} <= set(- fixed- )-- def test_fixes_corrupted_app_settings(self, no_side_effects):- """Corrupted app settings get fixed."""- settings = [- _make_setting(key="app.theme", value="{}"),- _make_setting(key="app.host", value=None),- _make_setting(key="app.port", value="null"),- _make_setting(key="app.debug", value="undefined"),- ]- result = _fix(_fix_session(settings))- assert _status(result) == 200- fixed = _body(result)["fixed_settings"]- assert {"app.theme", "app.host", "app.port", "app.debug"} <= set(fixed)-- def test_removes_duplicates(self, no_side_effects):- """Duplicate settings get removed."""- dup1 = _make_setting(key="llm.model", value="gpt-4")- dup2 = _make_setting(key="llm.model", value="gpt-3.5")- session = _fix_session(- [dup1], duplicate_keys=[("llm.model",)], dupe_rows=[dup1, dup2]- )- result = _fix(session)- assert _status(result) == 200- # Structural: the newest row is kept, every older one deleted.- session.delete.assert_called_once_with(dup2)- assert _body(result)["removed_duplicates"] == ["llm.model"]-- def test_exception_returns_500(self, no_side_effects):- session = MagicMock()- session.query.side_effect = RuntimeError("db fail")- result = _fix(session)- assert _status(result) == 500---class TestFixCorruptedSettingsReportFallback:- """Test report. key corruption fallback to empty dict."""-- def test_report_key_no_default_gets_empty_dict(self, no_side_effects):- setting = _make_setting(key="report.unknown_key", value=None)- result = _fix(_fix_session([setting]))- assert _status(result) == 200- assert "report.unknown_key" in _body(result)["fixed_settings"]- assert setting.value == {}--# ===========================================================================# GET /settings/api/warnings#diff --git a/tests/web/routers/test_settings_routes_deep_coverage2_port.py b/tests/web/routers/test_settings_routes_deep_coverage2_port.pyindex 7f4548a95c..edc589b780 100644--- a/tests/web/routers/test_settings_routes_deep_coverage2_port.py+++ b/tests/web/routers/test_settings_routes_deep_coverage2_port.py@@ -736,134 +736,9 @@ class TestSaveAllSettingsWarningKey:# ----------------------------------------------------------------------------# fix_corrupted_settings# ----------------------------------------------------------------------------class TestFixCorruptedSettingsDuplicates:- """fix_corrupted_settings removes duplicate settings."""-- def test_duplicate_settings_are_removed(self):- from local_deep_research.web.routers.settings import (- fix_corrupted_settings,- )-- dupe1 = _make_setting(key="llm.model", value="gpt-4")- dupe2 = _make_setting(key="llm.model", value="gpt-3.5")-- session = MagicMock()- dup_query = MagicMock()- dup_query.group_by.return_value.having.return_value.all.return_value = [- ("llm.model",)- ]- dupe_query = MagicMock()- dupe_query.filter.return_value.order_by.return_value.all.return_value = [- dupe1,- dupe2,- ]- all_query = MagicMock()- all_query.all.return_value = []-- calls = [0]-- def _query_side_effect(_model, *a, **kw):- calls[0] += 1- if calls[0] == 1:- return dup_query- if calls[0] == 2:- return dupe_query- return all_query-- session.query.side_effect = _query_side_effect-- @contextmanager- def fake_db_session(*a, **kw):- yield session-- with (- patch(f"{S}.get_user_db_session", side_effect=fake_db_session),- _quiet_side_effects(),- ):- resp = fix_corrupted_settings.__wrapped__(- _fake_request(), username="testuser"- )-- data = _body(resp)- assert data["status"] == "success"- # The most recently updated row is kept; every other one is deleted.- session.delete.assert_called_once_with(dupe2)- assert data["removed_duplicates"] == ["llm.model"]---class TestFixCorruptedSettingsReportNoDefault:- """fix_corrupted_settings sets unknown report.* to empty dict."""-- def test_corrupted_unknown_report_key_set_to_empty_dict(self):- from local_deep_research.web.routers.settings import (- fix_corrupted_settings,- )-- setting = _make_setting(key="report.unknown_format", value=None)-- session = MagicMock()- dup_query = MagicMock()- dup_query.group_by.return_value.having.return_value.all.return_value = []- all_query = MagicMock()- all_query.all.return_value = [setting]- calls = [0]-- def _query_side_effect(_model, *a, **kw):- calls[0] += 1- return dup_query if calls[0] == 1 else all_query-- session.query.side_effect = _query_side_effect-- @contextmanager- def fake_db_session(*a, **kw):- yield session-- with (- patch(f"{S}.get_user_db_session", side_effect=fake_db_session),- _quiet_side_effects(),- ):- resp = fix_corrupted_settings.__wrapped__(- _fake_request(), username="testuser"- )-- data = _body(resp)- assert "report.unknown_format" in data["fixed_settings"]- assert setting.value == {}---class TestFixCorruptedSettingsException:- """fix_corrupted_settings returns 500 on unexpected exception."""-- def test_exception_returns_500(self):- from local_deep_research.web.routers.settings import (- fix_corrupted_settings,- )-- session = MagicMock()- session.query.return_value.group_by.side_effect = RuntimeError(- "db error"- )-- @contextmanager- def fake_db_session(*a, **kw):- yield session-- with (- patch(f"{S}.get_user_db_session", side_effect=fake_db_session),- _quiet_side_effects(),- ):- resp = fix_corrupted_settings.__wrapped__(- _fake_request(), username="testuser"- )-- assert resp.status_code == 500- assert _body(resp)["status"] == "error"--# ---------------------------------------------------------------------------# api_get_available_models# ---------------------------------------------------------------------------diff --git a/tests/web/routers/test_settings_routes_deep_coverage_port.py b/tests/web/routers/test_settings_routes_deep_coverage_port.pyindex d7c57e0555..249414d77f 100644--- a/tests/web/routers/test_settings_routes_deep_coverage_port.py+++ b/tests/web/routers/test_settings_routes_deep_coverage_port.py@@ -786,108 +786,9 @@ def _run_favorites_impl(# ----------------------------------------------------------------------------# fix_corrupted_settings: default-value repair table# ----------------------------------------------------------------------------class TestFixCorruptedSettingsSubKeys:- """fix_corrupted_settings: additional corrupted key defaults."""-- def _post_fix(self, settings_list):- from local_deep_research.web.routers.settings import (- fix_corrupted_settings,- )-- session = MagicMock()- dup_query = MagicMock()- dup_query.group_by.return_value.having.return_value.all.return_value = []- all_query = MagicMock()- all_query.all.return_value = settings_list-- calls = {"n": 0}-- def _query(_model, *a, **kw):- calls["n"] += 1- return dup_query if calls["n"] == 1 else all_query-- session.query.side_effect = _query-- @contextmanager- def fake_db_session(*a, **kw):- yield session-- with (- patch(f"{S}.get_user_db_session", side_effect=fake_db_session),- _quiet_side_effects(),- ):- return fix_corrupted_settings.__wrapped__(- _fake_request(), username="testuser"- )-- def test_fixes_search_sub_keys(self):- settings = [- _make_setting(key="search.questions_per_iteration", value=None),- _make_setting(key="search.searches_per_section", value="null"),- _make_setting(- key="search.skip_relevance_filter", value="undefined"- ),- _make_setting(key="search.safe_search", value="{}"),- _make_setting(key="search.search_language", value=None),- ]-- data = _body(self._post_fix(settings))-- assert "search.questions_per_iteration" in data["fixed_settings"]- assert "search.safe_search" in data["fixed_settings"]-- def test_fixes_app_enable_notifications(self):- data = _body(- self._post_fix(- [_make_setting(key="app.enable_notifications", value="null")]- )- )-- assert "app.enable_notifications" in data["fixed_settings"]-- def test_fixes_llm_temperature_and_max_tokens(self):- settings = [- _make_setting(key="llm.temperature", value=None),- _make_setting(key="llm.max_tokens", value="undefined"),- ]-- data = _body(self._post_fix(settings))-- assert "llm.temperature" in data["fixed_settings"]- assert "llm.max_tokens" in data["fixed_settings"]-- def test_report_unknown_key_fallback(self):- setting = _make_setting(- key="report.unknown_key", value="[object Object]"- )-- data = _body(self._post_fix([setting]))-- assert "report.unknown_key" in data["fixed_settings"]- # The fallback for an unknown report.* key is {}, not the corruption.- assert setting.value == {}-- def test_empty_dict_corruption(self):- setting = _make_setting(key="llm.provider", value={})-- data = _body(self._post_fix([setting]))-- assert "llm.provider" in data["fixed_settings"]- assert setting.value == "ollama"-- def test_report_searches_per_section(self):- setting = _make_setting(key="report.searches_per_section", value="null")-- data = _body(self._post_fix([setting]))-- assert "report.searches_per_section" in data["fixed_settings"]- assert setting.value == 2--# ---------------------------------------------------------------------------# save_all_settings: setting type/category derivation# ---------------------------------------------------------------------------diff --git a/tests/web/routers/test_settings_scheduler_route_integration.py b/tests/web/routers/test_settings_scheduler_route_integration.pyindex 0b1628b5b0..913459a105 100644--- a/tests/web/routers/test_settings_scheduler_route_integration.py+++ b/tests/web/routers/test_settings_scheduler_route_integration.py@@ -224,71 +224,3 @@ def test_delete_does_not_reschedule_when_delete_rolls_back():assert response.status_code == 500assert events == []---def _corrupted_settings_session(commit_failure=False):- duplicate_keys_query = MagicMock()- duplicate_keys_query.group_by.return_value.having.return_value.all.return_value = [- ("document_scheduler.enabled",)- ]-- duplicate_rows_query = MagicMock()- duplicate_rows_query.filter.return_value.order_by.return_value.all.return_value = [- Mock(),- Mock(),- Mock(),- ]-- all_settings_query = MagicMock()- all_settings_query.all.return_value = []-- db_session = MagicMock()- db_session.query.side_effect = [- duplicate_keys_query,- duplicate_rows_query,- all_settings_query,- ]- if commit_failure:- db_session.commit.side_effect = RuntimeError("commit failed")- return db_session---def test_corruption_repair_deduplicates_changed_keys_before_rescheduling():- db_session = _corrupted_settings_session()-- with (- _runtime_spies() as (events, *_spies),- _session_patch(db_session),- ):- result = settings_router.fix_corrupted_settings.__wrapped__(- Mock(), username="alice"- )-- assert result["removed_duplicates"] == [- "document_scheduler.enabled",- "document_scheduler.enabled",- ]- db_session.commit.assert_called_once_with()- assert db_session.delete.call_count == 2- changed_keys = ("document_scheduler.enabled",)- assert events == [- ("invalidate", "alice"),- ("documents", "alice", changed_keys),- ("zotero", "alice", changed_keys),- ]---def test_corruption_repair_does_not_reschedule_after_commit_rollback():- db_session = _corrupted_settings_session(commit_failure=True)-- with (- _runtime_spies() as (events, *_spies),- _session_patch(db_session),- ):- response = settings_router.fix_corrupted_settings.__wrapped__(- Mock(), username="alice"- )-- assert response.status_code == 500- db_session.rollback.assert_called_once_with()- assert events == []diff --git a/tests/web/test_rate_limit_census.py b/tests/web/test_rate_limit_census.pyindex ec82f4fcd0..801388a808 100644--- a/tests/web/test_rate_limit_census.py+++ b/tests/web/test_rate_limit_census.py@@ -246,7 +246,6 @@ CENSUS = {"settings.api_import_settings": (SETTINGS,),"settings.api_update_setting": (SETTINGS,),"settings.api_delete_setting": (SETTINGS,),- "settings.fix_corrupted_settings": (SETTINGS,),"settings.api_toggle_search_favorite": (SETTINGS,),"settings.api_update_search_favorites": (SETTINGS,),"settings.api_test_notification_url": (NOTIFICATION_TEST,),diff --git a/tests/web/test_rate_limit_coverage.py b/tests/web/test_rate_limit_coverage.pyindex f0a994a1cc..565d19b824 100644--- a/tests/web/test_rate_limit_coverage.py+++ b/tests/web/test_rate_limit_coverage.py@@ -47,7 +47,6 @@ class TestLimitRegistry:"local_deep_research.web.routers.settings.api_import_settings","local_deep_research.web.routers.settings.api_update_setting","local_deep_research.web.routers.settings.api_delete_setting",- "local_deep_research.web.routers.settings.fix_corrupted_settings",# uploads (per-user AND per-IP buckets)"local_deep_research.web.routers.research.upload_pdf","local_deep_research.web.routers.rag.upload_to_collection",diff --git a/tests/web/test_route_table_parity.py b/tests/web/test_route_table_parity.pyindex 0eae834484..ed03ddb3a1 100644--- a/tests/web/test_route_table_parity.py+++ b/tests/web/test_route_table_parity.py@@ -141,6 +141,8 @@ EXPECTED_REMOVED = [("POST", "/api/news/research"),("POST", "/api/news/subscriptions"),("PUT", "/api/news/subscriptions/{}"),+ # Legacy corruption repair is now the one-time migration 0031.+ ("POST", "/settings/fix_corrupted_settings"),# Context-overflow analytics moved out from under the /metrics blueprint# prefix to top-level /api paths (routes/context_overflow_api.py's own# decorators were always "/api/context-overflow" etc; Flask prepended