~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
fix: stop safe_rollback from masking provisioning races; surface exception context in app_logs and metrics tracebacks (#5261)
S45abe7099e83
diff --git a/changelog.d/+safe-rollback-provisioning-masking.bugfix.md b/changelog.d/+safe-rollback-provisioning-masking.bugfix.mdnew file mode 100644index 0000000000..dd9bf34629--- /dev/null+++ b/changelog.d/+safe-rollback-provisioning-masking.bugfix.md@@ -0,0 +1,3 @@+- Stop `safe_rollback` from masking the original failure with a secondary `InvalidRequestError` or `InterfaceError` when the thread-local SQLAlchemy session is in a broken state — either mid-provisioning on the per-user `QueuePool` (concurrent-operation race) or holding a cursor invalidated by a `commit/rollback` that fired between `execute()` and the lazy-attribute fetch. Both states now reset the thread-local cache (so the next caller on the same thread gets a fresh session from the `QueuePool`) and log at DEBUG; other `SQLAlchemyError` failures still hit the loud `logger.exception` path (unless their message matches a known broken-session signature).+- Persist a short `[Type: value]` exception prefix to `app_logs` rows from `database_sink` when the loguru record carries an active exception, so an investigator querying `ResearchLog` can distinguish ERROR lines that share a bare message. The full traceback remains off the encrypted-DB sink per the #4182 password-redaction policy.+- Standardize fallback and exception handlers in `TokenCountingCallback._save_to_db` and `SearchTracker.record_search` to use `logger.warning` with `scrub_error` sanitization, ensuring DB/metrics failure logs are captured safely without exposing tracebacks, credentials, or sensitive encryption passwords on stderr.diff --git a/src/local_deep_research/database/session_context.py b/src/local_deep_research/database/session_context.pyindex 2f1284ce8e..a72a64f811 100644--- a/src/local_deep_research/database/session_context.py+++ b/src/local_deep_research/database/session_context.py@@ -15,10 +15,12 @@ from flask import (session as flask_session,)from loguru import logger+from sqlalchemy.exc import SQLAlchemyErrorfrom sqlalchemy.orm import Sessionfrom ..utilities.thread_context import get_search_contextfrom .encrypted_db import db_manager+from .thread_local_session import thread_session_manager# Placeholder password used when accessing unencrypted databases.# This should only be used when LDR_ALLOW_UNENCRYPTED=true is set.@@ -42,14 +44,68 @@ def safe_rollback(session: Session, context: str = "") -> None:without repeating the try/except/log boilerplate at every except handler.``context`` is included in the error log so failed rollbacks can betraced back to the call site.++ Two SQLAlchemy error shapes are treated as "the session is structurally+ unusable — give up on it, drop the thread-local cache, and let the next+ caller get a fresh one" rather than as loud failures:++ * ``InvalidRequestError("...provisioning a new connection; concurrent+ operations are not permitted...")`` — the second thread racing on the+ per-user QueuePool.+ * ``InterfaceError("Cursor needed to be reset because of commit/rollback+ and can no longer be fetched from")`` — a cursor was invalidated by a+ commit/rollback that fired between the original ``execute()`` and the+ lazy-attribute fetch that followed.++ In both cases SQLAlchemy has already marked the session unrecoverable, so+ a no-op rollback is correct, the thread-local cache is cleared, and the+ failure is logged at DEBUG so the production stderr stream stays clean.+ Other ``SQLAlchemyError`` failures still hit the loud ``logger.exception``+ path (unless their message matches a known broken-session signature) —+ the session is normally recoverable via rollback and the operator needs+ to see them."""+ if session is None:+ return+ log_msg = (+ f"Failed to rollback session: {context}"+ if context+ else "Failed to rollback session"+ )try:session.rollback()+ except SQLAlchemyError as exc:+ msg = str(exc)+ # Message-substring matching pinned against SQLAlchemy 2.0+ QueuePool error messages+ # ('provisioning a new connection', 'concurrent operations are not permitted').+ is_provisioning_race = (+ "provisioning a new connection" in msg+ or "concurrent operations are not permitted" in msg+ )+ # Requires 'Cursor needed to be reset' message match so other InterfaceErrors+ # (e.g., driver/connectivity failures) are not quietly swallowed into the DEBUG path.+ is_cursor_invalidated = "Cursor needed to be reset" in msg+ if is_provisioning_race or is_cursor_invalidated:+ label = f": {context}" if context else ""+ logger.debug(f"safe_rollback — resetting broken session{label}")+ # Drop the thread-local cache so the next caller on this+ # thread gets a fresh session. Identity-checked inside the+ # helper, so a caller that hands in a session that ISN'T+ # the cached one (e.g. borrowed from ``g.db_session`` or+ # owned by a different thread) won't accidentally clear+ # someone else's cache. The reset itself is best-effort —+ # never let it raise past ``safe_rollback`` (call sites are+ # themselves in except handlers).+ try:+ thread_session_manager.reset_session_if_matches(session)+ except Exception:+ logger.debug(+ f"safe_rollback: reset_session_if_matches raised for{label}"+ )+ return+ logger.exception(log_msg)except Exception:- if context:- logger.exception(f"Failed to rollback session: {context}")- else:- logger.exception("Failed to rollback session")+ logger.exception(log_msg)def get_g_db_session() -> Optional[Session]:diff --git a/src/local_deep_research/database/thread_local_session.py b/src/local_deep_research/database/thread_local_session.pyindex 554d39a5f3..95f29e690f 100644--- a/src/local_deep_research/database/thread_local_session.py+++ b/src/local_deep_research/database/thread_local_session.py@@ -170,6 +170,31 @@ class ThreadLocalSessionManager:with self._lock:self._thread_credentials.pop(thread_id, None)+ def reset_session_if_matches(self, session: "Session | None") -> bool:+ """If ``session`` is the current thread's cached session, clear it.++ Used by ``safe_rollback`` in ``database/session_context.py`` to heal+ the thread-local session cache when an error tells us the session+ is structurally unusable (a provisioning race or an invalidated+ cursor). The next caller on this thread then gets a fresh session+ from the shared ``QueuePool`` instead of inheriting the broken+ one.++ Identity-checked: a caller that hands in a session from a+ different thread (or a session that isn't the cached one at all+ — e.g. one borrowed from ``g.db_session``) won't accidentally+ clear someone else's cache. Returns ``True`` if a reset+ actually happened, ``False`` otherwise.+ """+ if session is None:+ return False+ if not hasattr(self._local, "session") or self._local.session is None:+ return False+ if self._local.session is not session:+ return False+ self._cleanup_thread_session()+ return True+def cleanup_thread(self, thread_id: Optional[int] = None):"""Clean up session for a specific thread or current thread.diff --git a/src/local_deep_research/metrics/search_tracker.py b/src/local_deep_research/metrics/search_tracker.pyindex b0d98aa449..d5a3ad1451 100644--- a/src/local_deep_research/metrics/search_tracker.py+++ b/src/local_deep_research/metrics/search_tracker.py@@ -31,6 +31,7 @@ class SearchTracker:error_message: Optional[str] = None,) -> None:"""Record a completed search operation directly to database."""+ password = None# Extract research context (thread-safe)context = get_search_context()@@ -113,11 +114,19 @@ class SearchTracker:f"Search call recorded to encrypted DB: {engine_name} - "f"{results_count} results in {response_time_ms}ms")- except Exception:- logger.warning("Failed to write search metrics")+ except Exception as e:+ # Deferred import to avoid potential circular imports during module initialization+ from ..security.log_sanitizer import scrub_error++ safe_msg = scrub_error(e, password)+ logger.warning(f"Failed to write search metrics: {safe_msg}")++ except Exception as e:+ # Deferred import to avoid potential circular imports during module initialization+ from ..security.log_sanitizer import scrub_error- except Exception:- logger.warning("Failed to record search call")+ safe_msg = scrub_error(e, password)+ logger.warning(f"Failed to record search call: {safe_msg}")def get_search_metrics(self,diff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.pyindex 1fa03c9509..d6f61fd684 100644--- a/src/local_deep_research/metrics/token_counter.py+++ b/src/local_deep_research/metrics/token_counter.py@@ -797,8 +797,14 @@ class TokenCountingCallback(BaseCallbackHandler):metrics_writer.write_token_metrics(username, self.research_id, token_data)- except Exception:- logger.warning("Failed to write metrics from thread")+ except Exception as e:+ # Deferred import to avoid potential circular imports during module initialization+ from ..security.log_sanitizer import scrub_error++ safe_msg = scrub_error(e, password)+ logger.warning(+ f"Failed to write metrics from thread: {safe_msg}"+ )return# In MainThread, save directly@@ -904,8 +910,12 @@ class TokenCountingCallback(BaseCallbackHandler):# Commit the transactionsession.commit()- except Exception:- logger.warning("Error saving token usage to database")+ except Exception as e:+ # Deferred import to avoid potential circular imports during module initialization+ from ..security.log_sanitizer import scrub_error++ safe_msg = scrub_error(e)+ logger.warning(f"Error saving token usage to database: {safe_msg}")def get_counts(self) -> Dict[str, Any]:"""Get the current token counts."""diff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.pyindex 60178f7833..802fc591a3 100644--- a/src/local_deep_research/utilities/log_utils.py+++ b/src/local_deep_research/utilities/log_utils.py@@ -361,7 +361,14 @@ def database_sink(message: loguru.Message) -> None:# Create log entry dictlog_entry = {"timestamp": record["time"],- "message": _truncate_for_database(record["message"]),+ # Prefix the message with exception type/value when the record+ # carries one (logger.exception / logger.opt(exception=...)).+ # Keeps the full traceback off the encrypted-DB row (diagnose=False+ # on this sink; password-redaction policy #4182) while still+ # leaving the database log useful for triage.+ "message": _truncate_for_database(+ _exception_context(record) + record["message"]+ ),"module": record["name"],"function": record["function"],"line_no": int(record["line"]),@@ -402,6 +409,54 @@ def _truncate_for_database(message: str) -> str:return message[:DATABASE_MESSAGE_MAX_LENGTH] + suffix+def _exception_context(record) -> str:+ """Render a short exception prefix from the log record, if any.++ Loguru stores the active exception in ``record["exception"]`` as a+ ``RecordException`` namedtuple (or None) populated by ``.exception()``+ or by ``logger.opt(exception=...)``. Without this, the database sink+ persists messages like ``"LangGraph agent error"`` with the actual+ exception type and message only on stderr — investigators querying+ ``app_logs`` see an empty ERROR row. The exception is always+ separately available in container-log/stderr/file sinks; this just+ gives the DB row enough context to triage. The full traceback is+ deliberately NOT included because ``diagnose=False`` on the database+ sink (see ``config_logger``) and the password-redaction policy+ (#4182) forbid it for encrypted-DB persistence.+ """+ exc = record.get("exception") if record else None+ if not exc:+ return ""+ # RecordException is a namedtuple of (type, value, traceback).+ # ``value`` is the exception instance (or None if un-picklable).+ exc_type = getattr(exc, "type", None)+ exc_value = getattr(exc, "value", None)+ if exc_type is None and isinstance(exc, tuple) and len(exc) >= 1:+ exc_type = exc[0]+ if exc_value is None and len(exc) >= 2:+ exc_value = exc[1]+ if exc_type is None:+ return ""+ type_name = getattr(exc_type, "__name__", str(exc_type))+ if exc_value is None:+ return f"[{type_name}] "+ try:+ value_text = str(exc_value)+ if len(value_text) > 4096:+ value_text = value_text[:4096]+ # Deferred import to avoid potential circular imports during module initialization+ from ..security.log_sanitizer import sanitize_error_message++ value_text = sanitize_error_message(value_text)+ except Exception:+ value_text = "<unprintable exception>"+ if not value_text:+ return f"[{type_name}] "+ if len(value_text) > 240:+ value_text = value_text[:237] + "…"+ return f"[{type_name}: {value_text}] "++def _truncate_for_frontend(message: str) -> str:"""Bound the wire size of an outbound log message.diff --git a/tests/database/test_session_context.py b/tests/database/test_session_context.pyindex f3a70604d8..303d8c86d5 100644--- a/tests/database/test_session_context.py+++ b/tests/database/test_session_context.py@@ -299,3 +299,293 @@ class TestSafeRollback:session = Mock()safe_rollback(session)session.rollback.assert_called_once()++ def test_provisioning_state_invalid_request_is_treated_as_noop(self):+ """When the per-user QueuePool is mid-acquire on another thread,+ ``session.rollback()`` raises+ ``InvalidRequestError("This session is provisioning a new connection;+ concurrent operations are not permitted")``. That secondary error+ used to cascade back into the original caller and pollute the logs+ with a misleading "Failed to rollback session" line. ``safe_rollback``+ now treats that exact subclass of failure as a benign no-op (logged+ at DEBUG so the production stderr stream stays clean) and the call+ must NOT raise.+ """+ from sqlalchemy.exc import InvalidRequestError++ from local_deep_research.database.session_context import (+ safe_rollback,+ )++ session = Mock()+ session.rollback.side_effect = InvalidRequestError(+ "This session is provisioning a new connection; concurrent "+ "operations are not permitted"+ )++ # Must NOT raise — original caller is itself in an except handler.+ safe_rollback(session, "context_manager")++ session.rollback.assert_called_once()++ def test_provisioning_state_debug_logged(self):+ """The provisioning no-op emits a DEBUG line so a forensic analyst+ with ``LDR_APP_DEBUG=true`` can see *why* a recovery rollback was+ skipped, but the production stderr stream stays at WARNING+.+ """+ from sqlalchemy.exc import InvalidRequestError++ from local_deep_research.database.session_context import (+ safe_rollback,+ )+ import local_deep_research.database.session_context as sc_mod++ session = Mock()+ session.rollback.side_effect = InvalidRequestError(+ "This session is provisioning a new connection"+ )++ with patch.object(sc_mod.logger, "debug") as mock_debug:+ with patch.object(sc_mod.logger, "exception") as mock_exception:+ with patch.object(sc_mod.logger, "warning") as mock_warning:+ safe_rollback(session, "context_manager")++ # DEBUG line carries the caller-supplied context so a tail of+ # skipped rollbacks can be attributed to the call site.+ debug_msg = mock_debug.call_args[0][0]+ assert "resetting broken session" in debug_msg+ assert "context_manager" in debug_msg++ # And the loud failure paths are NOT used for this benign case.+ mock_exception.assert_not_called()+ mock_warning.assert_not_called()++ def test_unrelated_sqlalchemy_error_still_logs_at_exception(self):+ """Only the provisioning/concurrency state is treated as a no-op.+ Other ``SQLAlchemyError`` subclasses (e.g. ``OperationalError``)+ still hit the loud ``logger.exception`` path so persistent DB+ issues stay visible at ERROR level on stderr."""+ from sqlalchemy.exc import OperationalError++ from local_deep_research.database.session_context import (+ safe_rollback,+ )+ import local_deep_research.database.session_context as sc_mod++ session = Mock()+ session.rollback.side_effect = OperationalError(+ "stmt", {}, Exception("database is locked")+ )++ with patch.object(sc_mod.logger, "exception") as mock_exception:+ safe_rollback(session, "context_manager")++ mock_exception.assert_called_once()+ # The error log line keeps the call-site context for forensics.+ msg = mock_exception.call_args[0][0]+ assert "context_manager" in msg+ assert "Failed to rollback session" in msg++ def test_safe_rollback_handles_none_session(self):+ """Passing None as session should return early without error."""+ from local_deep_research.database.session_context import safe_rollback++ # Must NOT raise AttributeError+ safe_rollback(None, "none_test")++ def test_interface_error_invalidates_session_and_resets_cache(self):+ """When ``session.rollback()`` raises ``InterfaceError`` (the+ ``Cursor needed to be reset because of commit/rollback …`` family),+ the session is structurally unusable — a future query on it would+ just re-raise. ``safe_rollback`` should treat the InterfaceError+ the same as the provisioning race: log at DEBUG and clear the+ thread-local cache so the next caller on this thread gets a+ fresh session from the ``QueuePool``.+ """+ from sqlalchemy.exc import InterfaceError++ from local_deep_research.database.session_context import (+ safe_rollback,+ )+ from local_deep_research.database.thread_local_session import (+ thread_session_manager,+ )++ # Pretend ``session`` IS the current thread's cached session —+ # the realistic case from ``get_user_db_session``.+ session = Mock()+ # ``InterfaceError`` is a ``DBAPIError`` subclass; the+ # (statement, params, orig) signature is the SQLAlchemy 2.x+ # way to construct it without going through a real driver.+ session.rollback.side_effect = InterfaceError(+ "Cursor needed to be reset because of commit/rollback and can "+ "no longer be fetched from",+ None,+ Exception("reset"),+ )+ thread_session_manager._local.session = session+ thread_session_manager._local.username = "testuser"+ try:+ safe_rollback(session, "library_search")+ # Must NOT raise — the caller is in an except handler.+ # And the thread-local cache must be cleared so the next+ # ``get_user_db_session`` on this thread gets a fresh+ # session from the QueuePool.+ assert thread_session_manager._local.session is None+ assert thread_session_manager._local.username is None+ finally:+ # Make sure a failing assertion above doesn't leak the+ # mock into the next test.+ thread_session_manager._local.session = None+ thread_session_manager._local.username = None++ def test_interface_error_reset_failure_does_not_mask_original(self):+ """If the thread-local cache reset itself raises (e.g. the+ session's ``close()`` blows up because the connection is gone),+ ``safe_rollback`` must still return cleanly — call sites are+ themselves in except handlers and a raise here would mask the+ original failure.+ """+ from sqlalchemy.exc import InterfaceError++ from local_deep_research.database.session_context import (+ safe_rollback,+ )+ import local_deep_research.database.session_context as sc_mod++ session = Mock()+ session.rollback.side_effect = InterfaceError(+ "Cursor needed to be reset", None, Exception("reset")+ )+ # Force ``reset_session_if_matches`` to raise — the rollback+ # path must still swallow it.+ with patch.object(+ sc_mod.thread_session_manager,+ "reset_session_if_matches",+ side_effect=RuntimeError("reset boom"),+ ):+ with patch.object(sc_mod.logger, "debug") as mock_debug:+ # Must NOT raise.+ safe_rollback(session, "library_search")++ # A DEBUG line still records the recovery attempt so a forensic+ # analyst with ``LDR_APP_DEBUG=true`` sees it.+ debug_msgs = [c.args[0] for c in mock_debug.call_args_list]+ assert any("reset_session_if_matches raised" in m for m in debug_msgs)++ def test_interface_error_message_only_also_resets(self):+ """Some SQLAlchemy builds wrap ``InterfaceError`` in a parent+ class whose ``str()`` still contains the canonical+ ``Cursor needed to be reset`` substring. The detection must+ match on the message as well as on the type, so an exotic+ subclass doesn't slip through into the loud path.+ """+ from local_deep_research.database.session_context import (+ safe_rollback,+ )+ from local_deep_research.database.thread_local_session import (+ thread_session_manager,+ )+ import local_deep_research.database.session_context as sc_mod++ session = Mock()+ # A bare ``SQLAlchemyError`` (not InterfaceError) but with the+ # canonical message — the message-based check should still fire.+ from sqlalchemy.exc import SQLAlchemyError++ session.rollback.side_effect = SQLAlchemyError(+ "Cursor needed to be reset because of commit/rollback"+ )+ thread_session_manager._local.session = session+ try:+ with patch.object(sc_mod.logger, "exception") as mock_exception:+ safe_rollback(session, "library_search")++ # Loud ``logger.exception`` is NOT used for this benign+ # broken-state case.+ mock_exception.assert_not_called()+ # And the cache was cleared.+ assert thread_session_manager._local.session is None+ finally:+ thread_session_manager._local.session = None++ def test_unrelated_interface_error_still_logs_at_exception(self):+ """InterfaceError without 'Cursor needed to be reset' (e.g. driver-level+ connection failures) should NOT be quietly swallowed into the DEBUG path;+ they must log at ERROR via logger.exception.+ """+ from sqlalchemy.exc import InterfaceError++ from local_deep_research.database.session_context import (+ safe_rollback,+ )+ import local_deep_research.database.session_context as sc_mod++ session = Mock()+ session.rollback.side_effect = InterfaceError(+ "connection already closed", None, Exception("closed")+ )++ with patch.object(sc_mod.logger, "exception") as mock_exception:+ safe_rollback(session, "test_context")++ mock_exception.assert_called_once()+ msg = mock_exception.call_args[0][0]+ assert "test_context" in msg+ assert "Failed to rollback session" in msg++ def test_reset_session_if_matches_only_clears_cached_session(self):+ """The ``reset_session_if_matches`` helper is identity-checked:+ passing a session that is NOT the current thread's cached one+ must not touch the cache. This protects callers that hand+ ``safe_rollback`` a session borrowed from another context+ (e.g. ``g.db_session`` or a worker thread's local) — a wrong+ identity match would silently clear someone else's cache and+ hide the original failure under a different stack trace.+ """+ from local_deep_research.database.thread_local_session import (+ thread_session_manager,+ )++ cached = Mock(name="cached")+ other = Mock(name="other")+ thread_session_manager._local.session = cached+ thread_session_manager._local.username = "alice"+ try:+ # Pass the WRONG session: must be a no-op.+ result = thread_session_manager.reset_session_if_matches(other)+ assert result is False+ # The cache is untouched — alice's session is still there.+ assert thread_session_manager._local.session is cached+ assert thread_session_manager._local.username == "alice"++ # Pass the RIGHT session: must clear and return True.+ result = thread_session_manager.reset_session_if_matches(cached)+ assert result is True+ assert thread_session_manager._local.session is None+ finally:+ thread_session_manager._local.session = None+ thread_session_manager._local.username = None++ def test_reset_session_if_matches_with_none_session_is_noop(self):+ """``reset_session_if_matches(None)`` is a defensive no-op so+ call sites can hand the helper a possibly-None session without+ a separate guard.+ """+ from local_deep_research.database.thread_local_session import (+ thread_session_manager,+ )++ # No session cached → no-op.+ assert thread_session_manager.reset_session_if_matches(None) is False++ # Session cached but identity doesn't match → still no-op.+ cached = Mock()+ thread_session_manager._local.session = cached+ try:+ assert (+ thread_session_manager.reset_session_if_matches(None) is False+ )+ assert thread_session_manager._local.session is cached+ finally:+ thread_session_manager._local.session = Nonediff --git a/tests/metrics/test_search_tracker_coverage.py b/tests/metrics/test_search_tracker_coverage.pyindex c46ef1b9d6..71615fb589 100644--- a/tests/metrics/test_search_tracker_coverage.py+++ b/tests/metrics/test_search_tracker_coverage.py@@ -237,6 +237,98 @@ class TestRecordSearchOuterException:query="q",)+ def test_search_metrics_write_failure_logs_via_logger_warning_with_redaction(+ self,+ ):+ """The search-metrics write failure path runs while the user's+ encryption ``password`` is in scope (``context.get('user_password')``).+ ``logger.exception`` would attach the originating traceback —+ which can include the password — so the path uses+ ``logger.warning`` with a ``scrub_error``-sanitized exception+ string. This test pins both halves of that contract:+ ``logger.warning`` is called once with the identifying message,+ and the exception is run through ``scrub_error`` with the in-scope+ password.+ """+ import local_deep_research.metrics.search_tracker as st_mod++ ctx = _base_context()+ mock_session = MagicMock()+ mock_cm = _mock_session_cm(mock_session)+ # Force the inner ``with metrics_writer.get_session(...)`` to raise+ # so the inner except branch fires.+ mock_cm.__enter__.side_effect = RuntimeError("simulated DB failure")+ mock_writer = MagicMock()+ mock_writer.get_session.return_value = mock_cm++ with (+ patch.object(st_mod, "get_search_context", return_value=ctx),+ patch.object(st_mod, "logger") as mock_logger,+ patch(+ "local_deep_research.database.thread_metrics.metrics_writer",+ mock_writer,+ ),+ patch(+ "local_deep_research.security.log_sanitizer.scrub_error",+ wraps=lambda e, *s: str(e),+ ) as mock_scrub,+ ):+ SearchTracker.record_search(+ engine_name="brave",+ query="q",+ )++ mock_scrub.assert_called_once()+ scrub_args = mock_scrub.call_args.args+ assert "simulated DB failure" in str(scrub_args[0])+ assert scrub_args[1] == ctx["user_password"]+ mock_logger.warning.assert_called_once()+ assert (+ "Failed to write search metrics"+ in mock_logger.warning.call_args[0][0]+ )+ mock_logger.exception.assert_not_called()++ def test_search_tracker_outer_exception_logs_via_logger_warning_with_scrub_error(+ self,+ ):+ """The outer ``record_search`` failure path logs via ``logger.warning``+ with ``scrub_error`` sanitization using the in-scope password.+ """+ import local_deep_research.metrics.search_tracker as st_mod++ def mock_get(key, default=None):+ if key == "username":+ return "bob"+ if key == "user_password":+ raise RuntimeError("outer context lookup error")+ return default++ ctx = MagicMock()+ ctx.get.side_effect = mock_get+ with (+ patch.object(st_mod, "get_search_context", return_value=ctx),+ patch.object(st_mod, "logger") as mock_logger,+ patch(+ "local_deep_research.security.log_sanitizer.scrub_error",+ wraps=lambda e, *s: str(e),+ ) as mock_scrub,+ ):+ SearchTracker.record_search(+ engine_name="brave",+ query="q",+ )++ mock_scrub.assert_called_once()+ scrub_args = mock_scrub.call_args.args+ assert "outer context lookup error" in str(scrub_args[0])+ mock_logger.warning.assert_called_once()+ assert (+ "Failed to record search call"+ in mock_logger.warning.call_args[0][0]+ )+ mock_logger.exception.assert_not_called()+# ===========================================================================# get_search_metrics -- engine stats formatting, success_rate, truncationdiff --git a/tests/metrics/test_token_counter_coverage.py b/tests/metrics/test_token_counter_coverage.pyindex 43b5c72a79..c916fc8f24 100644--- a/tests/metrics/test_token_counter_coverage.py+++ b/tests/metrics/test_token_counter_coverage.py@@ -202,6 +202,81 @@ class TestSaveToDbBackgroundThreadCoverage:):cb._save_to_db(100, 50)+ def test_metrics_writer_exception_logs_via_logger_warning_with_redaction(+ self,+ ):+ """The metrics-write failure path runs inside a worker thread+ that has the user's encryption ``password`` in scope. ``logger.exception``+ would attach the traceback (which can include the password from+ the originating exception) — that is unsafe here, so the path+ uses ``logger.warning`` with a ``scrub_error``-sanitized+ exception string. This test pins both halves of that contract:+ ``logger.warning`` is called once with the identifying message,+ and the exception is run through ``scrub_error`` with the in-scope+ password.+ """+ import local_deep_research.metrics.token_counter as tc_mod++ cb = _make_callback(+ research_context={"username": "bob", "user_password": "secret"}+ )+ mock_writer = MagicMock()+ mock_writer.write_token_metrics.side_effect = RuntimeError("fail")+ with _patch_worker_thread():+ with patch.object(tc_mod, "logger") as mock_logger:+ with patch(+ "local_deep_research.database.thread_metrics.metrics_writer",+ mock_writer,+ ):+ with patch(+ "local_deep_research.security.log_sanitizer.scrub_error",+ wraps=lambda e, *s: str(e),+ ) as mock_scrub:+ cb._save_to_db(100, 50)++ mock_scrub.assert_called_once()+ scrub_args = mock_scrub.call_args.args+ assert "fail" in str(scrub_args[0])+ assert scrub_args[1] == "secret"+ mock_logger.warning.assert_called_once()+ assert (+ "Failed to write metrics from thread"+ in mock_logger.warning.call_args[0][0]+ )+ mock_logger.exception.assert_not_called()++ def test_main_thread_save_to_db_exception_logs_via_logger_warning_with_scrub_error(+ self,+ ):+ """The main-thread ``_save_to_db`` failure path uses ``logger.warning``+ with ``scrub_error`` sanitization.+ """+ import local_deep_research.metrics.token_counter as tc_mod++ cb = _make_callback(research_context={})+ with (+ patch("flask.session", {"username": "bob"}),+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ side_effect=RuntimeError("db connection failed"),+ ),+ patch.object(tc_mod, "logger") as mock_logger,+ patch(+ "local_deep_research.security.log_sanitizer.scrub_error",+ wraps=lambda e, *s: str(e),+ ) as mock_scrub,+ ):+ cb._save_to_db(100, 50)++ mock_scrub.assert_called_once()+ assert "db connection failed" in str(mock_scrub.call_args.args[0])+ mock_logger.warning.assert_called_once()+ assert (+ "Error saving token usage to database"+ in mock_logger.warning.call_args[0][0]+ )+ mock_logger.exception.assert_not_called()+def test_writes_token_data_with_context_overflow_fields(self):cb = _make_callback(research_context={diff --git a/tests/utilities/test_log_utils.py b/tests/utilities/test_log_utils.pyindex 528877f6af..943566dd3b 100644--- a/tests/utilities/test_log_utils.py+++ b/tests/utilities/test_log_utils.py@@ -539,6 +539,252 @@ class TestTruncateForDatabase:assert queued["message"].startswith("Z" * DATABASE_MESSAGE_MAX_LENGTH)assert "truncated" in queued["message"]+ def test_database_sink_persists_exception_context_on_error_records(self):+ """When ``logger.exception`` is used, the persisted+ ``app_logs.message`` previously contained only the bare message+ string ("LangGraph agent error") with the exception type and value+ stripped out. The DB sink now prefixes a short ``[Type: value]``+ context when the record carries an active exception, so an+ investigator querying ``app_logs`` can distinguish the same line+ emitted under different failure modes without the full traceback+ (which the diagnose=False policy on the encrypted-DB sink forbids+ per #4182).+ """+ from loguru._logger import RecordException++ from local_deep_research.utilities.log_utils import database_sink++ mock_message = Mock()+ mock_message.record = {+ "time": datetime.now(),+ "message": "LangGraph agent error",+ "name": "strategies.langgraph_agent_strategy",+ "function": "analyze_topic",+ "line": 1598,+ "level": Mock(name="ERROR"),+ "extra": {"research_id": "rid-ctx"},+ # RecordException is loguru's internal namedtuple+ # (type, value, traceback). The DB sink reads it via+ # record.get("exception") and renders a short prefix.+ "exception": RecordException(+ ValueError, ValueError("Unknown search engine 'foo'"), None+ ),+ }++ with patch(+ "local_deep_research.utilities.log_utils.has_app_context",+ return_value=False,+ ):+ with patch(+ "local_deep_research.utilities.log_utils._log_queue"+ ) as mock_queue:+ database_sink(mock_message)++ mock_queue.put_nowait.assert_called_once()+ queued = mock_queue.put_nowait.call_args[0][0]+ assert queued["message"].startswith(+ "[ValueError: Unknown search engine 'foo'] "+ )+ # The original bare message is preserved as the suffix so downstream+ # filters and search by message text still work.+ assert "LangGraph agent error" in queued["message"]+ # No traceback frame is ever rendered to the encrypted-DB row.+ assert "Traceback" not in queued["message"]++ def test_database_sink_unchanged_when_record_has_no_exception(self):+ """Records without an active exception (e.g. INFO/DEBUG logs)+ pass through unchanged — the prefix is only added when loguru+ attached a RecordException to the record."""+ from local_deep_research.utilities.log_utils import database_sink++ mock_message = Mock()+ mock_message.record = {+ "time": datetime.now(),+ "message": "Search completed",+ "name": "mod",+ "function": "fn",+ "line": 1,+ "level": Mock(name="INFO"),+ "extra": {"research_id": "rid-noexc"},+ "exception": None,+ }++ with patch(+ "local_deep_research.utilities.log_utils.has_app_context",+ return_value=False,+ ):+ with patch(+ "local_deep_research.utilities.log_utils._log_queue"+ ) as mock_queue:+ database_sink(mock_message)++ queued = mock_queue.put_nowait.call_args[0][0]+ assert queued["message"] == "Search completed"+ assert "[" not in queued["message"]++ def test_database_sink_truncates_long_exception_values(self):+ """An exception whose ``str()`` is hundreds of chars long should+ be bounded — the same prefix-then-truncation discipline that+ applies to plain message bodies also applies to the exception+ context, so a 5 KB ``repr()`` doesn't blow past the per-row+ ``DATABASE_MESSAGE_MAX_LENGTH`` budget."""+ from loguru._logger import RecordException++ from local_deep_research.utilities.log_utils import (+ DATABASE_MESSAGE_MAX_LENGTH,+ database_sink,+ )++ long_value = "x" * 600+ mock_message = Mock()+ mock_message.record = {+ "time": datetime.now(),+ "message": "boom",+ "name": "mod",+ "function": "fn",+ "line": 1,+ "level": Mock(name="ERROR"),+ "extra": {"research_id": "rid-bigexc"},+ "exception": RecordException(+ RuntimeError, RuntimeError(long_value), None+ ),+ }++ with patch(+ "local_deep_research.utilities.log_utils.has_app_context",+ return_value=False,+ ):+ with patch(+ "local_deep_research.utilities.log_utils._log_queue"+ ) as mock_queue:+ database_sink(mock_message)++ queued = mock_queue.put_nowait.call_args[0][0]+ # 240 char cap on the value preview (per _exception_context's own+ # documented contract), with ellipsis once exceeded. The full+ # 600-char value must NOT be present.+ assert long_value not in queued["message"]+ assert "…" in queued["message"]+ assert len(queued["message"]) < DATABASE_MESSAGE_MAX_LENGTH + 200++ def test_database_sink_handles_tuple_exceptions(self):+ """Standard tuple sys.exc_info() stored in record['exception'] should be supported."""+ from local_deep_research.utilities.log_utils import database_sink++ mock_message = Mock()+ mock_message.record = {+ "time": datetime.now(),+ "message": "tuple exc",+ "name": "mod",+ "function": "fn",+ "line": 1,+ "level": Mock(name="ERROR"),+ "extra": {"research_id": "rid-tuple"},+ "exception": (TypeError, TypeError("invalid type"), None),+ }++ with patch(+ "local_deep_research.utilities.log_utils.has_app_context",+ return_value=False,+ ):+ with patch(+ "local_deep_research.utilities.log_utils._log_queue"+ ) as mock_queue:+ database_sink(mock_message)++ queued = mock_queue.put_nowait.call_args[0][0]+ assert queued["message"].startswith("[TypeError: invalid type] ")++ def test_database_sink_handles_unprintable_exceptions(self):+ """If str(exc_value) raises an exception, _exception_context should not crash."""+ from local_deep_research.utilities.log_utils import database_sink++ class FaultyException(Exception):+ def __str__(self):+ raise RuntimeError("str failed")++ mock_message = Mock()+ mock_message.record = {+ "time": datetime.now(),+ "message": "faulty str",+ "name": "mod",+ "function": "fn",+ "line": 1,+ "level": Mock(name="ERROR"),+ "extra": {"research_id": "rid-faulty"},+ "exception": (FaultyException, FaultyException(), None),+ }++ with patch(+ "local_deep_research.utilities.log_utils.has_app_context",+ return_value=False,+ ):+ with patch(+ "local_deep_research.utilities.log_utils._log_queue"+ ) as mock_queue:+ database_sink(mock_message)++ queued = mock_queue.put_nowait.call_args[0][0]+ assert "[FaultyException: <unprintable exception>]" in queued["message"]++ def test_database_sink_sanitizes_credentials_in_exception_context(self):+ """Exception messages containing credential shapes (e.g. DSN passwords or API keys)+ must be scrubbed via sanitize_error_message in _exception_context before being written to app_logs."""+ from loguru._logger import RecordException++ from local_deep_research.utilities.log_utils import database_sink++ secret_dsn = "postgresql://user:supersecretpass@localhost:5432/db"+ mock_message = Mock()+ mock_message.record = {+ "time": datetime.now(),+ "message": "Connection error",+ "name": "mod",+ "function": "fn",+ "line": 1,+ "level": Mock(name="ERROR"),+ "extra": {"research_id": "rid-sanitized"},+ "exception": RecordException(+ RuntimeError,+ RuntimeError(f"Failed to connect to {secret_dsn}"),+ None,+ ),+ }++ with patch(+ "local_deep_research.utilities.log_utils.has_app_context",+ return_value=False,+ ):+ with patch(+ "local_deep_research.utilities.log_utils._log_queue"+ ) as mock_queue:+ database_sink(mock_message)++ queued = mock_queue.put_nowait.call_args[0][0]+ assert "supersecretpass" not in queued["message"]+ assert queued["message"].startswith(+ "[RuntimeError: Failed to connect to postgresql://[REDACTED]"+ )++ def test_exception_context_precaps_large_exception_messages(self):+ """_exception_context should pre-cap massive exception message strings before running sanitize_error_message."""+ from loguru._logger import RecordException++ from local_deep_research.utilities.log_utils import _exception_context++ large_err_msg = "A" * 10000 + "Bearer secret-token-12345"+ record = {+ "exception": RecordException(+ RuntimeError, RuntimeError(large_err_msg), None+ )+ }++ result = _exception_context(record)+ # Verify it was capped to 240 chars (237 + '…')+ assert len(result) <= 260+ assert result.startswith("[RuntimeError: AAAAAA")+ assert result.endswith("…] ")+class TestFrontendProgressSink:"""Tests for frontend_progress_sink function."""