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.

41.0 KB
Raw Blame
"""
Tests for the LibraryRAGSearchEngine class.

Tests cover:
- Initialization and configuration
- Search functionality
- Preview generation
- Full content retrieval
"""

from unittest.mock import Mock, patch

from local_deep_research.constants import (
    DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,
    DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,
    DEFAULT_LOCAL_SEARCH_MODEL,
    DEFAULT_LOCAL_SEARCH_PROVIDER,
)

from local_deep_research.vector_stores.facade import SearchResult


class TestLibraryRAGSearchEngineInit:
    """Tests for LibraryRAGSearchEngine initialization."""

    def test_init_with_defaults(self):
        """Initialize with default values."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        with patch(
            "local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot",
            return_value=None,
        ):
            with patch(
                "local_deep_research.web_search_engines.engines.search_engine_library.get_server_url",
                return_value="http://localhost:5000",
            ):
                engine = LibraryRAGSearchEngine()

                assert engine.max_results == 10
                assert engine.username is None
                assert engine.is_local is True

    def test_init_with_settings_snapshot(self):
        """Initialize with settings snapshot."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        settings = {"_username": "testuser"}

        with patch(
            "local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot"
        ) as mock_get_setting:
            mock_get_setting.side_effect = lambda key, default=None, **kwargs: {
                "local_search_embedding_model": DEFAULT_LOCAL_SEARCH_MODEL,
                "local_search_embedding_provider": DEFAULT_LOCAL_SEARCH_PROVIDER,
                "local_search_chunk_size": DEFAULT_LOCAL_SEARCH_CHUNK_SIZE,
                "local_search_chunk_overlap": DEFAULT_LOCAL_SEARCH_CHUNK_OVERLAP,
            }.get(key, default)

            with patch(
                "local_deep_research.web_search_engines.engines.search_engine_library.get_server_url",
                return_value="http://localhost:5000",
            ):
                engine = LibraryRAGSearchEngine(settings_snapshot=settings)

                assert engine.username == "testuser"

    def test_init_with_custom_max_results(self):
        """Initialize with custom max_results."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        with patch(
            "local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot",
            return_value=None,
        ):
            with patch(
                "local_deep_research.web_search_engines.engines.search_engine_library.get_server_url",
                return_value="http://localhost:5000",
            ):
                engine = LibraryRAGSearchEngine(max_results=25)

                assert engine.max_results == 25

    def test_init_with_llm(self):
        """Initialize with LLM."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        mock_llm = Mock()

        with patch(
            "local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot",
            return_value=None,
        ):
            with patch(
                "local_deep_research.web_search_engines.engines.search_engine_library.get_server_url",
                return_value="http://localhost:5000",
            ):
                engine = LibraryRAGSearchEngine(llm=mock_llm)

                assert engine.llm is mock_llm


