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.

feat(embeddings): weakref.finalize safety net for OllamaEmbeddings (#4408)

LearningCircuit09b26e0381db
diff --git a/changelog.d/+ollama-embeddings-finalizer.bugfix.md b/changelog.d/+ollama-embeddings-finalizer.bugfix.md
new file mode 100644
index 0000000000..76c04ded6c
--- /dev/null
+++ b/changelog.d/+ollama-embeddings-finalizer.bugfix.md
@@ -0,0 +1,5 @@
+Added a `weakref.finalize`-based safety net inside the Ollama
+embeddings factory so that programmatic API callers and example
+scripts that construct `OllamaEmbeddings` directly — bypassing
+the managed RAG service lifecycle — still release their underlying
+httpx clients when the instance is garbage-collected.
diff --git a/src/local_deep_research/embeddings/providers/implementations/ollama.py b/src/local_deep_research/embeddings/providers/implementations/ollama.py
index 7deb4a92e4..a44fbe1d0d 100644
--- a/src/local_deep_research/embeddings/providers/implementations/ollama.py
+++ b/src/local_deep_research/embeddings/providers/implementations/ollama.py
@@ -1,5 +1,6 @@
"""Ollama embedding provider."""
+import weakref
from typing import Any, Dict, List, Optional
from langchain_ollama import OllamaEmbeddings
@@ -7,7 +8,10 @@ from langchain_core.embeddings import Embeddings
from loguru import logger
from ....config.thread_settings import get_setting_from_snapshot
-from ....utilities.llm_utils import get_ollama_base_url
+from ....utilities.llm_utils import (
+ _close_inner_ollama_clients,
+ get_ollama_base_url,
+)
from ..base import BaseEmbeddingProvider
from ....security import safe_get, safe_post
@@ -79,7 +83,32 @@ class OllamaEmbeddingsProvider(BaseEmbeddingProvider):
if num_ctx:
ollama_kwargs["num_ctx"] = int(num_ctx)
- return OllamaEmbeddings(**ollama_kwargs)
+ instance = OllamaEmbeddings(**ollama_kwargs)
+
+ # Safety net for callers that bypass LocalEmbeddingManager (e.g.,
+ # the programmatic-API examples in examples/api_usage, direct
+ # constructions in test fixtures). The manager-driven explicit
+ # close remains the load-bearing primary path; this finalizer
+ # only fires when the instance is GC'd without an explicit
+ # close. We pass the inner sync/async ``ollama.Client`` objects
+ # rather than ``instance`` itself — a strong reference back to
+ # the wrapping instance would defeat the finalizer's purpose by
+ # keeping the instance alive forever.
+ try:
+ weakref.finalize(
+ instance,
+ _close_inner_ollama_clients,
+ instance._client,
+ instance._async_client,
+ )
+ except AttributeError:
+ # Future langchain_ollama versions may reshape the private
+ # attrs; don't crash the factory if the introspection misses.
+ logger.debug(
+ "OllamaEmbeddings shape changed — finalizer not registered"
+ )
+
+ return instance
@classmethod
def is_available(
diff --git a/src/local_deep_research/utilities/llm_utils.py b/src/local_deep_research/utilities/llm_utils.py
index 324ed5b9ac..d8480d9066 100644
--- a/src/local_deep_research/utilities/llm_utils.py
+++ b/src/local_deep_research/utilities/llm_utils.py
@@ -178,6 +178,27 @@ def _close_base_llm(llm):
async_httpx._ldr_closed = True
+def _close_inner_ollama_clients(sync_client, async_client):
+ """Close just the inner sync/async ``ollama.Client`` pair.
+
+ A ``weakref.finalize`` callback that strong-refs the wrapping LLM or
+ embeddings instance would defeat its own purpose — the registry's
+ reference would keep the instance alive forever. Callers (the Ollama
+ provider factory's safety net) pass the inner clients directly
+ instead. This shim wraps them in a ``_close_base_llm``-shaped proxy
+ so we reuse the same idempotent sync+async close logic without
+ duplicating its asyncio/eventpoll handling.
+ """
+
+ class _Proxy:
+ pass
+
+ proxy = _Proxy()
+ proxy._client = sync_client
+ proxy._async_client = async_client
+ _close_base_llm(proxy)
+
+
def get_ollama_base_url(
settings_snapshot: Optional[Dict[str, Any]] = None,
) -> str:
diff --git a/tests/embeddings/test_ollama_embeddings.py b/tests/embeddings/test_ollama_embeddings.py
index e13b49988c..952b8f8dc3 100644
--- a/tests/embeddings/test_ollama_embeddings.py
+++ b/tests/embeddings/test_ollama_embeddings.py
@@ -380,6 +380,139 @@ class TestOllamaEmbeddingsCreate:
assert call_kwargs["num_ctx"] == 8192
+# ── weakref.finalize safety net ─────────────────────────────────────────
+
+
+class TestOllamaEmbeddingsFinalizerSafetyNet:
+ """The provider factory registers a ``weakref.finalize`` so callers
+ that bypass ``LocalEmbeddingManager`` (e.g. the programmatic-API
+ example scripts under ``examples/api_usage/``, direct test
+ constructions) still get cleanup at GC time.
+
+ The manager-driven explicit close path remains the load-bearing
+ primary cleanup; the finalizer is the last-resort safety net only.
+ """
+
+ def test_create_registers_finalizer_with_inner_clients(self):
+ """Provider passes the inner sync/async ``ollama.Client`` objects to
+ ``weakref.finalize`` — not the wrapping ``OllamaEmbeddings`` itself.
+ Passing the instance would defeat the finalizer's purpose by keeping
+ the instance alive through the registry's strong-ref."""
+ with patch(
+ f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {
+ "embeddings.ollama.model": "nomic-embed-text",
+ "embeddings.ollama.num_ctx": 8192,
+ }
+ )
+
+ with patch(f"{_OLLAMA_MODULE}.get_ollama_base_url") as mock_get_url:
+ mock_get_url.return_value = "http://localhost:11434"
+
+ # A simple object (not Mock) so the auto-attr behavior of
+ # Mock doesn't mask a missing _client/_async_client.
+ class _FakeOllamaEmbeddings:
+ def __init__(self):
+ self._client = object()
+ self._async_client = object()
+
+ fake_instance = _FakeOllamaEmbeddings()
+
+ with patch(
+ f"{_OLLAMA_MODULE}.OllamaEmbeddings",
+ return_value=fake_instance,
+ ):
+ with patch(
+ f"{_OLLAMA_MODULE}.weakref.finalize"
+ ) as mock_finalize:
+ result = OllamaEmbeddingsProvider.create_embeddings()
+
+ assert result is fake_instance
+ mock_finalize.assert_called_once()
+ args, _ = mock_finalize.call_args
+ # weakref.finalize(instance, callback, sync, async)
+ assert args[0] is fake_instance
+ assert args[2] is fake_instance._client
+ assert args[3] is fake_instance._async_client
+
+ def test_finalizer_does_not_crash_if_inner_attrs_missing(self):
+ """A future langchain_ollama version might rename _client /
+ _async_client. The factory must not crash in that case — the
+ explicit close path (or the upstream's own cleanup) remains
+ responsible for resource release.
+ """
+ with patch(
+ f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {
+ "embeddings.ollama.model": "nomic-embed-text",
+ "embeddings.ollama.num_ctx": 8192,
+ }
+ )
+
+ with patch(f"{_OLLAMA_MODULE}.get_ollama_base_url") as mock_get_url:
+ mock_get_url.return_value = "http://localhost:11434"
+
+ # Slotted class with no _client / _async_client → attribute
+ # access raises AttributeError, exercising the except branch.
+ class _ReshapedEmbeddings:
+ __slots__ = ()
+
+ with patch(
+ f"{_OLLAMA_MODULE}.OllamaEmbeddings",
+ return_value=_ReshapedEmbeddings(),
+ ):
+ # Must not raise.
+ result = OllamaEmbeddingsProvider.create_embeddings()
+ assert result is not None
+
+ def test_real_ollama_embeddings_finalizer_closes_clients_on_gc(self):
+ """End-to-end: construct a real ``langchain_ollama.OllamaEmbeddings``
+ via the provider, drop the reference, force GC, and verify both
+ inner httpx clients are closed. This is the canary for the
+ #3816-shaped FD leak on the embeddings side.
+ """
+ import gc
+ import weakref as _weakref
+
+ with patch(
+ f"{_OLLAMA_MODULE}.get_setting_from_snapshot"
+ ) as mock_get_setting:
+ mock_get_setting.side_effect = _make_settings_side_effect(
+ {
+ "embeddings.ollama.model": "nomic-embed-text",
+ "embeddings.ollama.num_ctx": 8192,
+ }
+ )
+
+ with patch(f"{_OLLAMA_MODULE}.get_ollama_base_url") as mock_get_url:
+ mock_get_url.return_value = "http://localhost:1"
+
+ # No OllamaEmbeddings patch — uses the real class.
+ instance = OllamaEmbeddingsProvider.create_embeddings()
+ sync_httpx = instance._client._client
+ async_httpx = instance._async_client._client
+ assert sync_httpx.is_closed is False
+ assert async_httpx.is_closed is False
+
+ instance_ref = _weakref.ref(instance)
+
+ # End the patches before dropping the ref so the finalizer
+ # runs against the real ``_close_inner_ollama_clients``.
+ del instance
+ gc.collect()
+
+ assert instance_ref() is None, (
+ "OllamaEmbeddings instance must be GC'able — the finalizer "
+ "must not strong-ref it"
+ )
+ assert sync_httpx.is_closed is True
+ assert async_httpx.is_closed is True
+
+
# ── _get_model_capabilities ─────────────────────────────────────────────