Skip to content

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

fix(observability): log uncaught exceptions on any daemon thread (#3489)

LearningCircuitb4d836ce2023
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index 7057369b29..c8aaded544 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -1,4 +1,6 @@
import atexit
+import threading
+import traceback
from loguru import logger
from ..__version__ import __version__
@@ -7,12 +9,57 @@ from .app_factory import create_app
from .server_config import load_server_config
+def _install_thread_excepthook() -> None:
+ """Install a global hook that loudly logs uncaught exceptions on any
+ thread — including daemon threads — so silent crashes in the queue
+ processor, APScheduler jobs, or the post-login background thread
+ surface in logs instead of leaving the app wedged with no signal.
+
+ Respects a previously-installed hook if any (chains to it).
+ """
+ previous = threading.excepthook
+
+ def _hook(args: threading.ExceptHookArgs) -> None:
+ # Don't try to log for SystemExit-in-thread; that is intentional.
+ if issubclass(args.exc_type, SystemExit):
+ return
+ try:
+ tb = "".join(
+ traceback.format_exception(
+ args.exc_type, args.exc_value, args.exc_traceback
+ )
+ )
+ thread_name = (
+ args.thread.name if args.thread is not None else "unknown"
+ )
+ logger.error(
+ f"Uncaught exception on thread {thread_name!r}: "
+ f"{args.exc_type.__name__}: {args.exc_value}\n{tb}"
+ )
+ except Exception:
+ pass # noqa: silent-exception — last-ditch; the excepthook itself must never crash the interpreter
+ finally:
+ # Chain to the previous hook (usually threading's default).
+ try:
+ previous(args)
+ except Exception:
+ pass # noqa: silent-exception — previous hook failing must not turn our hook into a crash vector
+
+ threading.excepthook = _hook
+
+
@logger.catch
def main():
"""
Entry point for the web application when run as a command.
This function is needed for the package's entry point to work properly.
"""
+ # Install the excepthook before any other threads are spawned so
+ # uncaught exceptions in daemon threads (queue processor, APScheduler
+ # jobs, post-login background thread) surface in logs instead of
+ # dying silently.
+ _install_thread_excepthook()
+
# Configure logging with milestone level
config = load_server_config()
config_logger("ldr_web", debug=config["debug"])
diff --git a/src/local_deep_research/web/auth/routes.py b/src/local_deep_research/web/auth/routes.py
index bde2fe45b1..3b9e8bbd9a 100644
--- a/src/local_deep_research/web/auth/routes.py
+++ b/src/local_deep_research/web/auth/routes.py
@@ -187,7 +187,24 @@ def _perform_post_login_tasks(username: str, password: str) -> None:
Each operation is wrapped in its own try/except so that one failure
does not prevent the others from running. All operations here are
idempotent and safe to retry on the next login.
+
+ An outer try/except wraps the whole body so any exception that
+ escapes the per-step handlers (for example a failure inside a
+ ``with`` context manager's __enter__ / __exit__) is logged loudly
+ with a traceback instead of dying silently in the daemon thread.
"""
+ try:
+ _perform_post_login_tasks_body(username, password)
+ except Exception:
+ logger.exception(
+ f"Post-login background thread crashed for user {username}"
+ )
+
+
+def _perform_post_login_tasks_body(username: str, password: str) -> None:
+ """Body of _perform_post_login_tasks — split out so the outer
+ try/except in the wrapper catches anything the per-step handlers
+ miss. See _perform_post_login_tasks for rationale."""
# 1. Settings version check + migration
#
# ATOMICITY INVARIANT: the defaults import and the `app.version`
diff --git a/tests/web/test_thread_excepthook.py b/tests/web/test_thread_excepthook.py
new file mode 100644
index 0000000000..84137ee941
--- /dev/null
+++ b/tests/web/test_thread_excepthook.py
@@ -0,0 +1,85 @@
+"""Tests for the daemon-thread excepthook.
+
+Covers:
+- _install_thread_excepthook logs uncaught exceptions from daemon threads.
+- _perform_post_login_tasks wraps its body so an otherwise-uncaught exception
+ from inside the `with` context managers is logged instead of disappearing.
+"""
+
+import threading
+from unittest.mock import MagicMock, patch
+
+
+def test_install_thread_excepthook_logs_uncaught_exception():
+ """After installing the hook, an uncaught exception on a daemon thread
+ must be logged at ERROR level including the exception type and the
+ thread name. Without this, silent crashes in the queue processor
+ or APScheduler jobs are the mechanism by which the login path
+ gradually starves.
+ """
+ from local_deep_research.web.app import _install_thread_excepthook
+
+ previous = threading.excepthook
+ _install_thread_excepthook()
+ try:
+ with patch("local_deep_research.web.app.logger") as mock_logger:
+
+ def raiser():
+ raise RuntimeError("boom from daemon")
+
+ t = threading.Thread(target=raiser, name="test-daemon", daemon=True)
+ t.start()
+ t.join(timeout=2.0)
+
+ assert not t.is_alive()
+ assert mock_logger.error.called, "excepthook did not log"
+
+ logged = mock_logger.error.call_args[0][0]
+ assert "test-daemon" in logged
+ assert "RuntimeError" in logged
+ assert "boom from daemon" in logged
+ finally:
+ threading.excepthook = previous
+
+
+def test_perform_post_login_tasks_catches_outer_exceptions():
+ """If the outer structure of _perform_post_login_tasks itself raises
+ (for example from inside a `with` context manager's __enter__) —
+ not inside a per-step try/except — the wrapper must log the
+ exception and not let the daemon thread die silently.
+ """
+ from local_deep_research.web.auth import routes
+
+ with (
+ patch.object(
+ routes,
+ "_perform_post_login_tasks_body",
+ side_effect=RuntimeError("outer failure"),
+ ),
+ patch.object(routes, "logger") as mock_logger,
+ ):
+ # Must not raise.
+ routes._perform_post_login_tasks("alice", "pw")
+
+ assert mock_logger.exception.called
+ msg = mock_logger.exception.call_args[0][0]
+ assert "alice" in msg
+ assert "crashed" in msg.lower() or "post-login" in msg.lower()
+
+
+def test_perform_post_login_tasks_body_runs_when_no_outer_error():
+ """Positive path: when the body succeeds, the wrapper forwards to
+ it exactly once with the right args, and does not log any
+ crash.
+ """
+ from local_deep_research.web.auth import routes
+
+ body = MagicMock()
+ with (
+ patch.object(routes, "_perform_post_login_tasks_body", body),
+ patch.object(routes, "logger") as mock_logger,
+ ):
+ routes._perform_post_login_tasks("bob", "pw")
+
+ body.assert_called_once_with("bob", "pw")
+ mock_logger.exception.assert_not_called()