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(llm,docker): close ChatOllama async httpx client when called from a running loop + healthcheck timeout (#4047)

LearningCircuit04de8597ec1b
diff --git a/Dockerfile b/Dockerfile
index 81a7d56776..60f09259e3 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -312,8 +312,14 @@ RUN chmod +x /scripts/ollama_entrypoint.sh \
EXPOSE 5000
# Health check for container orchestration (Docker, Kubernetes, etc.)
+# The ``timeout=8`` on urlopen is load-bearing: without it, urllib hangs forever
+# on a slow/blocked server. Docker's --timeout=10s only SIGKILLs the ``sh -c``
+# wrapper; the python child gets reparented to PID 1 and continues holding a
+# TCP socket open against the app (one pidfd per hung child on PID 1). With
+# ``timeout=8`` the child returns/raises before Docker's wall, exits cleanly,
+# and gets reaped.
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
- CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:5000/api/v1/health')" || exit 1
+ CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:5000/api/v1/health', timeout=8)" || exit 1
STOPSIGNAL SIGINT
diff --git a/changelog.d/+close-base-llm-async-skip-fix.bugfix.md b/changelog.d/+close-base-llm-async-skip-fix.bugfix.md
new file mode 100644
index 0000000000..69144fef97
--- /dev/null
+++ b/changelog.d/+close-base-llm-async-skip-fix.bugfix.md
@@ -0,0 +1,3 @@
+Fix file-descriptor leak (`anon_inode:[eventpoll]`) in `_close_base_llm` when invoked while an asyncio loop is running. The previous code path skipped the async-client close in that case and documented that the "loop owner" would close instead — but no loop-owner cleanup actually exists in the project, so the inner `httpx.AsyncClient` (and its `epoll_create` FD) was silently abandoned. The same skip-path fires under the default `langgraph-agent` strategy because LangGraph dispatches some tool steps via asyncio internally, so close calls reached from a sync `finally` can still land inside a live loop. Cleanup now runs in a brief daemon thread that owns its own loop, so `asyncio.run(aclose())` works regardless of the caller's loop state; a bounded 5-second `join` keeps it from holding up shutdown if the Ollama server is unresponsive. This is the gap left by #3855's coverage of #3816 — same leak class, different code path.
+
+Also fixes a smaller secondary leak in the Docker `HEALTHCHECK`: `urllib.request.urlopen('http://localhost:5000/api/v1/health')` had no `timeout=` argument, so when the app slowed down (FD exhaustion or otherwise) Docker's 10s healthcheck timeout SIGKILL'd the `sh -c` wrapper but the python child got reparented to PID 1 and hung forever, each contributing a `pidfd` and a TCP socket against the app. Adding `timeout=8` lets the child return/raise before Docker's wall so it exits cleanly and gets reaped.
diff --git a/src/local_deep_research/utilities/llm_utils.py b/src/local_deep_research/utilities/llm_utils.py
index 54abf7f163..5de13f9217 100644
--- a/src/local_deep_research/utilities/llm_utils.py
+++ b/src/local_deep_research/utilities/llm_utils.py
@@ -64,10 +64,19 @@ def _close_base_llm(llm):
``a_inode [eventpoll]`` selectors bound to those async clients.
Idempotent via an ``_ldr_closed`` sentinel on the inner httpx clients.
- The async path uses ``asyncio.run()`` only when no event loop is
- currently running; when called from inside async code (e.g. an
- ``async def`` finalizer hypothetically) we skip and rely on the loop
- owner to close it.
+
+ The async path always runs ``aclose()`` to completion: when no event
+ loop is currently running we use ``asyncio.run()`` directly; when a
+ loop is running in the calling thread (e.g. ``_close_base_llm`` is
+ invoked inside async code or in a ``finally`` block reached through
+ LangGraph/LangChain async dispatch) we hand the close off to a brief
+ daemon thread whose own ``asyncio.run()`` is unaffected by the
+ caller's loop state. A prior implementation skipped the close in
+ that case and relied on the "loop owner" to close — but no loop
+ owner code actually does, so the ``httpx.AsyncClient`` and its
+ ``epoll_create`` FD were silently leaked. See the regression history
+ in ``docs/developing/resource-cleanup.md`` (this is the gap left by
+ #3855 when reaching for the in-async-context close).
"""
# If the llm is another wrapper with its own close(), delegate.
# NOTE: if a future ChatOllama version adds a public close() method,
@@ -112,18 +121,61 @@ def _close_base_llm(llm):
try:
asyncio.get_running_loop()
- # Inside a running loop: skip. Fire-and-forget tasks are
- # unreliable from a finally block, and we cannot block here.
- # The loop owner is responsible for closing the client.
- # Don't mark _ldr_closed — a later sync call should still
- # try to close.
except RuntimeError:
- # No running loop: spin a temporary one to await aclose.
+ # No running loop in this thread: spin a temporary one
+ # to await aclose() right here.
try:
asyncio.run(async_httpx.aclose())
except Exception:
logger.warning("Failed to close Ollama async httpx client")
+ # Mark closed unconditionally — matches the sync-side
+ # invariant: on a known-broken close we don't want to
+ # retry endlessly. The WARNING above is the signal.
async_httpx._ldr_closed = True
+ else:
+ # A loop is running in this thread. ``asyncio.run`` cannot
+ # be called here and fire-and-forget tasks scheduled on the
+ # caller's loop from a finally block are unreliable (the
+ # loop may exit before the task is awaited). Hand the close
+ # off to a brief daemon thread whose own loop is
+ # independent of ours; cap with a bounded ``join`` so a
+ # stuck server can't hold up shutdown.
+ import threading
+
+ def _close_in_thread() -> None:
+ try:
+ asyncio.run(async_httpx.aclose())
+ except Exception:
+ logger.warning(
+ "Failed to close Ollama async httpx client "
+ "in cleanup thread"
+ )
+
+ t = threading.Thread(
+ target=_close_in_thread,
+ daemon=True,
+ name="ldr-async-llm-close",
+ )
+ t.start()
+ t.join(timeout=5)
+ if t.is_alive():
+ # Don't set ``_ldr_closed`` — the cleanup thread is
+ # still running and the FD is therefore still open.
+ # Surface at WARNING so operators can correlate
+ # against rising eventpoll-FD counts. A subsequent
+ # call to _close_base_llm will retry the close.
+ logger.warning(
+ "Async httpx close exceeded 5s; abandoning to GC. "
+ "If this fires repeatedly, check Ollama server "
+ "responsiveness and look for rising "
+ "anon_inode:[eventpoll] FDs on the process."
+ )
+ else:
+ # Thread completed (with or without an inner
+ # exception). Mark closed to match the sync-side
+ # invariant; the inner exception, if any, was
+ # already logged from inside the thread.
+ async_httpx._ldr_closed = True
def get_ollama_base_url(
diff --git a/tests/utilities/test_close_base_llm.py b/tests/utilities/test_close_base_llm.py
index a1c5718c82..1d4188a9ee 100644
--- a/tests/utilities/test_close_base_llm.py
+++ b/tests/utilities/test_close_base_llm.py
@@ -121,7 +121,7 @@ class TestCloseBaseLLMSync:
class TestCloseBaseLLMAsync:
"""The async httpx client must be closed via ``asyncio.run`` when no loop
- is running; skipped (left for the loop owner) otherwise."""
+ is running, and via a brief daemon thread when one is."""
def test_closes_async_httpx_client_via_asyncio_run(self):
called = {"count": 0}
@@ -151,7 +151,37 @@ class TestCloseBaseLLMAsync:
# _ldr_closed sentinel prevents the second aclose.
assert called["count"] == 1
- def test_skips_async_close_inside_running_loop(self):
+ def test_closes_async_inside_running_loop_via_thread(self):
+ """Regression for the v1.6.10 leak. ``_close_base_llm`` used to
+ skip the async close when invoked inside a running asyncio loop
+ and rely on a non-existent "loop owner" cleanup — so the inner
+ ``httpx.AsyncClient`` (and its ``epoll_create`` FD) was silently
+ abandoned. The current implementation must run the close in a
+ brief daemon thread whose own ``asyncio.run`` is independent of
+ the caller's loop.
+ """
+ called = {"count": 0}
+
+ async def fake_aclose():
+ called["count"] += 1
+
+ llm = _make_fake_chat_ollama(async_aclose=fake_aclose)
+
+ async def driver():
+ _close_base_llm(llm)
+
+ asyncio.run(driver())
+
+ # aclose ran exactly once (via the cleanup thread, not skipped).
+ assert called["count"] == 1
+ # And _ldr_closed IS set on success — subsequent calls short-circuit.
+ async_httpx = llm._async_client._client
+ assert async_httpx._ldr_closed is True
+
+ def test_in_loop_close_is_idempotent(self):
+ """A close fired from inside a loop should set ``_ldr_closed`` just
+ like the no-loop path, so repeat calls don't re-spawn the cleanup
+ thread or re-run ``aclose``."""
called = {"count": 0}
async def fake_aclose():
@@ -160,16 +190,57 @@ class TestCloseBaseLLMAsync:
llm = _make_fake_chat_ollama(async_aclose=fake_aclose)
async def driver():
- # Inside a running loop, _close_base_llm must NOT call aclose
- # (would deadlock on asyncio.run nesting). The loop owner is
- # responsible for closing the client.
+ _close_base_llm(llm)
+ _close_base_llm(llm)
_close_base_llm(llm)
asyncio.run(driver())
- # aclose was skipped because we were inside a running loop.
- assert called["count"] == 0
- # And _ldr_closed is NOT set, so a later sync call still tries.
+ assert called["count"] == 1
+
+ def test_in_loop_close_timeout_does_not_mark_closed(self):
+ """If the cleanup thread is still alive after the 5-second join
+ (e.g. ``aclose`` is blocked on a stuck server), the sentinel must
+ NOT be set so a later call can retry — and the FD leak is at
+ least visible via WARNING log instead of silent drift.
+ """
+ import threading
+ from unittest.mock import patch
+
+ release = threading.Event()
+ aclose_started = threading.Event()
+
+ async def slow_aclose():
+ aclose_started.set()
+ # Block until released (or the test's shortened join fires).
+ await asyncio.get_event_loop().run_in_executor(
+ None, release.wait, 30
+ )
+
+ llm = _make_fake_chat_ollama(async_aclose=slow_aclose)
+
+ original_thread = threading.Thread
+
+ class _ShortJoinThread(original_thread):
+ def join(self, timeout=None):
+ # Tighten the production 5s wait to 200ms for the test
+ # so we don't actually sit here for 5 seconds.
+ return super().join(timeout=0.2)
+
+ try:
+ with patch("threading.Thread", _ShortJoinThread):
+
+ async def driver():
+ _close_base_llm(llm)
+
+ asyncio.run(driver())
+ finally:
+ release.set()
+
+ # ``aclose`` started but the join timed out before it could
+ # finish — sentinel must be unset so the FD is not silently
+ # leaked (a subsequent _close_base_llm call should retry).
+ assert aclose_started.is_set()
async_httpx = llm._async_client._client
assert not getattr(async_httpx, "_ldr_closed", False)
@@ -327,6 +398,49 @@ class TestCloseBaseLLMRealHttpxAsync:
f"before={before}, after={after}"
)
+ @pytest.mark.skipif(
+ sys.platform == "win32",
+ reason="Linux/macOS-specific FD semantics",
+ )
+ def test_no_fd_growth_when_closed_inside_running_loop(self):
+ """The user-facing regression. Before the fix, calling
+ ``_close_base_llm`` inside a running loop silently skipped the
+ async close — every iteration leaked ~1 ``epoll_create`` FD.
+ After the fix, the cleanup thread closes the client even when
+ a loop is running, so the FD count stays flat across iterations.
+ """
+
+ async def _close_from_inside_loop():
+ async_httpx = httpx.AsyncClient()
+ async_ollama = type("FakeAsyncOllama", (), {})()
+ async_ollama._client = async_httpx
+ type(async_ollama).__module__ = "ollama"
+ llm = Mock(spec=[])
+ llm._client = None
+ llm._async_client = async_ollama
+
+ # _close_base_llm is invoked while this loop is running —
+ # the exact scenario that leaked before the fix.
+ _close_base_llm(llm)
+
+ assert async_httpx.is_closed is True
+
+ gc.collect()
+ before = _open_fd_count()
+
+ for _ in range(5):
+ asyncio.run(_close_from_inside_loop())
+ gc.collect()
+
+ gc.collect()
+ after = _open_fd_count()
+
+ assert after - before <= 2, (
+ f"FD count climbed across in-loop close cycles "
+ f"(this is the #3816-shaped leak): "
+ f"before={before}, after={after}"
+ )
+
class TestCloseBaseLLMRealLangchain:
"""End-to-end regression coverage against the real langchain LLM classes