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(rag-routes): close LibraryRAGService on every endpoint exit (#4407)

LearningCircuit9261c66bbc96
diff --git a/changelog.d/+rag-routes-lifecycle-hygiene.bugfix.md b/changelog.d/+rag-routes-lifecycle-hygiene.bugfix.md
new file mode 100644
index 0000000000..03bf57434c
--- /dev/null
+++ b/changelog.d/+rag-routes-lifecycle-hygiene.bugfix.md
@@ -0,0 +1,4 @@
+Library RAG service is now closed at the end of every HTTP request
+that uses it — including streaming endpoints. Together with the
+embedding-manager close path, this stops file-descriptor accumulation
+under sustained library indexing/search traffic.
diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.py
index 4ff6f0f569..f16ba98968 100644
--- a/src/local_deep_research/research_library/routes/rag_routes.py
+++ b/src/local_deep_research/research_library/routes/rag_routes.py
@@ -37,6 +37,7 @@ from ...security.decorators import require_json_body
from ...web.auth.decorators import login_required
from ...web.utils.request_helpers import parse_bool_arg
from ...utilities.db_utils import get_settings_manager
+from ...utilities.resource_utils import safe_close
from ..services.library_rag_service import LibraryRAGService
from ...settings.manager import SettingsManager
from ...security.file_upload_validator import FileUploadValidator
@@ -537,8 +538,8 @@ def get_index_info():
f"Getting RAG index info for collection_id: {collection_id}"
)
- rag_service = get_rag_service(collection_id)
- info = rag_service.get_current_index_info(collection_id)
+ with get_rag_service(collection_id) as rag_service:
+ info = rag_service.get_current_index_info(collection_id)
if info is None:
logger.info(
@@ -566,8 +567,8 @@ def get_rag_stats():
if not collection_id:
collection_id = get_default_library_id(session["username"])
- rag_service = get_rag_service(collection_id)
- stats = rag_service.get_rag_stats(collection_id)
+ with get_rag_service(collection_id) as rag_service:
+ stats = rag_service.get_rag_stats(collection_id)
return jsonify({"success": True, "stats": stats})
except Exception as e:
@@ -596,10 +597,10 @@ def index_document():
if not collection_id:
collection_id = get_default_library_id(session["username"])
- rag_service = get_rag_service(collection_id)
- result = rag_service.index_document(
- text_doc_id, collection_id, force_reindex
- )
+ with get_rag_service(collection_id) as rag_service:
+ result = rag_service.index_document(
+ text_doc_id, collection_id, force_reindex
+ )
if result["status"] == "error":
return jsonify(
@@ -632,10 +633,10 @@ def remove_document():
if not collection_id:
collection_id = get_default_library_id(session["username"])
- rag_service = get_rag_service(collection_id)
- result = rag_service.remove_document_from_rag(
- text_doc_id, collection_id
- )
+ with get_rag_service(collection_id) as rag_service:
+ result = rag_service.remove_document_from_rag(
+ text_doc_id, collection_id
+ )
if result["status"] == "error":
return jsonify(
@@ -662,10 +663,10 @@ def index_research():
{"success": False, "error": "research_id is required"}
), 400
- rag_service = get_rag_service()
- results = rag_service.index_research_documents(
- research_id, force_reindex
- )
+ with get_rag_service() as rag_service:
+ results = rag_service.index_research_documents(
+ research_id, force_reindex
+ )
return jsonify({"success": True, "results": results})
except Exception as e:
@@ -774,6 +775,14 @@ def index_all():
except Exception:
logger.exception("Error in bulk indexing")
yield f"data: {json.dumps({'type': 'error', 'error': 'An internal error occurred during indexing'})}\n\n"
+ finally:
+ # Generator ``finally`` runs at stream completion (or client
+ # disconnect via ``GeneratorExit``) — the safe place to release
+ # the RAG service's embedding-manager httpx clients. Closing at
+ # the outer route scope would tear it down before the streamed
+ # generator runs. ``safe_close`` swallows close-time errors so
+ # a broken Ollama doesn't mask the original generator outcome.
+ safe_close(rag_service, "rag_service (index-all SSE)")
return Response(
stream_with_context(generate()), mimetype="text/event-stream"
@@ -1126,6 +1135,10 @@ def index_local_library():
except Exception:
logger.exception("Error in local library indexing")
yield f"data: {json.dumps({'type': 'error', 'error': 'An internal error occurred during indexing'})}\n\n"
+ finally:
+ # See parallel comment in index-all generator above — generator
+ # ``finally`` is the safe close site for streamed RAG services.
+ safe_close(rag_service, "rag_service (index-local SSE)")
return Response(
stream_with_context(generate()), mimetype="text/event-stream"
@@ -2060,6 +2073,10 @@ def index_collection(collection_id):
except Exception:
logger.exception("Error in collection indexing")
yield f"data: {json.dumps({'type': 'error', 'error': 'An internal error occurred during indexing'})}\n\n"
+ finally:
+ # See parallel comment in index-all generator above — generator
+ # ``finally`` is the safe close site for streamed RAG services.
+ safe_close(rag_service, "rag_service (index-collection SSE)")
response = Response(
stream_with_context(generate()), mimetype="text/event-stream"
diff --git a/tests/research_library/routes/test_rag_routes_coverage.py b/tests/research_library/routes/test_rag_routes_coverage.py
index dbdec05feb..a97724546f 100644
--- a/tests/research_library/routes/test_rag_routes_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_coverage.py
@@ -8,7 +8,7 @@ precise assertions on response bodies, status codes, and mock interactions.
from contextlib import contextmanager
from datetime import datetime, UTC
from io import BytesIO
-from unittest.mock import Mock, patch
+from unittest.mock import MagicMock, Mock, patch
import pytest
from flask import Flask, jsonify
@@ -557,7 +557,11 @@ class TestGetAvailableModels:
class TestGetIndexInfo:
def test_with_index(self, app):
- mock_rag = Mock()
+ mock_rag = MagicMock()
+ # rag_routes now uses ``with get_rag_service(...) as rag_service:``
+ # MagicMock's default __enter__ returns a child mock, so route body
+ # would see a different object. Pin __enter__ to self.
+ mock_rag.__enter__.return_value = mock_rag
mock_rag.get_current_index_info.return_value = {"total_chunks": 10}
with _auth_client(
@@ -577,7 +581,11 @@ class TestGetIndexInfo:
assert data["info"]["total_chunks"] == 10
def test_no_index(self, app):
- mock_rag = Mock()
+ mock_rag = MagicMock()
+ # rag_routes now uses ``with get_rag_service(...) as rag_service:``
+ # MagicMock's default __enter__ returns a child mock, so route body
+ # would see a different object. Pin __enter__ to self.
+ mock_rag.__enter__.return_value = mock_rag
mock_rag.get_current_index_info.return_value = None
with _auth_client(
@@ -596,7 +604,11 @@ class TestGetIndexInfo:
assert data["info"] is None
def test_with_collection_id(self, app):
- mock_rag = Mock()
+ mock_rag = MagicMock()
+ # rag_routes now uses ``with get_rag_service(...) as rag_service:``
+ # MagicMock's default __enter__ returns a child mock, so route body
+ # would see a different object. Pin __enter__ to self.
+ mock_rag.__enter__.return_value = mock_rag
mock_rag.get_current_index_info.return_value = {"total_chunks": 5}
with _auth_client(
@@ -618,7 +630,11 @@ class TestGetIndexInfo:
class TestGetRagStats:
def test_success(self, app):
- mock_rag = Mock()
+ mock_rag = MagicMock()
+ # rag_routes now uses ``with get_rag_service(...) as rag_service:``
+ # MagicMock's default __enter__ returns a child mock, so route body
+ # would see a different object. Pin __enter__ to self.
+ mock_rag.__enter__.return_value = mock_rag
mock_rag.get_rag_stats.return_value = {"indexed": 10, "total": 20}
with _auth_client(
@@ -661,7 +677,11 @@ class TestIndexDocument:
assert resp.status_code == 400
def test_success(self, app):
- mock_rag = Mock()
+ mock_rag = MagicMock()
+ # rag_routes now uses ``with get_rag_service(...) as rag_service:``
+ # MagicMock's default __enter__ returns a child mock, so route body
+ # would see a different object. Pin __enter__ to self.
+ mock_rag.__enter__.return_value = mock_rag
mock_rag.index_document.return_value = {
"status": "success",
"chunks": 5,
@@ -686,7 +706,11 @@ class TestIndexDocument:
assert data["success"] is True
def test_error_result(self, app):
- mock_rag = Mock()
+ mock_rag = MagicMock()
+ # rag_routes now uses ``with get_rag_service(...) as rag_service:``
+ # MagicMock's default __enter__ returns a child mock, so route body
+ # would see a different object. Pin __enter__ to self.
+ mock_rag.__enter__.return_value = mock_rag
mock_rag.index_document.return_value = {
"status": "error",
"error": "No text",
@@ -709,7 +733,11 @@ class TestIndexDocument:
assert resp.status_code == 400
def test_with_collection_id(self, app):
- mock_rag = Mock()
+ mock_rag = MagicMock()
+ # rag_routes now uses ``with get_rag_service(...) as rag_service:``
+ # MagicMock's default __enter__ returns a child mock, so route body
+ # would see a different object. Pin __enter__ to self.
+ mock_rag.__enter__.return_value = mock_rag
mock_rag.index_document.return_value = {"status": "success"}
with _auth_client(
@@ -745,7 +773,11 @@ class TestRemoveDocument:
assert resp.status_code == 400
def test_success(self, app):
- mock_rag = Mock()
+ mock_rag = MagicMock()
+ # rag_routes now uses ``with get_rag_service(...) as rag_service:``
+ # MagicMock's default __enter__ returns a child mock, so route body
+ # would see a different object. Pin __enter__ to self.
+ mock_rag.__enter__.return_value = mock_rag
mock_rag.remove_document_from_rag.return_value = {"status": "success"}
with _auth_client(
@@ -767,7 +799,11 @@ class TestRemoveDocument:
assert data["success"] is True
def test_error_result(self, app):
- mock_rag = Mock()
+ mock_rag = MagicMock()
+ # rag_routes now uses ``with get_rag_service(...) as rag_service:``
+ # MagicMock's default __enter__ returns a child mock, so route body
+ # would see a different object. Pin __enter__ to self.
+ mock_rag.__enter__.return_value = mock_rag
mock_rag.remove_document_from_rag.return_value = {
"status": "error",
"error": "not found",
@@ -802,7 +838,11 @@ class TestIndexResearch:
assert resp.status_code == 400
def test_success(self, app):
- mock_rag = Mock()
+ mock_rag = MagicMock()
+ # rag_routes now uses ``with get_rag_service(...) as rag_service:``
+ # MagicMock's default __enter__ returns a child mock, so route body
+ # would see a different object. Pin __enter__ to self.
+ mock_rag.__enter__.return_value = mock_rag
mock_rag.index_research_documents.return_value = [{"status": "success"}]
with _auth_client(
diff --git a/tests/research_library/routes/test_rag_routes_deep_coverage.py b/tests/research_library/routes/test_rag_routes_deep_coverage.py
index de6715b8c0..00cef20f46 100644
--- a/tests/research_library/routes/test_rag_routes_deep_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_deep_coverage.py
@@ -27,7 +27,7 @@ Covers:
import uuid
from contextlib import contextmanager
from io import BytesIO
-from unittest.mock import Mock, patch
+from unittest.mock import MagicMock, Mock, patch
import pytest
from flask import Flask, jsonify
@@ -1228,7 +1228,11 @@ class TestGetRagServiceTextSeparatorsList:
def test_text_separators_already_list(self, app):
"""When text_separators setting is already a list, no JSON parsing needed."""
- mock_service = Mock()
+ # MagicMock so the service supports `with get_rag_service(...) as svc:`
+ # (production route now context-manages — see rag_routes lifecycle PR).
+ # Pin __enter__ to self so the route body sees this mock, not a child.
+ mock_service = MagicMock()
+ mock_service.__enter__.return_value = mock_service
mock_service.get_rag_stats.return_value = {}
rag_patch = patch(
@@ -1439,7 +1443,11 @@ class TestGetRagServiceNoCollection:
q = _build_mock_query(first_result=None) # Collection not found
db_session.query = Mock(return_value=q)
- mock_service = Mock()
+ # MagicMock so the service supports `with get_rag_service(...) as svc:`
+ # (production route now context-manages — see rag_routes lifecycle PR).
+ # Pin __enter__ to self so the route body sees this mock, not a child.
+ mock_service = MagicMock()
+ mock_service.__enter__.return_value = mock_service
mock_service.get_rag_stats.return_value = {}
with _auth_client(
diff --git a/tests/research_library/routes/test_rag_routes_gaps_coverage.py b/tests/research_library/routes/test_rag_routes_gaps_coverage.py
index d8abedeb6b..d7bc364eb5 100644
--- a/tests/research_library/routes/test_rag_routes_gaps_coverage.py
+++ b/tests/research_library/routes/test_rag_routes_gaps_coverage.py
@@ -730,3 +730,126 @@ class TestIndexCollection:
assert "text/event-stream" in resp.content_type
assert resp.headers.get("Cache-Control") == "no-cache, no-transform"
assert resp.headers.get("X-Accel-Buffering") == "no"
+
+
+class TestRagServiceCloseLifecycle:
+ """Regression coverage for the RAG-service close-on-exit guarantee.
+
+ Without these tests, the existing route fixtures only assert status
+ codes — they accept ``Mock().close()`` silently and would not detect
+ a regression that drops the ``finally: safe_close(...)`` block from
+ an SSE generator, or the ``with get_rag_service(...) as ...``
+ wrapper from a synchronous route. The leak the wider PR series
+ closes (#3816-shaped FD ramp on the embeddings side) lives behind
+ exactly these close calls — so they need explicit assertions.
+
+ Each test asserts that ``close()`` (or its ``__exit__`` cousin)
+ fires exactly once when the route handler completes — happy path
+ for sync routes, stream-drained path for SSE routes.
+ """
+
+ def _collect_sse_events(self, response):
+ """Parse SSE events from streaming response."""
+ events = []
+ for line in response.data.decode().split("\n"):
+ if line.startswith("data: "):
+ events.append(json.loads(line[6:]))
+ return events
+
+ def test_with_wrap_endpoint_calls_exit_on_completion(self, app):
+ """Synchronous ``with get_rag_service(...) as rag_service:`` routes
+ must invoke the service's ``__exit__`` — the entry-point for
+ ``LibraryRAGService.close()`` which in turn closes the embedding
+ manager's httpx clients.
+ """
+ # MagicMock so the route's `with` block works; pin __enter__ to self
+ # so the body sees this mock, then assert __exit__ fires.
+ mock_rag = MagicMock()
+ mock_rag.__enter__.return_value = mock_rag
+ mock_rag.get_current_index_info.return_value = {"total_chunks": 0}
+
+ with _auth_client(
+ app,
+ extra_patches=[
+ patch(f"{_ROUTES}.get_rag_service", return_value=mock_rag),
+ patch(
+ "local_deep_research.database.library_init.get_default_library_id",
+ return_value="default-lib",
+ ),
+ ],
+ ) as (client, ctx):
+ resp = client.get("/library/api/rag/info")
+ assert resp.status_code == 200
+
+ mock_rag.__exit__.assert_called_once()
+
+ def test_sse_index_collection_calls_close_at_stream_end(self, app):
+ """``index_collection`` is one of three SSE routes that construct
+ ``rag_service`` at request scope but use it inside a streamed
+ generator. The fix moves the close into the generator's
+ ``finally:`` so it fires at stream completion (or client
+ disconnect via ``GeneratorExit``) — wrapping the construction
+ in a ``with`` at request scope would tear the service down
+ before ``stream_with_context`` iterates the generator.
+ """
+ db_session = _make_db_session()
+ db_session.query.return_value = _build_mock_query(first_result=None)
+
+ mock_rag = Mock() # bare Mock — its close() is auto-attr.
+
+ with _auth_client(
+ app,
+ mock_db_session=db_session,
+ extra_patches=[
+ patch(f"{_ROUTES}.get_rag_service", return_value=mock_rag),
+ patch(
+ "local_deep_research.database.session_passwords.session_password_store",
+ Mock(get_session_password=Mock(return_value=None)),
+ ),
+ ],
+ ) as (client, ctx):
+ resp = client.get("/library/api/collections/coll-1/index")
+ # Drain the stream so the generator runs to completion and
+ # its ``finally:`` fires. (test_client buffers in memory; the
+ # decode in _collect_sse_events forces iteration.)
+ self._collect_sse_events(resp)
+
+ # Exactly one close call — the generator's ``finally`` ran
+ # without the outer route closing it prematurely.
+ mock_rag.close.assert_called_once()
+
+ def test_sse_index_collection_calls_close_even_on_generator_exception(
+ self, app
+ ):
+ """If the SSE generator raises mid-stream, the ``finally:`` block
+ must still close ``rag_service``. Mock the DB query to raise; the
+ generator's outer ``except`` catches the error, yields an SSE
+ error event, and the ``finally`` still runs.
+ """
+ db_session = _make_db_session()
+ db_session.query.side_effect = RuntimeError(
+ "simulated DB failure inside generator"
+ )
+
+ mock_rag = Mock()
+
+ with _auth_client(
+ app,
+ mock_db_session=db_session,
+ extra_patches=[
+ patch(f"{_ROUTES}.get_rag_service", return_value=mock_rag),
+ patch(
+ "local_deep_research.database.session_passwords.session_password_store",
+ Mock(get_session_password=Mock(return_value=None)),
+ ),
+ ],
+ ) as (client, ctx):
+ resp = client.get("/library/api/collections/coll-1/index")
+ events = self._collect_sse_events(resp)
+
+ # The generator's except branch should have surfaced an
+ # error event before finally fired.
+ assert any(e.get("type") == "error" for e in events)
+
+ # And close still ran despite the exception.
+ mock_rag.close.assert_called_once()