class TestSearch:
    """Tests for search method."""

    def test_search_without_username(self):
        """Search returns empty without username."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        with patch(
            "local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot",
            return_value=None,
        ):
            with patch(
                "local_deep_research.web_search_engines.engines.search_engine_library.get_server_url",
                return_value="http://localhost:5000",
            ):
                engine = LibraryRAGSearchEngine()
                results = engine.search("test query")

                assert results == []

    def test_search_no_collections(self):
        """Search handles no collections."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        settings = {"_username": "testuser"}

        with patch(
            "local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot",
            return_value=None,
        ):
            with patch(
                "local_deep_research.web_search_engines.engines.search_engine_library.get_server_url",
                return_value="http://localhost:5000",
            ):
                with patch(
                    "local_deep_research.web_search_engines.engines.search_engine_library.LibraryService"
                ) as mock_service:
                    mock_service.return_value.get_all_collections.return_value = []

                    engine = LibraryRAGSearchEngine(settings_snapshot=settings)
                    results = engine.search("test query")

                    assert results == []

    def test_search_returns_results(self):
        """Search returns formatted results."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        settings = {"_username": "testuser"}

        mock_doc = Mock()
        mock_doc.page_content = "This is the document content for testing."
        mock_doc.metadata = {
            "source_id": "123",
            "document_title": "Test Document",
            "chunk_index": 0,
        }

        with patch(
            "local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot",
            return_value=None,
        ):
            with patch(
                "local_deep_research.web_search_engines.engines.search_engine_library.get_server_url",
                return_value="http://localhost:5000",
            ):
                with patch(
                    "local_deep_research.web_search_engines.engines.search_engine_library.LibraryService"
                ) as mock_lib_service:
                    mock_lib_service.return_value.get_all_collections.return_value = [
                        {"id": 1, "name": "Test Collection"}
                    ]

                    with patch(
                        "local_deep_research.web_search_engines.engines.search_engine_library.get_user_db_session"
                    ) as mock_session:
                        mock_collection = Mock()
                        mock_collection.embedding_model = "all-MiniLM-L6-v2"
                        mock_collection.embedding_model_type = Mock(
                            value="sentence_transformers"
                        )
                        mock_collection.chunk_size = 1000
                        mock_collection.chunk_overlap = 200
                        mock_collection.splitter_type = None
                        mock_collection.text_separators = None
                        mock_collection.normalize_vectors = True
                        mock_collection.distance_metric = "l2"
                        mock_collection.index_type = "flat"

                        mock_session.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = mock_collection

                        with patch(
                            "local_deep_research.web_search_engines.engines.search_engine_library.LibraryRAGService"
                        ) as mock_rag_service:
                            # Set up mock RAG service instance for context manager
                            mock_rag_instance = Mock()
                            mock_rag_instance.has_indexed_documents.return_value = True
                            # Eligibility must use the cheap EXISTS helper; fail
                            # loudly if the full stats query is run again.
                            mock_rag_instance.get_rag_stats.side_effect = (
                                AssertionError(
                                    "library search must use "
                                    "has_indexed_documents, not get_rag_stats"
                                )
                            )
                            mock_rag_instance.search.return_value = [
                                SearchResult(
                                    chunk_id=1,
                                    text=mock_doc.page_content,
                                    distance=0.5,
                                    metric="l2",
                                    metadata=mock_doc.metadata,
                                    document_title=None,
                                    source_id=None,
                                    source_type=None,
                                )
                            ]
                            # Configure context manager behavior
                            mock_rag_service.return_value.__enter__.return_value = mock_rag_instance
                            mock_rag_service.return_value.__exit__.return_value = None

                            engine = LibraryRAGSearchEngine(
                                settings_snapshot=settings
                            )
                            results = engine.search("test query")

                            assert len(results) == 1
                            assert results[0]["title"] == "Test Document"
                            assert results[0]["source"] == "library"
                            assert results[0]["source_type"] == "library"
                            assert (
                                results[0]["metadata"]["document_chunk_id"] == 1
                            )
                            assert results[0]["url"] == (
                                "/library/document/123/chunks?document_chunk_id=1#chunk-0"
                            )

    def test_search_forwards_zero_overlap_and_splitter_settings(self):
        """Search forwards chunk_overlap=0, splitter_type, and text_separators to LibraryRAGService."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        settings = {"_username": "testuser"}

        with patch(
            "local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot",
            return_value=None,
        ):
            with patch(
                "local_deep_research.web_search_engines.engines.search_engine_library.get_server_url",
                return_value="http://localhost:5000",
            ):
                with patch(
                    "local_deep_research.web_search_engines.engines.search_engine_library.LibraryService"
                ) as mock_lib_service:
                    mock_lib_service.return_value.get_all_collections.return_value = [
                        {"id": "col_1", "name": "Zero Overlap Collection"}
                    ]

                    with patch(
                        "local_deep_research.web_search_engines.engines.search_engine_library.get_user_db_session"
                    ) as mock_session:
                        mock_collection = Mock()
                        mock_collection.embedding_model = "nomic-embed"
                        mock_collection.embedding_model_type = Mock(
                            value="openai"
                        )
                        mock_collection.chunk_size = 1000
                        mock_collection.chunk_overlap = 0
                        mock_collection.splitter_type = "token"
                        mock_collection.text_separators = [
                            "\n\n\n",
                            "\n\n",
                            "\n",
                        ]
                        mock_collection.distance_metric = "cosine"
                        mock_collection.normalize_vectors = True
                        mock_collection.index_type = "flat"

                        mock_session.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = mock_collection

                        with patch(
                            "local_deep_research.web_search_engines.engines.search_engine_library.LibraryRAGService"
                        ) as mock_rag_service:
                            mock_rag_instance = Mock()
                            mock_rag_instance.has_indexed_documents.return_value = True
                            mock_rag_instance.search.return_value = [
                                SearchResult(
                                    chunk_id=1,
                                    text="test text",
                                    distance=0.8,
                                    metric="cosine",
                                    metadata={"source_id": "doc1"},
                                    document_title="Title",
                                    source_id=None,
                                    source_type=None,
                                )
                            ]
                            mock_rag_service.return_value.__enter__.return_value = mock_rag_instance
                            mock_rag_service.return_value.__exit__.return_value = None

                            engine = LibraryRAGSearchEngine(
                                settings_snapshot=settings
                            )
                            results = engine.search("query")

                            assert len(results) == 1
                            call_kwargs = mock_rag_service.call_args.kwargs
                            assert call_kwargs["chunk_overlap"] == 0
                            assert call_kwargs["splitter_type"] == "token"
                            assert call_kwargs["text_separators"] == [
                                "\n\n\n",
                                "\n\n",
                                "\n",
                            ]
                            assert call_kwargs["distance_metric"] == "cosine"
                            assert call_kwargs["normalize_vectors"] is True
                            assert call_kwargs["index_type"] == "flat"

    def test_search_nullable_embedding_model_type_uses_default(self):
        """When collection.embedding_model_type is NULL, search falls back to default provider, not 'None'."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        settings = {
            "_username": "testuser",
            "local_search_embedding_provider": "sentence_transformers",
        }

        with patch(
            "local_deep_research.web_search_engines.engines.search_engine_library.LibraryService"
        ) as mock_lib_service:
            mock_lib_service.return_value.get_all_collections.return_value = [
                {"id": "col1", "name": "Collection 1"}
            ]

            with patch(
                "local_deep_research.web_search_engines.engines.search_engine_library.get_user_db_session"
            ) as mock_session:
                mock_collection = Mock()
                mock_collection.embedding_model = "all-MiniLM-L6-v2"
                mock_collection.embedding_model_type = None
                mock_collection.chunk_size = 1000
                mock_collection.chunk_overlap = 200
                mock_collection.splitter_type = None
                mock_collection.text_separators = None
                mock_collection.distance_metric = None
                mock_collection.normalize_vectors = None
                mock_collection.index_type = None

                mock_session.return_value.__enter__.return_value.query.return_value.filter_by.return_value.first.return_value = mock_collection

                with patch(
                    "local_deep_research.web_search_engines.engines.search_engine_library.LibraryRAGService"
                ) as mock_rag_service:
                    mock_rag_instance = Mock()
                    mock_rag_instance.has_indexed_documents.return_value = False
                    mock_rag_service.return_value.__enter__.return_value = (
                        mock_rag_instance
                    )
                    mock_rag_service.return_value.__exit__.return_value = None

                    engine = LibraryRAGSearchEngine(settings_snapshot=settings)
                    engine.search("test query")

                    call_kwargs = mock_rag_service.call_args.kwargs
                    assert (
                        call_kwargs["embedding_provider"]
                        == "sentence_transformers"
                    )
                    assert call_kwargs["embedding_provider"] != "None"

    def test_all_collections_fail_passes_collection_names(self):
        """When all collections fail, _raise_collections_failed receives collection names, not raw UUIDs."""
        import pytest
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        settings = {"_username": "testuser"}
        with patch(
            "local_deep_research.web_search_engines.engines.search_engine_library.LibraryService"
        ) as mock_lib:
            mock_lib.return_value.get_all_collections.return_value = [
                {"id": "uuid-1234", "name": "Important Docs"}
            ]
            with patch(
                "local_deep_research.web_search_engines.engines.search_engine_library.get_user_db_session",
                side_effect=RuntimeError("db error"),
            ):
                engine = LibraryRAGSearchEngine(settings_snapshot=settings)
                with pytest.raises(RuntimeError) as exc_info:
                    engine.search("test query")

                assert "Important Docs" in str(exc_info.value)

    def test_search_exception(self):
        """Search re-raises so failures are not mistaken for no results."""
        import pytest

        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        settings = {"_username": "testuser"}

        with patch(
            "local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot",
            return_value=None,
        ):
            with patch(
                "local_deep_research.web_search_engines.engines.search_engine_library.get_server_url",
                return_value="http://localhost:5000",
            ):
                with patch(
                    "local_deep_research.web_search_engines.engines.search_engine_library.LibraryService"
                ) as mock_service:
                    mock_service.return_value.get_all_collections.side_effect = Exception(
                        "Service error"
                    )

                    engine = LibraryRAGSearchEngine(settings_snapshot=settings)
                    with pytest.raises(Exception, match="Service error"):
                        engine.search("test query")


class TestGetPreviews:
    """Tests for _get_previews method."""

    def test_get_previews_delegates_to_search(self):
        """Get previews delegates to search method."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        with patch(
            "local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot",
            return_value=None,
        ):
            with patch(
                "local_deep_research.web_search_engines.engines.search_engine_library.get_server_url",
                return_value="http://localhost:5000",
            ):
                engine = LibraryRAGSearchEngine()

                with patch.object(
                    engine, "search", return_value=[{"title": "Test"}]
                ) as mock_search:
                    results = engine._get_previews("test query", limit=5)

                    mock_search.assert_called_once()
                    assert results == [{"title": "Test"}]

    def test_get_previews_uses_max_results_when_no_limit(self):
        """Without an explicit limit, the configured max_results is used.

        Regression test for #4428: the base class run() calls
        _get_previews(query) without a limit, so the configured
        search.max_results must be forwarded to search() instead of a
        hardcoded default.
        """
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        with patch(
            "local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot",
            return_value=None,
        ):
            with patch(
                "local_deep_research.web_search_engines.engines.search_engine_library.get_server_url",
                return_value="http://localhost:5000",
            ):
                engine = LibraryRAGSearchEngine(max_results=30)

                with patch.object(
                    engine, "search", return_value=[]
                ) as mock_search:
                    engine._get_previews("test query")

                    mock_search.assert_called_once_with(
                        "test query", 30, None, None
                    )


