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(logs): make flush_log_queue non-blocking + add log daemon (#3488)

LearningCircuit87bdfaf78815
diff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.py
index 8bf996e4ef..eb51e7f517 100644
--- a/src/local_deep_research/utilities/log_utils.py
+++ b/src/local_deep_research/utilities/log_utils.py
@@ -30,6 +30,7 @@ _LOG_DIR.mkdir(parents=True, exist_ok=True)
# Thread-safe queue for database logs from background threads
_log_queue = queue.Queue(maxsize=1000)
_queue_processor_thread = None
+_queue_processor_lock = threading.Lock()
_stop_queue = threading.Event()
"""
Default log directory to use.
@@ -115,8 +116,12 @@ def _get_research_id(record=None) -> str | None:
def _process_log_queue():
"""
- Process logs from the queue in a dedicated thread with app context.
- This runs in the main thread context to avoid SQLite thread safety issues.
+ Process logs from the queue in a dedicated daemon thread.
+
+ Safe to run off the main thread: ``_write_log_to_database`` uses
+ ``get_user_db_session`` which yields a thread-local SQLAlchemy session,
+ and the underlying SQLite engines are opened with
+ ``check_same_thread=False``.
"""
while not _stop_queue.is_set():
try:
@@ -236,8 +241,13 @@ def frontend_progress_sink(message: loguru.Message) -> None:
def flush_log_queue():
"""
- Flush all pending logs from the queue to the database.
- This should be called from a Flask request context.
+ Drain all pending logs from the queue to the database.
+
+ Used at process exit (see ``flush_logs_on_exit`` in ``web/app.py``) to
+ drain whatever the background daemon did not get to before it was
+ stopped. The request path no longer calls this — the
+ ``start_log_queue_processor`` daemon handles steady-state drainage so
+ requests never block on DB writes.
"""
flushed = 0
while not _log_queue.empty():
@@ -254,6 +264,67 @@ def flush_log_queue():
logger.debug(f"Flushed {flushed} queued log entries to database")
+def start_log_queue_processor(app) -> threading.Thread:
+ """Start the background daemon that drains the log queue into the DB.
+
+ Runs ``_process_log_queue`` inside an application context so writes
+ have a Flask context, and so the daemon can work independently of
+ any in-flight request. Idempotent: calling twice is a no-op.
+
+ Args:
+ app: The Flask app whose context the daemon should push.
+
+ Returns:
+ The daemon thread (running).
+ """
+ global _queue_processor_thread
+ with _queue_processor_lock:
+ if (
+ _queue_processor_thread is not None
+ and _queue_processor_thread.is_alive()
+ ):
+ return _queue_processor_thread
+
+ _stop_queue.clear()
+
+ def _run():
+ # Push an app context for the lifetime of the daemon so
+ # the queue processor can call into DB code that requires
+ # Flask g.
+ with app.app_context():
+ _process_log_queue()
+
+ _queue_processor_thread = threading.Thread(
+ target=_run,
+ name="log-queue-processor",
+ daemon=True,
+ )
+ _queue_processor_thread.start()
+ thread = _queue_processor_thread
+ logger.info("Log queue processor daemon started")
+ return thread
+
+
+def stop_log_queue_processor(timeout: float = 2.0) -> None:
+ """Signal the log queue processor to stop and wait briefly for it."""
+ global _queue_processor_thread
+ _stop_queue.set()
+ with _queue_processor_lock:
+ thread = _queue_processor_thread
+ if thread is not None:
+ thread.join(timeout=timeout)
+ # Only clear the reference if the thread actually exited. If join
+ # timed out the daemon is still running, and clearing the ref would
+ # let a subsequent start_log_queue_processor() spawn a second
+ # daemon that drains the same queue concurrently. Re-check identity
+ # under the lock so we don't accidentally null out a fresh thread
+ # that another start spawned in the meantime.
+ if not thread.is_alive():
+ with _queue_processor_lock:
+ if _queue_processor_thread is thread:
+ _queue_processor_thread = None
+
+
def config_logger(name: str, debug: bool = False) -> None:
"""
Configures the default logger.
diff --git a/src/local_deep_research/web/app.py b/src/local_deep_research/web/app.py
index bdc273bfe0..3a681a6971 100644
--- a/src/local_deep_research/web/app.py
+++ b/src/local_deep_research/web/app.py
@@ -4,7 +4,12 @@ import traceback
from loguru import logger
from ..__version__ import __version__
-from ..utilities.log_utils import config_logger, flush_log_queue
+from ..utilities.log_utils import (
+ config_logger,
+ flush_log_queue,
+ start_log_queue_processor,
+ stop_log_queue_processor,
+)
from .app_factory import create_app
from .server_config import load_server_config
@@ -65,25 +70,19 @@ def main():
config_logger("ldr_web", debug=config["debug"])
logger.info(f"Starting Local Deep Research v{__version__}")
- # Register atexit handler to flush logs on exit
- def flush_logs_on_exit():
- """Flush any pending logs when the program exits."""
- try:
- # Create a minimal Flask app context to allow database access
- from flask import Flask
-
- app = Flask(__name__)
- with app.app_context():
- flush_log_queue()
- except Exception:
- logger.exception("Failed to flush logs on exit")
-
- atexit.register(flush_logs_on_exit)
- logger.debug("Registered atexit handler for log flushing")
-
# Create the Flask app and SocketIO instance
app, socket_service = create_app()
+ # Start the background log-queue processor. With no ``before_request``
+ # handler pulling from the queue, this daemon is the only drain path
+ # during normal operation; a final drain runs at atexit.
+ daemon_started = False
+ try:
+ start_log_queue_processor(app)
+ daemon_started = True
+ except Exception:
+ logger.exception("Failed to start log queue processor")
+
# Get web server settings from environment variables (LDR_WEB_HOST, etc.)
# These require a server restart to take effect
host = config["host"]
@@ -104,6 +103,7 @@ def main():
# Guard against Flask debug reloader spawning duplicate schedulers
import os
+ cleanup_scheduler = None
if not debug or os.environ.get("WERKZEUG_RUN_MAIN") == "true":
from .auth.connection_cleanup import start_connection_cleanup_scheduler
from .auth.session_manager import session_manager
@@ -113,14 +113,11 @@ def main():
cleanup_scheduler = start_connection_cleanup_scheduler(
session_manager, db_manager
)
- atexit.register(lambda: cleanup_scheduler.shutdown(wait=False))
except Exception:
logger.warning(
"Failed to start cleanup scheduler; idle connections will not be auto-closed",
)
- cleanup_scheduler = None
- # Register shutdown handler for scheduler
def shutdown_scheduler():
if (
hasattr(app, "background_job_scheduler")
@@ -132,9 +129,6 @@ def main():
except Exception:
logger.exception("Error stopping scheduler")
- atexit.register(shutdown_scheduler)
-
- # Register shutdown handler for database connections
def shutdown_databases():
try:
from ..database.encrypted_db import db_manager
@@ -144,7 +138,32 @@ def main():
except Exception:
logger.exception("Error closing database connections")
+ def flush_logs_on_exit():
+ """Drain remaining queued logs after the daemon has stopped."""
+ try:
+ # Use a minimal Flask context here rather than the main app so
+ # the flush still works if the main app is already torn down.
+ from flask import Flask
+
+ exit_app = Flask(__name__)
+ with exit_app.app_context():
+ flush_log_queue()
+ except Exception:
+ logger.exception("Failed to flush logs on exit")
+
+ # atexit runs LIFO, so register in reverse of desired execution order.
+ # Desired execution:
+ # 1. stop_log_queue_processor — daemon releases the queue
+ # 2. flush_logs_on_exit — drain whatever the daemon missed
+ # 3. shutdown_scheduler + cleanup_scheduler — stop other workers
+ # 4. shutdown_databases — close engines last
atexit.register(shutdown_databases)
+ atexit.register(shutdown_scheduler)
+ if cleanup_scheduler is not None:
+ atexit.register(lambda: cleanup_scheduler.shutdown(wait=False))
+ atexit.register(flush_logs_on_exit)
+ if daemon_started:
+ atexit.register(stop_log_queue_processor)
# Use the SocketIOService's run method which properly runs the socketio server
socket_service.run(host=host, port=port, debug=debug)
diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.py
index 070b77630a..a3e114398f 100644
--- a/src/local_deep_research/web/app_factory.py
+++ b/src/local_deep_research/web/app_factory.py
@@ -535,12 +535,14 @@ def apply_middleware(app):
logger.info("All middleware registered")
- # Flush any queued logs from background threads
- logger.info("Importing log_utils...")
- from ..utilities.log_utils import flush_log_queue
-
- app.before_request(flush_log_queue)
- logger.info("Log flushing middleware registered")
+ # Note: log-queue flushing is handled asynchronously by the
+ # background daemon started in web/app.py::main() (see
+ # start_log_queue_processor). We deliberately do NOT register
+ # flush_log_queue as a before_request handler: doing so makes
+ # every request (including GET /auth/login) synchronously wait
+ # on _write_log_to_database, which opens a user DB session and
+ # blocks if the shared connection pool is wedged. At-exit
+ # draining is still handled via atexit in web/app.py.
# Inject backend constants into Jinja2 templates for frontend JS.
# This is the Flask-documented pattern for sharing Python enums with JavaScript.
diff --git a/tests/utilities/test_log_utils.py b/tests/utilities/test_log_utils.py
index d61b8c8a28..f1834af860 100644
--- a/tests/utilities/test_log_utils.py
+++ b/tests/utilities/test_log_utils.py
@@ -621,3 +621,71 @@ class TestWriteLogToDatabase:
):
# Should not raise
_write_log_to_database(log_entry)
+
+
+class TestLogQueueProcessorDaemon:
+ """Tests for start_log_queue_processor / stop_log_queue_processor."""
+
+ def _make_fake_app(self):
+ """Return a Flask-app-like stub that supports ``with app.app_context()``."""
+ fake_app = MagicMock()
+ ctx = MagicMock()
+ ctx.__enter__ = Mock(return_value=None)
+ ctx.__exit__ = Mock(return_value=False)
+ fake_app.app_context.return_value = ctx
+ return fake_app
+
+ def test_spawns_daemon_thread(self):
+ from local_deep_research.utilities import log_utils
+
+ app = self._make_fake_app()
+ try:
+ thread = log_utils.start_log_queue_processor(app)
+ assert isinstance(thread, threading.Thread)
+ assert thread.daemon is True
+ assert thread.is_alive()
+ assert thread.name == "log-queue-processor"
+ finally:
+ log_utils.stop_log_queue_processor(timeout=2.0)
+
+ def test_is_idempotent(self):
+ from local_deep_research.utilities import log_utils
+
+ app = self._make_fake_app()
+ try:
+ first = log_utils.start_log_queue_processor(app)
+ second = log_utils.start_log_queue_processor(app)
+ assert first is second
+ finally:
+ log_utils.stop_log_queue_processor(timeout=2.0)
+
+ def test_stop_joins_thread(self):
+ from local_deep_research.utilities import log_utils
+
+ app = self._make_fake_app()
+ thread = log_utils.start_log_queue_processor(app)
+ log_utils.stop_log_queue_processor(timeout=2.0)
+ assert not thread.is_alive()
+
+ def test_stop_does_not_clear_ref_when_join_times_out(self):
+ """If the daemon doesn't exit before join() times out, the
+ module-level reference must stay populated — otherwise a
+ subsequent start would happily spawn a second daemon competing
+ for the same queue."""
+ from local_deep_research.utilities import log_utils
+
+ # Stand-in thread that ignores the stop signal so join() always
+ # times out. Daemon=True so it doesn't keep the test process alive.
+ live_thread = threading.Thread(
+ target=lambda: threading.Event().wait(), daemon=True
+ )
+ live_thread.start()
+ log_utils._queue_processor_thread = live_thread
+ try:
+ log_utils.stop_log_queue_processor(timeout=0.05)
+ assert log_utils._queue_processor_thread is live_thread, (
+ "thread reference cleared despite join timing out — would "
+ "let start_log_queue_processor spawn a duplicate daemon"
+ )
+ finally:
+ log_utils._queue_processor_thread = None
diff --git a/tests/web/test_app_coverage.py b/tests/web/test_app_coverage.py
index 989fb1dd37..e946da36a6 100644
--- a/tests/web/test_app_coverage.py
+++ b/tests/web/test_app_coverage.py
@@ -12,6 +12,8 @@ because they are not present as attributes on the app module itself.
import os
from unittest.mock import MagicMock, patch
+import pytest
+
MODULE = "local_deep_research.web.app"
@@ -21,6 +23,27 @@ _SESSION_MOD = "local_deep_research.web.auth.session_manager"
_DB_MOD = "local_deep_research.database.encrypted_db"
[email protected](autouse=True)
+def _stub_log_queue_daemon():
+ """Prevent main() from spawning a real log-queue daemon thread during tests."""
+ with (
+ patch(f"{MODULE}.start_log_queue_processor"),
+ patch(f"{MODULE}.stop_log_queue_processor"),
+ ):
+ yield
+
+
+def _handler_by_name(captured, name):
+ """Locate an atexit handler by function name (order-independent)."""
+ for fn in captured:
+ if getattr(fn, "__name__", None) == name:
+ return fn
+ raise AssertionError(
+ f"No captured handler named {name!r}; got "
+ f"{[getattr(fn, '__name__', repr(fn)) for fn in captured]}"
+ )
+
+
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
@@ -278,7 +301,8 @@ class TestMainAtexitRegistrations:
from local_deep_research.web import app as app_module
app_module.main()
- # Expect flush_logs, cleanup-scheduler lambda, shutdown_scheduler, shutdown_databases
+ # Expect: shutdown_databases, shutdown_scheduler, cleanup-scheduler
+ # lambda, flush_logs_on_exit, stop_log_queue_processor
assert mock_reg.call_count >= 3
@@ -386,9 +410,7 @@ class TestFlushLogsOnExit:
def test_flush_handler_calls_flush_log_queue(self):
with patch(f"{MODULE}.flush_log_queue") as mock_flush:
captured = self._run_and_capture()
- assert len(captured) >= 1
- # First registered handler is flush_logs_on_exit
- captured[0]()
+ _handler_by_name(captured, "flush_logs_on_exit")()
mock_flush.assert_called_once()
def test_flush_handler_swallows_exceptions(self):
@@ -396,8 +418,7 @@ class TestFlushLogsOnExit:
f"{MODULE}.flush_log_queue", side_effect=RuntimeError("log error")
):
captured = self._run_and_capture()
- flush_handler = captured[0]
- flush_handler() # must not raise
+ _handler_by_name(captured, "flush_logs_on_exit")() # must not raise
# ---------------------------------------------------------------------------
@@ -500,14 +521,13 @@ class TestShutdownDatabasesHandler:
def test_shutdown_databases_calls_close_all_databases(self):
mock_db_manager = MagicMock()
captured = self._run_and_capture_handlers()
- # Invoke the last handler with db_manager patched at source
- last_handler = captured[-1]
+ handler = _handler_by_name(captured, "shutdown_databases")
with patch(f"{_DB_MOD}.db_manager", mock_db_manager):
- last_handler()
+ handler()
mock_db_manager.close_all_databases.assert_called_once()
def test_shutdown_databases_swallows_exceptions(self):
captured = self._run_and_capture_handlers()
- last_handler = captured[-1]
+ handler = _handler_by_name(captured, "shutdown_databases")
with patch(f"{_DB_MOD}.db_manager", side_effect=ImportError("db gone")):
- last_handler() # must not propagate
+ handler() # must not propagate
diff --git a/tests/web/test_app_main_coverage.py b/tests/web/test_app_main_coverage.py
index 2dba55704a..3ba2119b1c 100644
--- a/tests/web/test_app_main_coverage.py
+++ b/tests/web/test_app_main_coverage.py
@@ -18,6 +18,8 @@ Tests:
import os
from unittest.mock import MagicMock, patch
+import pytest
+
MODULE = "local_deep_research.web.app"
@@ -26,6 +28,27 @@ _SESSION_MOD = "local_deep_research.web.auth.session_manager"
_DB_MOD = "local_deep_research.database.encrypted_db"
[email protected](autouse=True)
+def _stub_log_queue_daemon():
+ """Prevent main() from spawning a real log-queue daemon thread during tests."""
+ with (
+ patch(f"{MODULE}.start_log_queue_processor"),
+ patch(f"{MODULE}.stop_log_queue_processor"),
+ ):
+ yield
+
+
+def _handler_by_name(captured, name):
+ """Locate an atexit handler by function name (order-independent)."""
+ for fn in captured:
+ if getattr(fn, "__name__", None) == name:
+ return fn
+ raise AssertionError(
+ f"No captured handler named {name!r}; got "
+ f"{[getattr(fn, '__name__', repr(fn)) for fn in captured]}"
+ )
+
+
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
@@ -326,12 +349,17 @@ class TestMainCleanupSchedulerStart:
app_module.main()
- # At least 4 atexit handlers: flush_logs, cleanup lambda, shutdown_scheduler, shutdown_db
+ # At least 4 atexit handlers: shutdown_db, shutdown_scheduler,
+ # cleanup lambda, flush_logs, (+ stop_log_queue_processor)
assert len(atexit_calls) >= 4
- # Find and call the lambda (second registered handler)
- cleanup_lambda = atexit_calls[1]
- cleanup_lambda()
+ # The cleanup_scheduler.shutdown call is an anonymous lambda — locate
+ # it by calling each handler and finding the one that triggers
+ # mock_scheduler.shutdown.
+ for handler in atexit_calls:
+ if getattr(handler, "__name__", None) == "<lambda>":
+ handler()
+ break
mock_scheduler.shutdown.assert_called_once_with(wait=False)
@@ -396,9 +424,14 @@ class TestMainCleanupSchedulerFailure:
app_module.main()
- # When scheduler fails, atexit lambda is NOT registered for it (only 3 handlers)
- # flush_logs + shutdown_scheduler + shutdown_databases = 3
- assert len(atexit_calls) == 3
+ # When scheduler fails, no cleanup-scheduler lambda is registered.
+ # The other handlers (shutdown_databases, shutdown_scheduler,
+ # flush_logs_on_exit, stop_log_queue_processor) are still registered.
+ handler_names = [getattr(h, "__name__", None) for h in atexit_calls]
+ assert "<lambda>" not in handler_names
+ assert "shutdown_databases" in handler_names
+ assert "shutdown_scheduler" in handler_names
+ assert "flush_logs_on_exit" in handler_names
# ---------------------------------------------------------------------------
@@ -521,36 +554,36 @@ class TestMainShutdownDatabasesAtexit:
return captured
def test_close_all_databases_called(self):
- """The last atexit handler calls db_manager.close_all_databases()."""
+ """The shutdown_databases atexit handler calls db_manager.close_all_databases()."""
captured = self._run_and_capture()
mock_db_manager = MagicMock()
- # shutdown_databases is the last registered handler
- last_handler = captured[-1]
+ handler = _handler_by_name(captured, "shutdown_databases")
with patch(f"{_DB_MOD}.db_manager", mock_db_manager):
- last_handler()
+ handler()
mock_db_manager.close_all_databases.assert_called_once()
def test_shutdown_databases_swallows_import_error(self):
"""shutdown_databases does not propagate exceptions."""
captured = self._run_and_capture()
- last_handler = captured[-1]
+ handler = _handler_by_name(captured, "shutdown_databases")
# Simulate import failure inside the handler
with patch(f"{_DB_MOD}.db_manager", side_effect=ImportError("gone")):
- last_handler() # must not raise
+ handler() # must not raise
def test_shutdown_databases_swallows_runtime_error(self):
"""shutdown_databases swallows RuntimeError from close_all_databases."""
captured = self._run_and_capture()
- last_handler = captured[-1]
+ handler = _handler_by_name(captured, "shutdown_databases")
mock_db = MagicMock()
mock_db.close_all_databases.side_effect = RuntimeError("db error")
with patch(f"{_DB_MOD}.db_manager", mock_db):
- last_handler() # must not raise
+ handler() # must not raise
def test_at_least_three_atexit_handlers_registered(self):
"""main() always registers at least 3 atexit handlers."""
captured = self._run_and_capture()
- # flush_logs + shutdown_scheduler + shutdown_databases (+ optional scheduler lambda)
+ # shutdown_databases + shutdown_scheduler + flush_logs_on_exit
+ # (+ optional cleanup-scheduler lambda, + stop_log_queue_processor)
assert len(captured) >= 3
@@ -593,10 +626,9 @@ class TestFlushLogsOnExit:
return captured
def test_first_handler_is_flush_logs(self):
- """flush_logs_on_exit is the first atexit handler registered; calling it flushes logs."""
+ """Calling the flush_logs_on_exit atexit handler flushes the log queue."""
captured = self._run_and_capture()
- assert len(captured) >= 1
- flush_handler = captured[0]
+ flush_handler = _handler_by_name(captured, "flush_logs_on_exit")
# Patch flush_log_queue at the module where flush_logs_on_exit imports it
with patch(f"{MODULE}.flush_log_queue") as mock_flush:
flush_handler()
@@ -605,8 +637,7 @@ class TestFlushLogsOnExit:
def test_flush_handler_swallows_exceptions(self):
"""flush_logs_on_exit does not propagate exceptions from flush_log_queue."""
captured = self._run_and_capture()
- flush_handler = captured[0]
- # Call while patching flush_log_queue to raise
+ flush_handler = _handler_by_name(captured, "flush_logs_on_exit")
with patch(
f"{MODULE}.flush_log_queue", side_effect=RuntimeError("log err")
):
@@ -615,7 +646,7 @@ class TestFlushLogsOnExit:
def test_flush_handler_uses_flask_app_context(self):
"""flush_logs_on_exit creates a minimal Flask app context before flushing."""
captured = self._run_and_capture()
- flush_handler = captured[0]
+ flush_handler = _handler_by_name(captured, "flush_logs_on_exit")
mock_flask_app = MagicMock()
mock_flask_app.app_context.return_value.__enter__ = MagicMock(