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(mcp): drain the enqueue=True stderr sink before run_server() returns (#6194)

LearningCircuit8610691a9c0d
diff --git a/src/local_deep_research/mcp/server.py b/src/local_deep_research/mcp/server.py
index 8a1278e14a..694440d9e3 100644
--- a/src/local_deep_research/mcp/server.py
+++ b/src/local_deep_research/mcp/server.py
@@ -1076,23 +1076,133 @@ def configure_mcp_logging(sink=None):
def run_server():
"""Run the MCP server using STDIO transport."""
configure_mcp_logging()
- logger.info("Starting Local Deep Research MCP server...")
-
- # Phase-1 of the RAG plaintext-at-rest migration must run here too, not only
- # in the ldr-web entrypoint: an MCP-only deployment (Claude Desktop / Code /
- # OpenClaw) that never launches ldr-web would otherwise never purge a
- # pre-existing legacy plaintext <hash>.pkl docstore, leaving chunk text on
- # disk indefinitely. The sweep is filesystem-only (no DB/login needed),
- # idempotent (a clean tree no-ops), and logs its own errors — wrapped so a
- # cleanup issue never blocks the server. Mirrors web/app.py's main().
+
+ # The drain `finally` opens immediately after the sink exists, not just
+ # around `mcp.run()`: the startup window below logs through the same
+ # enqueue=True sink, and the legacy-docstore sweep only catches
+ # `Exception`. A KeyboardInterrupt/SystemExit raised inside
+ # `migrate_legacy_docstores()` would otherwise escape with the startup
+ # lines still queued and reproduce the very inversion this fixes.
try:
- from ..vector_stores.legacy_cleanup import migrate_legacy_docstores
+ logger.info("Starting Local Deep Research MCP server...")
+
+ # Phase-1 of the RAG plaintext-at-rest migration must run here too,
+ # not only in the ldr-web entrypoint: an MCP-only deployment (Claude
+ # Desktop / Code / OpenClaw) that never launches ldr-web would
+ # otherwise never purge a pre-existing legacy plaintext <hash>.pkl
+ # docstore, leaving chunk text on disk indefinitely. The sweep is
+ # filesystem-only (no DB/login needed), idempotent (a clean tree
+ # no-ops), and logs its own errors — wrapped so a cleanup issue never
+ # blocks the server. Mirrors web/app.py's main().
+ try:
+ from ..vector_stores.legacy_cleanup import (
+ migrate_legacy_docstores,
+ )
- migrate_legacy_docstores()
- except Exception:
- logger.exception("Legacy RAG docstore migration failed at MCP startup")
+ migrate_legacy_docstores()
+ except Exception:
+ logger.exception(
+ "Legacy RAG docstore migration failed at MCP startup"
+ )
- mcp.run(transport="stdio")
+ mcp.run(transport="stdio")
+ finally:
+ # Drain the enqueue=True stderr sink (see configure_mcp_logging)
+ # before this function returns or raises, on every exit a
+ # `finally` covers - normal disconnect, Exception, and BaseException
+ # (KeyboardInterrupt) alike.
+ #
+ # loguru's enqueue=True handler runs a daemon writer thread reading
+ # off a multiprocessing.SimpleQueue; loguru/__init__.py registers
+ # `atexit.register(logger.remove)` for us, and draining (verified in
+ # the installed loguru 0.7.3's _handler.py) is FIFO-sentinel based:
+ # `Handler.stop()` enqueues a `None` sentinel and joins the writer
+ # thread, so every message queued ahead of it is written first. On
+ # its own, that atexit hook already keeps the *normal*-shutdown case
+ # from losing buffered lines, as long as the interpreter reaches a
+ # normal shutdown.
+ #
+ # What the atexit hook does NOT fix is ordering on an unhandled
+ # exception. CPython's default excepthook prints the traceback to
+ # stderr once the exception has finished propagating out of the top
+ # frame, and only afterwards does the interpreter run its atexit
+ # callbacks - so the atexit drain is strictly later than the
+ # traceback. Without this `finally`, whatever is still sitting in
+ # the queue when the exception is raised is written *after* the
+ # traceback, so the client's stderr capture can read [traceback]
+ # then [the log lines that led up to it], inverted from causal
+ # order. (Only records still queued at raise time invert; anything
+ # the writer thread already drained is unaffected.) Draining here,
+ # in a `finally` around the server body, runs while the exception is
+ # still propagating *through this frame* - strictly before it
+ # reaches the top-level excepthook - so the log lines that explain
+ # the crash are flushed first, then the traceback.
+ #
+ # This is `logger.complete()`, deliberately not `logger.remove()`
+ # (verified in the installed loguru 0.7.3): `remove(None)` empties the
+ # global handler table, so any record logged after this frame - a
+ # caller catching the exception to log its own failure, or background
+ # threads winding down - is silently dropped by `_log()`, which returns
+ # early on `not core.handlers`. No caller does the former today: the
+ # `ldr-mcp` console script (`pyproject.toml`:
+ # `local_deep_research.mcp:run_server`) and `mcp/__main__.py`'s bare
+ # `run_server()` call both invoke it with nothing wrapping the call to
+ # catch and log a failure of its own. The property is kept as a general
+ # guarantee `complete()` has over `remove()`, not a fix for an existing
+ # caller. `complete()` drains the same queue (per enqueue handler it
+ # enqueues a `True` confirmation token FIFO, then waits on the writer's
+ # confirmation event) while *retaining* every handler, so those later
+ # records still reach the sink. Sink teardown stays with its owner:
+ # loguru's atexit-registered `logger.remove()`.
+ #
+ # Boundedness, precisely: the *enqueue* side is byte-bounded
+ # back-pressure (SimpleQueue.put() runs under the handler lock and
+ # stalls producers once the pipe buffer fills - the #4431 / #5804
+ # window), but the drain itself is not time-bounded. The confirmation
+ # wait in `Handler.complete_queue()` passes no timeout, so a sink that
+ # blocks indefinitely blocks this `finally` indefinitely;
+ # `Logger.complete()` additionally holds `_core.lock` across that wait,
+ # so a concurrent `add`/`remove`/`configure` would block for the same
+ # duration (ordinary logging would not - `_log()` never takes that
+ # lock), and `tasks_to_complete()` briefly takes `_queue_lock`, the
+ # same lock the writer thread holds around `sink.write()`. loguru
+ # offers no honest bound to add here, so we accept the same
+ # unbounded-in-time wait the writer thread already needs to drain its
+ # queue. One practical consequence: a shutdown Ctrl-C now lands
+ # *inside* this drain, so a second Ctrl-C raises KeyboardInterrupt out
+ # of the `finally`, abandoning the drain and replacing whatever
+ # exception was propagating.
+ #
+ # One case that leaves out: a *dead* writer thread. `complete_queue()`
+ # first does `self._queue.put(True)` - which can itself block on a full
+ # pipe before the wait even starts, while holding both
+ # `Logger.complete()`'s `_core.lock` and its own `_confirmation_lock` -
+ # then waits on `_confirmation_event` with no timeout and no check that
+ # the writer thread is still alive to ever call `.set()` on it. If that
+ # thread has already died, `logger.complete()` never returns.
+ # `Handler.stop()` does not share this gap: `Thread.join()` returns
+ # immediately once its target thread has already finished, so a dead
+ # writer thread hangs `complete_queue()`, not `stop()`. Not reachable
+ # with the shipped sink: it defaults to `sys.stderr`, which CPython
+ # pins to `errors='backslashreplace'`, and a broken pipe raises
+ # `OSError`, which `ErrorInterceptor.print()` (`_error_interceptor.py`)
+ # itself catches around its own `sys.stderr.write()` when it reports a
+ # sink failure - so the writer thread's loop keeps running. It becomes
+ # reachable only if `sys.stderr` itself, not just this function's
+ # `sink` argument, is ever pointed at a stream whose `write()` can
+ # raise something other than `OSError`, since `ErrorInterceptor` always
+ # reports to `sys.stderr` directly, independent of the handler's
+ # configured sink. `Logger.enable()` and `.disable()` also take
+ # `_core.lock` (`_logger.py`'s `_change_activation()`, ~line 1782), so
+ # the full list of calls this drain can block is
+ # `add`/`remove`/`configure`/`enable`/`disable`.
+ #
+ # Limit, not a regression: SIGTERM under its default disposition
+ # kills the process outright and never runs this `finally` (nor
+ # loguru's atexit hook), so anything still queued is lost - which is
+ # what `scripts/mcp_smoke_test.sh`'s `timeout 5` does. Only in-band
+ # exits (return, exception, KeyboardInterrupt) are covered.
+ logger.complete()
if __name__ == "__main__":
diff --git a/tests/mcp/test_mcp_protocol.py b/tests/mcp/test_mcp_protocol.py
index f4ecdff792..deb321af32 100644
--- a/tests/mcp/test_mcp_protocol.py
+++ b/tests/mcp/test_mcp_protocol.py
@@ -6,9 +6,11 @@ Tests for server setup, tool registration, and logging configuration.
import sys
import io
+from contextlib import contextmanager
from unittest.mock import patch
import pytest
+from loguru import logger
# Skip all tests if MCP is not available
try:
@@ -265,6 +267,279 @@ class TestMCPLogging:
mock_enable.assert_called_once_with("local_deep_research")
+class _ListSink:
+ """Real loguru sink collecting formatted records.
+
+ ``write`` runs only on loguru's single queue-writer thread and
+ ``lines`` is append-only, so reads after a ``logger.complete()``
+ barrier never race a write.
+ """
+
+ def __init__(self):
+ self.lines = []
+
+ def write(self, message):
+ self.lines.append(str(message))
+
+ def has(self, text):
+ return any(text in line for line in self.lines)
+
+
+@contextmanager
+def _restored_logger():
+ """Undo what ``configure_mcp_logging`` does to the process-wide logger.
+
+ Twin of ``tests/mcp/test_stderr_control_chars.py::_restored_logger``
+ (kept local rather than imported so this module has no import-mode
+ dependence). ``logger.configure(patcher=None)`` does not clear a
+ patcher: None means "leave unchanged", so the patcher would leak into
+ the rest of the pytest worker. The namespace activation and the
+ handlers are process-wide for the same reason, so all three are
+ snapshotted off ``logger._core`` and put back.
+ """
+ core = logger._core
+ saved = (
+ core.patcher,
+ core.enabled.copy(),
+ list(core.activation_list),
+ core.activation_none,
+ )
+ try:
+ yield
+ finally:
+ logger.remove()
+ (
+ core.patcher,
+ core.enabled,
+ core.activation_list,
+ core.activation_none,
+ ) = saved
+ # configure_mcp_logging removed loguru's default stderr handler.
+ logger.add(sys.stderr)
+
+
+@contextmanager
+def _run_server_rig(mcp_run_factory, migrate_side_effect=None):
+ """Run ``run_server()`` against a real enqueue=True sink.
+
+ Only the two things a pytest process must not do for real are
+ patched: launching the stdio server and the legacy-docstore sweep.
+ The sink is injected through ``configure_mcp_logging``'s own ``sink``
+ parameter, so the real ``logger.remove()``/``logger.add(enqueue=True)``
+ setup, loguru's real queue-writer thread, and the real drain barrier
+ in ``run_server()``'s finally all execute. ``logger.complete`` is
+ wrapped by a spy that delegates to the real barrier and records its
+ position in ``order`` — without the spy, "record absent from the
+ sink at return time" is a race the writer thread usually (but not
+ always) loses, which is exactly the nondeterminism the barrier
+ exists to remove.
+
+ ``migrate_side_effect`` is attached to the patched legacy-docstore
+ sweep, so a test can raise from the startup window that now sits
+ inside the same ``try``.
+
+ Yields ``(sink, order, mock_run, real_complete)``.
+ """
+ from local_deep_research.mcp.server import (
+ configure_mcp_logging as real_configure,
+ )
+
+ order = []
+ sink = _ListSink()
+ real_complete = logger.complete
+
+ def _spy_complete():
+ order.append("complete")
+ real_complete()
+
+ with _restored_logger():
+ with (
+ patch(
+ "local_deep_research.mcp.server.configure_mcp_logging",
+ side_effect=lambda: real_configure(sink=sink),
+ ),
+ patch(
+ "local_deep_research.mcp.server.mcp.run",
+ side_effect=mcp_run_factory(order),
+ ) as mock_run,
+ patch(
+ "local_deep_research.vector_stores.legacy_cleanup"
+ ".migrate_legacy_docstores",
+ side_effect=migrate_side_effect,
+ ),
+ patch.object(logger, "complete", side_effect=_spy_complete),
+ ):
+ yield sink, order, mock_run, real_complete
+
+
+class TestMCPLoggingDrainOnShutdown:
+ """Real-drain regressions for the #5804 follow-up: ``run_server()`` must
+ synchronously drain the enqueue=True stderr sink before it returns or
+ propagates, while *retaining* the handlers so records logged afterwards
+ (a caller handling the failure, background threads winding down) still
+ reach the sink.
+
+ Every test here fails if the ``finally``'s ``logger.complete()`` is
+ removed, moved ahead of ``mcp.run()``, or swapped back to
+ ``logger.remove()``: the first two corrupt ``order`` directly, and the
+ third corrupts it too - the spy this class installs on
+ ``logger.complete`` never fires under ``remove()``, so every test's
+ ``order`` assertion fails first, before any ``sink.has(...)`` check
+ runs. (``remove()`` would also drop a caller's post-shutdown records
+ from the sink - the property
+ ``test_normal_return_retains_handlers_for_caller_records`` is named for
+ - but the ``order`` assertion catches the swap before that ever gets
+ exercised.)
+ """
+
+ def test_normal_return_drains_queue_before_return(self):
+ """A clean client disconnect leaves every record enqueued before
+ return already written to the sink."""
+ from local_deep_research.mcp.server import run_server
+
+ def _stdio_disconnect(order):
+ def _run(**kwargs):
+ logger.error("server: stdio client disconnected")
+ order.append("mcp.run")
+
+ return _run
+
+ with _run_server_rig(_stdio_disconnect) as (sink, order, mock_run, _):
+ run_server()
+
+ # Asserted *inside* the rig: the only drain that has run at
+ # this point is the finally's barrier. (_restored_logger's
+ # own logger.remove() teardown, which would also drain, is
+ # still pending on the way out of the `with`.)
+ mock_run.assert_called_once_with(transport="stdio")
+ # Barrier ran after mcp.run() and before run_server() returned.
+ assert order == ["mcp.run", "complete"]
+ assert sink.has("Starting Local Deep Research MCP server")
+ assert sink.has("stdio client disconnected")
+
+ def test_normal_return_retains_handlers_for_caller_records(self):
+ """After run_server() returns, the installed handlers must still
+ accept records: a caller logging its own post-shutdown line
+ must reach the same sink once drained. ``logger.remove()`` in
+ the finally would silently drop it."""
+ from local_deep_research.mcp.server import run_server
+
+ def _stdio_disconnect(order):
+ def _run(**kwargs):
+ order.append("mcp.run")
+
+ return _run
+
+ with _run_server_rig(_stdio_disconnect) as (
+ sink,
+ order,
+ _,
+ real_complete,
+ ):
+ run_server()
+
+ # Caller-side record, logged after run_server() returned...
+ logger.error("caller: shutting down after server exit")
+ # ...still reaches the retained sink once drained. This
+ # explicit barrier is the only drain between the record and
+ # the asserts below; the rig's teardown has not run yet.
+ real_complete()
+
+ assert order == ["mcp.run", "complete"]
+ assert sink.has("Starting Local Deep Research MCP server")
+ assert sink.has("caller: shutting down after server exit")
+
+ def test_exception_path_drains_before_propagation_and_retains(self):
+ """``mcp.run()`` raising must drain inside the finally — while the
+ exception is still propagating through run_server()'s frame,
+ strictly before it reaches this caller (and, in a real
+ process, before CPython's excepthook prints the traceback to
+ stderr, keeping causal order: log lines first, traceback
+ after). Handlers must also survive for the caller's own error
+ record."""
+ from local_deep_research.mcp.server import run_server
+
+ class _BoomError(Exception):
+ pass
+
+ def _stdio_crash(order):
+ def _run(**kwargs):
+ logger.error("server: stdio transport failed")
+ order.append("mcp.run")
+ raise _BoomError("client pipe broke")
+
+ return _run
+
+ with _run_server_rig(_stdio_crash) as (
+ sink,
+ order,
+ _,
+ real_complete,
+ ):
+ with pytest.raises(_BoomError):
+ run_server()
+ order.append("caught")
+
+ # The crash-context record was already written when the
+ # exception reached this frame: the finally's barrier is the
+ # only drain that has run, the rig teardown's is still
+ # pending.
+ assert order == ["mcp.run", "complete", "caught"]
+ assert sink.has("server: stdio transport failed")
+
+ logger.error("caller: handling server failure")
+ real_complete()
+ assert sink.has("caller: handling server failure")
+
+ def test_baseexception_path_still_drains_in_finally(self):
+ """A BaseException (KeyboardInterrupt) from mcp.run() must both
+ drain the queue via the finally and still propagate out of
+ run_server() unchanged."""
+ from local_deep_research.mcp.server import run_server
+
+ def _interrupted(order):
+ def _run(**kwargs):
+ logger.error("server: interrupted while serving stdio")
+ order.append("mcp.run")
+ raise KeyboardInterrupt
+
+ return _run
+
+ with _run_server_rig(_interrupted) as (sink, order, _, _):
+ with pytest.raises(KeyboardInterrupt):
+ run_server()
+ order.append("caught")
+
+ # Inside the rig, so the finally's barrier is the only drain
+ # these asserts can be observing.
+ assert order == ["mcp.run", "complete", "caught"]
+ assert sink.has("server: interrupted while serving stdio")
+
+ def test_startup_window_is_inside_the_drain(self):
+ """The startup log line and the legacy-docstore sweep run inside
+ the same ``try``. The sweep only catches ``Exception``, so a
+ BaseException from it escapes — and must still hit the barrier,
+ or the queued startup lines land after the traceback."""
+ from local_deep_research.mcp.server import run_server
+
+ def _never_runs(order):
+ def _run(**kwargs): # pragma: no cover - must not be reached
+ order.append("mcp.run")
+
+ return _run
+
+ with _run_server_rig(
+ _never_runs, migrate_side_effect=KeyboardInterrupt
+ ) as (sink, order, mock_run, _):
+ with pytest.raises(KeyboardInterrupt):
+ run_server()
+ order.append("caught")
+
+ mock_run.assert_not_called()
+ assert order == ["complete", "caught"]
+ assert sink.has("Starting Local Deep Research MCP server")
+
+
class TestAvailableStrategies:
"""Tests for the get_available_strategies function.