class TestGetFullContent:
    """Tests for _get_full_content method."""

    def test_get_full_content_uses_hit_chunk_id_across_index_versions(self):
        """A current-index hit must not hydrate an older same-ordinal chunk."""
        from contextlib import contextmanager

        from sqlalchemy import create_engine
        from sqlalchemy.orm import sessionmaker

        from local_deep_research.database.models.library import (
            Base,
            DocumentChunk,
            RAGIndex,
        )
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        db_engine = create_engine("sqlite:///:memory:")
        Base.metadata.create_all(
            db_engine, tables=[DocumentChunk.__table__, RAGIndex.__table__]
        )
        Session = sessionmaker(bind=db_engine)
        with Session() as session:
            for owner, text in (
                ("old-index", "old text"),
                ("new-index", "new text"),
            ):
                session.add(
                    DocumentChunk(
                        chunk_hash=owner,
                        source_type="document",
                        source_id="doc123",
                        collection_name="collection_coll-A",
                        chunk_text=text,
                        chunk_index=0,
                        start_char=0,
                        end_char=len(text),
                        word_count=2,
                        embedding_id=owner,
                        embedding_model="model",
                        embedding_model_type="openai",
                        vector_index_key=owner,
                    )
                )
                session.add(
                    RAGIndex(
                        collection_name="collection_coll-A",
                        embedding_model="model",
                        embedding_model_type="openai",
                        embedding_dimension=2,
                        index_path=f"/{owner}.faiss",
                        index_hash=owner,
                        chunk_size=500,
                        chunk_overlap=50,
                        is_current=owner == "new-index",
                    )
                )
            session.commit()
            current_id = (
                session.query(DocumentChunk.id)
                .filter_by(vector_index_key="new-index")
                .scalar()
            )
            old_id = (
                session.query(DocumentChunk.id)
                .filter_by(vector_index_key="old-index")
                .scalar()
            )

        @contextmanager
        def user_session(username):
            assert username == "testuser"
            with Session() as session:
                yield session

        engine = LibraryRAGSearchEngine(
            settings_snapshot={"_username": "testuser"}
        )
        item = {
            "source_id": "doc123",
            "metadata": {
                "chunk_index": 0,
                "collection_id": "coll-A",
                "document_chunk_id": current_id,
            },
            "snippet": "new text",
        }
        with patch(
            "local_deep_research.database.session_context.get_user_db_session",
            side_effect=user_session,
        ):
            result = engine._get_full_content([item])
            old_item = {
                **item,
                "metadata": {**item["metadata"], "document_chunk_id": old_id},
            }
            old_result = engine._get_full_content([old_item])
            rebuilt_item = {
                **item,
                "metadata": {
                    **item["metadata"],
                    "document_chunk_id": current_id + 1000,
                },
            }
            rebuilt_result = engine._get_full_content([rebuilt_item])
            legacy_item = {
                **item,
                "metadata": {
                    key: value
                    for key, value in item["metadata"].items()
                    if key != "document_chunk_id"
                },
            }
            legacy_result = engine._get_full_content([legacy_item])

        assert result[0]["full_content"] == "new text"
        assert old_result[0]["full_content"] == "old text"
        assert rebuilt_result[0]["full_content"] == "new text"
        assert legacy_result[0]["full_content"] == "new text"
        with Session() as session:
            session.query(DocumentChunk).delete()
            session.query(RAGIndex).update({"is_current": False})
            session.add(
                DocumentChunk(
                    chunk_hash="legacy-null",
                    source_type="document",
                    source_id="doc123",
                    collection_name="collection_coll-A",
                    chunk_text="legacy text",
                    chunk_index=0,
                    start_char=0,
                    end_char=11,
                    word_count=2,
                    embedding_id="legacy-null",
                    embedding_model="model",
                    embedding_model_type="openai",
                    vector_index_key=None,
                )
            )
            session.commit()
        with patch(
            "local_deep_research.database.session_context.get_user_db_session",
            side_effect=user_session,
        ):
            null_key_result = engine._get_full_content([legacy_item.copy()])
        assert null_key_result[0]["full_content"] == "legacy text"
        with Session() as session:
            session.query(DocumentChunk).update(
                {"vector_index_key": "old-index"}
            )
            session.commit()
        with patch(
            "local_deep_research.database.session_context.get_user_db_session",
            side_effect=user_session,
        ):
            retired_result = engine._get_full_content([legacy_item.copy()])
        assert retired_result[0]["full_content"] == "legacy text"
        db_engine.dispose()

    def test_get_full_content_retrieves_chunk_when_indexed(self):
        """When chunk metadata exists, chunk text is retrieved instead of full document."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        settings = {"_username": "testuser"}
        engine = LibraryRAGSearchEngine(settings_snapshot=settings)

        chunk = Mock()
        chunk.chunk_text = "Specific chunk text content"

        with patch(
            "local_deep_research.database.session_context.get_user_db_session"
        ) as mock_session_cm:
            mock_session = Mock()
            query_mock = Mock()
            mock_session.query.return_value = query_mock
            query_mock.filter.return_value = query_mock
            query_mock.order_by.return_value = query_mock
            query_mock.first.return_value = chunk
            mock_session_cm.return_value.__enter__.return_value = mock_session

            items = [
                {
                    "source_id": "doc123",
                    "metadata": {"chunk_index": 5, "document_id": "doc123"},
                    "content": "old snippet",
                }
            ]
            result = engine._get_full_content(items)

            assert len(result) == 1
            assert result[0]["content"] == "Specific chunk text content"
            assert result[0]["snippet"] == "Specific chunk text content"

    def test_get_full_content_publishes_whole_chunk_under_full_content(self):
        """The retrieved chunk reaches the key BaseCitationHandler reads.

        The handler takes result["full_content"] and falls back to the
        truncated result["snippet"], so a chunk longer than SNIPPET_LENGTH_LONG
        is only delivered whole if this key is populated.
        """
        from local_deep_research.constants import SNIPPET_LENGTH_LONG
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        settings = {"_username": "testuser"}
        engine = LibraryRAGSearchEngine(settings_snapshot=settings)

        chunk_text = "sentence. " * 120
        assert len(chunk_text) > SNIPPET_LENGTH_LONG

        chunk = Mock()
        chunk.chunk_text = chunk_text

        with patch(
            "local_deep_research.database.session_context.get_user_db_session"
        ) as mock_session_cm:
            mock_session = Mock()
            query_mock = Mock()
            mock_session.query.return_value = query_mock
            query_mock.filter.return_value = query_mock
            query_mock.order_by.return_value = query_mock
            query_mock.first.return_value = chunk
            mock_session_cm.return_value.__enter__.return_value = mock_session

            items = [
                {
                    "source_id": "doc123",
                    "metadata": {"chunk_index": 5, "document_id": "doc123"},
                    "content": "old snippet",
                }
            ]
            result = engine._get_full_content(items)

        assert result[0]["full_content"] == chunk_text
        assert len(result[0]["snippet"]) == SNIPPET_LENGTH_LONG + 3

        from local_deep_research.citation_handler import CitationHandler

        documents = CitationHandler(Mock())._create_documents(result)
        assert documents[0].page_content == chunk_text

    def test_get_full_content_falls_back_to_document_when_no_chunk_index(self):
        """When no chunk index exists in metadata, full document text is retrieved."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        settings = {"_username": "testuser"}
        engine = LibraryRAGSearchEngine(settings_snapshot=settings)

        doc = Mock()
        doc.text_content = "Full document body text"

        with patch(
            "local_deep_research.database.session_context.get_user_db_session"
        ) as mock_session_cm:
            mock_session = Mock()
            mock_session.query.return_value.filter_by.return_value.first.return_value = doc
            mock_session_cm.return_value.__enter__.return_value = mock_session

            items = [
                {
                    "source_id": "doc123",
                    "metadata": {"document_id": "doc123"},
                    "content": "old snippet",
                }
            ]
            result = engine._get_full_content(items)

            assert len(result) == 1
            assert result[0]["content"] == "Full document body text"
            assert result[0]["full_content"] == "Full document body text"

    def test_get_full_content_scopes_by_collection_id(self):
        """When collection_id is present in metadata, chunk query is scoped by collection_name.

        Pins the guarantee that a document indexed into two collections returns
        the chunk text for the requested collection rather than the other's.
        """
        from contextlib import contextmanager
        from sqlalchemy import create_engine
        from sqlalchemy.orm import sessionmaker
        from local_deep_research.database.models.library import (
            Base,
            DocumentChunk,
            RAGIndex,
        )
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        test_db_engine = create_engine("sqlite:///:memory:")
        Base.metadata.create_all(
            test_db_engine,
            tables=[DocumentChunk.__table__, RAGIndex.__table__],
        )
        Session = sessionmaker(bind=test_db_engine)
        db_session = Session()

        # Same (source_id, chunk_index) exists in two distinct collections
        db_session.add(
            DocumentChunk(
                chunk_hash="h1",
                source_type="document",
                source_id="doc123",
                collection_name="collection_coll-A",
                chunk_text="Collection A chunk text",
                chunk_index=5,
                start_char=0,
                end_char=23,
                word_count=4,
                embedding_id="e1",
                embedding_model="model",
                embedding_model_type="openai",
                vector_index_key="index-a",
            )
        )
        db_session.add(
            DocumentChunk(
                chunk_hash="h2",
                source_type="document",
                source_id="doc123",
                collection_name="collection_coll-B",
                chunk_text="Collection B chunk text",
                chunk_index=5,
                start_char=0,
                end_char=23,
                word_count=4,
                embedding_id="e2",
                embedding_model="model",
                embedding_model_type="openai",
                vector_index_key="index-b",
            )
        )
        for collection_name, index_hash in (
            ("collection_coll-A", "index-a"),
            ("collection_coll-B", "index-b"),
        ):
            db_session.add(
                RAGIndex(
                    collection_name=collection_name,
                    embedding_model="model",
                    embedding_model_type="openai",
                    embedding_dimension=2,
                    index_path=f"/{index_hash}.faiss",
                    index_hash=index_hash,
                    chunk_size=500,
                    chunk_overlap=50,
                    is_current=True,
                )
            )
        db_session.commit()

        @contextmanager
        def mock_get_user_db_session(username):
            yield db_session

        settings = {"_username": "testuser"}
        engine = LibraryRAGSearchEngine(settings_snapshot=settings)

        with patch(
            "local_deep_research.database.session_context.get_user_db_session",
            side_effect=mock_get_user_db_session,
        ):
            # Query specifying coll-B should resolve chunk from coll-B
            items_b = [
                {
                    "source_id": "doc123",
                    "metadata": {
                        "chunk_index": 5,
                        "document_id": "doc123",
                        "collection_id": "coll-B",
                    },
                    "content": "old snippet",
                }
            ]
            result_b = engine._get_full_content(items_b)
            assert len(result_b) == 1
            assert result_b[0]["content"] == "Collection B chunk text"

            # Query specifying coll-A should resolve chunk from coll-A
            items_a = [
                {
                    "source_id": "doc123",
                    "metadata": {
                        "chunk_index": 5,
                        "document_id": "doc123",
                        "collection_id": "coll-A",
                    },
                    "content": "old snippet",
                }
            ]
            result_a = engine._get_full_content(items_a)
            assert len(result_a) == 1
            assert result_a[0]["content"] == "Collection A chunk text"

    def test_get_full_content_reports_missing_chunk_without_fallback(self):
        """When chunk_index is targeted but chunk is missing, reports not found rather than full document."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        settings = {"_username": "testuser"}
        engine = LibraryRAGSearchEngine(settings_snapshot=settings)

        with patch(
            "local_deep_research.database.session_context.get_user_db_session"
        ) as mock_session_cm:
            mock_session = Mock()
            query_mock = Mock()
            mock_session.query.return_value = query_mock
            query_mock.filter.return_value = query_mock
            query_mock.order_by.return_value = query_mock
            query_mock.first.return_value = None
            query_mock.limit.return_value.all.return_value = []
            mock_session_cm.return_value.__enter__.return_value = mock_session

            items = [
                {
                    "source_id": "doc123",
                    "metadata": {"chunk_index": 5, "document_id": "doc123"},
                    "content": "old snippet",
                }
            ]
            result = engine._get_full_content(items)

            assert len(result) == 1
            assert (
                result[0]["content"] == "Chunk 5 not found for document doc123."
            )

    def test_get_full_content_returns_empty_when_chunk_text_empty(self):
        """When chunk exists but chunk_text is empty, returns empty content."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        settings = {"_username": "testuser"}
        engine = LibraryRAGSearchEngine(settings_snapshot=settings)

        chunk = Mock()
        chunk.chunk_text = ""

        with patch(
            "local_deep_research.database.session_context.get_user_db_session"
        ) as mock_session_cm:
            mock_session = Mock()
            query_mock = Mock()
            mock_session.query.return_value = query_mock
            query_mock.filter.return_value = query_mock
            query_mock.order_by.return_value = query_mock
            query_mock.first.return_value = chunk
            mock_session_cm.return_value.__enter__.return_value = mock_session

            items = [
                {
                    "source_id": "doc123",
                    "metadata": {"chunk_index": 5, "document_id": "doc123"},
                    "content": "old snippet",
                }
            ]
            result = engine._get_full_content(items)

            assert len(result) == 1
            assert result[0]["content"] == ""


class TestClose:
    """Tests for close method."""

    def test_close_does_nothing(self):
        """Close method runs without error."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        with patch(
            "local_deep_research.web_search_engines.engines.search_engine_library.get_setting_from_snapshot",
            return_value=None,
        ):
            with patch(
                "local_deep_research.web_search_engines.engines.search_engine_library.get_server_url",
                return_value="http://localhost:5000",
            ):
                engine = LibraryRAGSearchEngine()
                engine.close()  # Should not raise


class TestClassAttributes:
    """Tests for class attributes."""

    def test_is_local(self):
        """LibraryRAGSearchEngine is marked as local."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )

        assert LibraryRAGSearchEngine.is_local is True

    def test_egress_attributes(self):
        """LibraryRAGSearchEngine has egress sensitivity and exposure configured."""
        from local_deep_research.web_search_engines.engines.search_engine_library import (
            LibraryRAGSearchEngine,
        )
        from local_deep_research.web_search_engines.search_engine_base import (
            Exposure,
            Sensitivity,
        )

        assert (
            LibraryRAGSearchEngine.egress_sensitivity == Sensitivity.SENSITIVE
        )
        assert LibraryRAGSearchEngine.egress_exposure == Exposure.CONTAINED