~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.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(search): find uploaded documents by their listed filename (#7054)
LearningCircuit5f3af4574080
diff --git a/changelog.d/5835.bugfix.md b/changelog.d/5835.bugfix.mdnew file mode 100644index 0000000000..5558e60431--- /dev/null+++ b/changelog.d/5835.bugfix.md@@ -0,0 +1,10 @@+The Search page ("Search everything") now finds an uploaded document by+the filename it lists the document under, in its Text Only and AI Hybrid+modes. Its keyword search matched only titles and text, and an upload has+no title, so the name shown for it matched only when the document's text+happened to contain it. The JSON endpoint `GET /library/api/documents?search=`,+which no page calls, now matches that filename too. Neither matches a+stored filename that is not the listed name, such as a titled document's+(every Zotero item has a title). The Library page's own search box, which+filters the cards in the browser, is unchanged. Matching ignores case for+ASCII letters only.diff --git a/src/local_deep_research/research_library/services/library_service.py b/src/local_deep_research/research_library/services/library_service.pyindex b4734a52b7..741ee4d7f0 100644--- a/src/local_deep_research/research_library/services/library_service.py+++ b/src/local_deep_research/research_library/services/library_service.py@@ -13,7 +13,7 @@ from typing import Dict, List, Optionalfrom urllib.parse import urlparsefrom loguru import logger-from sqlalchemy import and_, or_, func, case+from sqlalchemy import and_, or_, func, case, selectfrom sqlalchemy.orm import aliased, deferfrom ...constants import FILE_PATH_SENTINELS, FILE_PATH_TEXT_ONLY@@ -149,6 +149,32 @@ def _counts_as_downloaded():)+def _sql_falsy(column):+ """SQL for Python's ``not value`` on a nullable text column: NULL or ''."""+ return or_(column.is_(None), column == "")+++def _fallback_resource_id(document_model):+ """Select one stable resource when no primary resource exists."""+ return (+ select(func.min(ResearchResource.id))+ .where(ResearchResource.document_id == document_model.id)+ .correlate(document_model)+ .scalar_subquery()+ )+++def _display_resource_id(document_model):+ """Match the listing's primary-FK preference and stable fallback."""+ primary_id = (+ select(ResearchResource.id)+ .where(ResearchResource.id == document_model.resource_id)+ .correlate(document_model)+ .scalar_subquery()+ )+ return func.coalesce(primary_id, _fallback_resource_id(document_model))++class LibraryService:"""Service for managing and querying the document library."""@@ -360,11 +386,49 @@ class LibraryService:return query.filter(model_class.original_url.like(pattern, escape="\\"))def _apply_search_filter(self, query, model_class, search_query: str):- """Apply search filter to query for Document."""+ """Apply the search filter to a Document query.++ Matches the document's title, authors and DOI, the title of a linked+ research resource, and the stored filename where that filename is+ the name the document is listed under. ``ilike`` folds case for+ ASCII letters only: on SQLite it is ``lower(...) LIKE lower(...)``.++ ``get_documents`` lists a document as ``document_title``, which is+ ``doc.title or (resource.title if resource else doc.filename)``, and+ the Library card falls back to ``file_name`` when that is empty;+ ``file_name`` is the filename unless the document has a real file+ path. So the filename is the listed name only when the document has+ no title and either no linked resource, or a linked resource with no+ title and no real file path. Any other stored filename is not+ searched: a titled document (every Zotero item) is listed under its+ title, and a document listed under a resource title is found by that+ title.++ The caller must outer-join ``ResearchResource`` (``get_documents``+ does).+ """search_pattern = f"%{_escape_like(search_query)}%"+ listed_under_filename = and_(+ _sql_falsy(model_class.title),+ or_(+ ResearchResource.id.is_(None),+ and_(+ ResearchResource.id == _display_resource_id(model_class),+ _sql_falsy(ResearchResource.title),+ or_(+ _sql_falsy(model_class.file_path),+ model_class.file_path.in_(FILE_PATH_SENTINELS),+ ),+ ),+ ),+ )return query.filter(or_(model_class.title.ilike(search_pattern, escape="\\"),+ and_(+ listed_under_filename,+ model_class.filename.ilike(search_pattern, escape="\\"),+ ),model_class.authors.ilike(search_pattern, escape="\\"),model_class.doi.ilike(search_pattern, escape="\\"),ResearchResource.title.ilike(search_pattern, escape="\\"),@@ -570,7 +634,8 @@ class LibraryService:# the OR-condition join that can fan out to multiple rows:# - ResourceByFK: matched via Document.resource_id (primary FK)# - ResourceByDoc: matched via ResearchResource.document_id- # We prefer ResourceByFK; fall back to ResourceByDoc in Python.+ # Prefer ResourceByFK; otherwise use the earliest back-linked+ # resource, matching the filename search's display selection.ResourceByFK = aliased(ResearchResource)ResourceByDoc = aliased(ResearchResource)@@ -593,7 +658,7 @@ class LibraryService:).outerjoin(ResourceByDoc,- ResourceByDoc.document_id == Document.id,+ ResourceByDoc.id == _fallback_resource_id(Document),).outerjoin(ResearchHistory,@@ -624,9 +689,7 @@ class LibraryService:.all()}- # Process results — deduplicate by doc.id since the ResourceByDoc- # outer join can fan out when multiple ResearchResource rows- # point to the same document via document_id.+ # Process results, defensively deduplicating by doc.id.## Resolve one settings manager for the whole page (lazily, on the# first document that actually needs a path resolved) instead ofdiff --git a/src/local_deep_research/web/routers/unified_search.py b/src/local_deep_research/web/routers/unified_search.pyindex 18365ff10b..e377afafd0 100644--- a/src/local_deep_research/web/routers/unified_search.py+++ b/src/local_deep_research/web/routers/unified_search.py@@ -5,7 +5,7 @@ One search surface across every entity stored as a ``Document`` row(notes, research reports, library downloads, user uploads):* GET /library/search/ — the Search page-* GET /library/search/api/keyword — ILIKE over title + text_content+* GET /library/search/api/keyword — ILIKE over the listed name + text_content* GET /library/search/api/semantic — FAISS search over the systemcollections (default_library, research_history, notes)@@ -175,7 +175,12 @@ def unified_search_page(def keyword_search(request: Request, username: Annotated[str, Depends(require_auth)]):- """Keyword leg: ILIKE over Document.title + text_content, ALL source types.+ """Keyword leg: ILIKE over the listed name + text_content, ALL source types.++ The listed name is ``title or filename`` (``display_title`` below), so+ the filename is searched only when the title is NULL or empty, as for+ an uploaded document. A titled document is not matched by its stored+ filename. ILIKE folds case for ASCII letters only.Query params:q: Search query (required, capped at MAX_SEARCH_LEN)@@ -189,7 +194,7 @@ def keyword_search(if error:return error- from sqlalchemy import case, func, or_+ from sqlalchemy import and_, case, func, or_from ...database.models.library import Document, SourceTypefrom ...database.session_context import get_user_db_session@@ -200,7 +205,7 @@ def keyword_search(# first 300 chars usually don't contain the matched text at all,# so the card gave no clue why the document matched. instr() takes# the raw query (wildcard escaping only applies to LIKE), folded- # with lower() on both sides exactly like ilike; 0 = title-only+ # with lower() on both sides exactly like ilike; 0 = name-only# match → head preview. PREVIEW_CONTEXT chars of lead-in keep the# match readable in situ.match_pos = func.instr(func.lower(Document.text_content), func.lower(q))@@ -233,6 +238,16 @@ def keyword_search(Document.status == "completed",or_(Document.title.ilike(pattern, escape="\\"),+ # Results are listed as ``title or filename``, so+ # the filename is searched exactly where it is+ # the listed name.+ and_(+ or_(+ Document.title.is_(None),+ Document.title == "",+ ),+ Document.filename.ilike(pattern, escape="\\"),+ ),Document.text_content.ilike(pattern, escape="\\"),),)diff --git a/src/local_deep_research/web/static/js/pages/unified_search.js b/src/local_deep_research/web/static/js/pages/unified_search.jsindex e2ef7c9ef2..5fce0aa72b 100644--- a/src/local_deep_research/web/static/js/pages/unified_search.js+++ b/src/local_deep_research/web/static/js/pages/unified_search.js@@ -366,7 +366,7 @@ async function runUnifiedSearch() {// Mode implementations (registry `run` functions)// ============================================================================-/** Text Only: the keyword endpoint (ILIKE over title + content). */+/** Text Only: the keyword endpoint (ILIKE over the listed name + content). */async function runKeywordMode(query, { signal } = {}) {const params = new URLSearchParams();params.append('q', query);diff --git a/tests/research_library/services/test_library_service.py b/tests/research_library/services/test_library_service.pyindex 7499fb3b10..0ad60e6ddc 100644--- a/tests/research_library/services/test_library_service.py+++ b/tests/research_library/services/test_library_service.py@@ -4,6 +4,8 @@ Tests for LibraryService.from unittest.mock import Mock, patch, MagicMock+import pytest+class TestLibraryServiceUrlDetection:"""Tests for URL detection methods."""@@ -604,51 +606,25 @@ class TestLibraryServiceApplyDomainFilter:class TestLibraryServiceApplySearchFilter:"""Tests for _apply_search_filter method."""- def test_apply_search_filter_query(self, mocker):- """Applies search query filter correctly."""+ def test_apply_search_filter_query(self):+ """Build a real SQL expression with bound search values."""+ from local_deep_research.database.models.library import Documentfrom local_deep_research.research_library.services.library_service import (LibraryService,)- mock_query = Mock()- mock_query.filter.return_value = mock_query-- # Create a proper mock model class with required attributes- # Use Mock() for return values since SQLAlchemy's or_() will receive them- mock_model = Mock()- mock_model.title = Mock()- mock_model.title.ilike = Mock(- return_value=Mock()- ) # Return Mock, not string- mock_model.authors = Mock()- mock_model.authors.ilike = Mock(return_value=Mock())- mock_model.doi = Mock()- mock_model.doi.ilike = Mock(return_value=Mock())-- # Mock the or_ function to avoid SQLAlchemy validation- mocker.patch(- "local_deep_research.research_library.services.library_service.or_",- return_value=Mock(),- )-- # Also mock ResearchResource.title.ilike since _apply_search_filter uses it- mock_resource = Mock()- mock_resource.title = Mock()- mock_resource.title.ilike = Mock(return_value=Mock())- mocker.patch(- "local_deep_research.research_library.services.library_service.ResearchResource",- mock_resource,+ query = Mock()+ query.filter.return_value = query+ assert (+ LibraryService("test_user")._apply_search_filter(+ query, Document, "test search"+ )+ is query)-- with patch.object(- LibraryService, "__init__", lambda self, username: None- ):- service = LibraryService.__new__(LibraryService)- service.username = "test_user"-- service._apply_search_filter(mock_query, mock_model, "test search")-- assert mock_query.filter.called+ query.filter.assert_called_once()+ expression = query.filter.call_args.args[0].compile()+ assert "test search" not in str(expression)+ assert "%test search%" in expression.params.values()class TestLibraryServiceApplySearchFilterEscaping:@@ -826,6 +802,278 @@ class TestLibraryServiceApplySearchFilterEscaping:assert "https://100pages.com/article" not in urls+class TestSearchMatchesFilenameOnlyWhereListed:+ """``get_documents(search_query=...)`` matches ``Document.filename``+ exactly where the Library lists the document under that filename.++ The listed name is read from the real, unsearched ``get_documents``+ output, combined the way the Library card heading combines it+ (``doc.document_title or doc.file_name`` in ``pages/library.html``), so+ the expectation follows the display code instead of restating it. Each+ filename carries a token that appears in no other column, so a hit on+ the token can only come from the filename.+ """++ def test_filename_matches_only_where_it_is_the_listed_name(+ self, library_session, mock_upload_source_type, mock_collection, mocker+ ):+ import hashlib+ import uuid+ from contextlib import contextmanager++ from local_deep_research.constants import FILE_PATH_TEXT_ONLY+ from local_deep_research.database.models.library import (+ Document,+ DocumentCollection,+ DocumentStatus,+ )+ from local_deep_research.database.models.research import (+ ResearchHistory,+ ResearchResource,+ )+ from local_deep_research.research_library.services import (+ library_service,+ )++ research = ResearchHistory(+ id=str(uuid.uuid4()),+ query="q",+ mode="quick",+ status="completed",+ created_at="2026-01-01T00:00:00",+ )+ library_session.add(research)+ library_session.flush()++ unlinked = object()+ # name: (token, title, filename, file_path, title of the research+ # resource linked by content-hash dedup, listed under filename)+ cases = {+ # An upload: no title and no linked resource.+ "upload": (+ "qx1q",+ None,+ "upload_qx1q.txt",+ FILE_PATH_TEXT_ONLY,+ unlinked,+ True,+ ),+ "empty_title": ("qx2q", "", "blank_qx2q.txt", None, unlinked, True),+ # A titled document whose stored filename holds the term, as a+ # Zotero item's does (it sets a title and a derived filename).+ "titled": (+ "qx3q",+ "Attention Is All You Need",+ "Attention_qx3q.pdf",+ None,+ unlinked,+ False,+ ),+ "linked_titled": (+ "qx4q",+ None,+ "linked_qx4q.pdf",+ None,+ "Linked Paper",+ False,+ ),+ # No title anywhere: the card falls back to file_name, which is+ # the filename while the document has no real file path ...+ "linked_untitled": (+ "qx5q",+ None,+ "linked_qx5q.txt",+ FILE_PATH_TEXT_ONLY,+ None,+ True,+ ),+ # ... and the stored file's own name once it has one.+ "linked_untitled_stored": (+ "qx6q",+ None,+ "linked_qx6q.pdf",+ "pdfs/12.pdf",+ "",+ False,+ ),+ }+ ids = {}+ for name, case in cases.items():+ _, title, filename, file_path, res_title, _ = case+ doc = Document(+ id=str(uuid.uuid4()),+ source_type_id=mock_upload_source_type.id,+ document_hash=hashlib.sha256(name.encode()).hexdigest(),+ file_size=1,+ file_type=filename.rsplit(".", 1)[1],+ title=title,+ filename=filename,+ file_path=file_path,+ status=DocumentStatus.COMPLETED,+ )+ library_session.add(doc)+ library_session.add(+ DocumentCollection(+ document_id=doc.id, collection_id=mock_collection.id+ )+ )+ if res_title is not unlinked:+ library_session.add(+ ResearchResource(+ research_id=research.id,+ title=res_title,+ url=f"https://example.com/{name}",+ created_at="2026-01-01T00:00:00",+ document_id=doc.id,+ )+ )+ ids[name] = doc.id+ library_session.commit()++ @contextmanager+ def _session(*args, **kwargs):+ yield library_session++ mocker.patch.object(library_service, "get_user_db_session", _session)+ mocker.patch(+ "local_deep_research.database.library_init.get_default_library_id",+ return_value=mock_collection.id,+ )+ mocker.patch.object(library_service, "get_settings_manager")+ mocker.patch.object(+ library_service,+ "get_absolute_path_from_settings",+ return_value=None,+ )+ service = library_service.LibraryService("test_user")++ listed = {d["id"]: d for d in service.get_documents()}+ for name, (token, _, filename, _, _, expected) in cases.items():+ card = listed[ids[name]]+ heading = card["document_title"] or card["file_name"]+ assert (heading == filename) is expected, (name, heading)++ hits = {d["id"] for d in service.get_documents(search_query=token)}+ assert hits <= {ids[name]}, (name, hits)+ assert (ids[name] in hits) is expected, (name, heading, hits)++ # A document listed under a resource title is found by that title.+ assert ids["linked_titled"] in {+ d["id"] for d in service.get_documents(search_query="Linked Paper")+ }++ @pytest.mark.parametrize("explicit_fk", [True, False])+ @pytest.mark.parametrize("preferred_title", ["Displayed paper title", None])+ def test_filename_search_uses_the_displayed_resource_with_dedup_fanout(+ self,+ library_session,+ mock_upload_source_type,+ mock_collection,+ mocker,+ explicit_fk,+ preferred_title,+ ):+ import hashlib+ import uuid+ from contextlib import contextmanager++ from local_deep_research.constants import FILE_PATH_TEXT_ONLY+ from local_deep_research.database.models.library import (+ Document,+ DocumentCollection,+ DocumentStatus,+ )+ from local_deep_research.database.models.research import (+ ResearchHistory,+ ResearchResource,+ )+ from local_deep_research.research_library.services import (+ library_service,+ )++ research = ResearchHistory(+ id=str(uuid.uuid4()),+ query="q",+ mode="quick",+ status="completed",+ created_at="2026-01-01T00:00:00",+ )+ doc = Document(+ id=str(uuid.uuid4()),+ source_type_id=mock_upload_source_type.id,+ document_hash=hashlib.sha256(b"deduplicated content").hexdigest(),+ file_size=1,+ file_type="pdf",+ title=None,+ filename="hidden_filename_token.pdf",+ file_path=FILE_PATH_TEXT_ONLY,+ status=DocumentStatus.COMPLETED,+ )+ library_session.add_all([research, doc])+ library_session.flush()+ # With an explicit FK, make the preferred resource the newer row.+ # Without one, the oldest resource is the stable display fallback.+ resources = [+ ResearchResource(+ research_id=research.id,+ title=title,+ url=f"https://example.com/{index}",+ created_at="2026-01-01T00:00:00",+ document_id=doc.id,+ )+ for index, title in enumerate(+ [+ None if preferred_title else "Other linked title",+ preferred_title,+ ]+ if explicit_fk+ else [+ preferred_title,+ None if preferred_title else "Other linked title",+ ]+ )+ ]+ library_session.add_all(resources)+ library_session.flush()+ if explicit_fk:+ doc.resource_id = resources[1].id+ library_session.add(+ DocumentCollection(+ document_id=doc.id, collection_id=mock_collection.id+ )+ )+ library_session.commit()++ @contextmanager+ def session(*args, **kwargs):+ yield library_session++ mocker.patch.object(library_service, "get_user_db_session", session)+ service = library_service.LibraryService("test_user")+ listed = service.get_documents(collection_id=mock_collection.id)+ assert len(listed) == 1+ assert (listed[0]["document_title"] or listed[0]["file_name"]) == (+ preferred_title or doc.filename+ )+ hits = service.get_documents(+ collection_id=mock_collection.id,+ search_query="hidden_filename_token",+ )+ assert [hit["id"] for hit in hits] == (+ [] if preferred_title else [doc.id]+ )+ # Existing title search still reaches every linked research resource.+ for resource in resources:+ if resource.title:+ assert [+ hit["id"]+ for hit in service.get_documents(+ collection_id=mock_collection.id,+ search_query=resource.title,+ )+ ] == [doc.id]++class TestLibraryServiceGetResearchListWithStats:"""Tests for get_research_list_with_stats method."""diff --git a/tests/research_library/services/test_library_service_domain_filters.py b/tests/research_library/services/test_library_service_domain_filters.pyindex a85f1addeb..3b5fb409fd 100644--- a/tests/research_library/services/test_library_service_domain_filters.py+++ b/tests/research_library/services/test_library_service_domain_filters.py@@ -4,11 +4,14 @@ Tests for LibraryService domain detection and query filter methods.Covers:- _is_pubmed_url edge cases (ncbi without /pmc, substring in hostname, etc.)- _apply_domain_filter generic substring match against original_url-- _apply_search_filter pattern wrapping and return values+- _apply_search_filter pattern binding, literal ``%`` and ``_`` in every+ searched field (real SQLite rows), and return values"""from unittest.mock import patch, MagicMock+import pytest+# ============== Helper to create service ==============@@ -127,103 +130,153 @@ class TestApplyDomainFilter:class TestApplySearchFilter:- """Tests for _apply_search_filter method."""-- def test_search_filter_wraps_query_in_wildcards(self, mocker):- """Search query is wrapped as %search_query% with escape='\\\\'."""- service = _make_service()- mock_query = MagicMock()- mock_model = MagicMock()-- mocker.patch(- "local_deep_research.research_library.services.library_service.or_",- return_value=MagicMock(),- )- mock_resource = MagicMock()- mocker.patch(- "local_deep_research.research_library.services.library_service.ResearchResource",- mock_resource,- )-- service._apply_search_filter(- mock_query, mock_model, "quantum computing"+ """Build and execute real SQL expressions with bound search input."""++ @pytest.mark.parametrize(+ ("search_query", "expected_pattern"),+ [+ ("quantum computing", "%quantum computing%"),+ ("100%_test", r"%100\%\_test%"),+ ("x' OR 1=1 --", "%x' OR 1=1 --%"),+ ],+ )+ def test_search_filter_binds_escaped_pattern(+ self, library_session, search_query, expected_pattern+ ):+ from sqlalchemy.dialects import sqlite++ from local_deep_research.database.models.library import Document+ from local_deep_research.database.models.research import (+ ResearchResource,)- # Verify all 4 fields called with correct pattern + escape kwarg- expected_pattern = "%quantum computing%"- mock_model.title.ilike.assert_called_once_with(- expected_pattern, escape="\\"- )- mock_model.authors.ilike.assert_called_once_with(- expected_pattern, escape="\\"- )- mock_model.doi.ilike.assert_called_once_with(- expected_pattern, escape="\\"+ query = library_session.query(Document).outerjoin(+ ResearchResource, ResearchResource.document_id == Document.id)- mock_resource.title.ilike.assert_called_once_with(- expected_pattern, escape="\\"- )-- def test_search_filter_uses_four_ilike_conditions(self, mocker):- """Search filter creates or_() with 4 ilike conditions."""- service = _make_service()- mock_query = MagicMock()- mock_model = MagicMock()-- mock_or = mocker.patch(- "local_deep_research.research_library.services.library_service.or_",- return_value=MagicMock(),+ filtered = _make_service()._apply_search_filter(+ query, Document, search_query)- mock_resource = MagicMock()- mocker.patch(- "local_deep_research.research_library.services.library_service.ResearchResource",- mock_resource,+ compiled = filtered.statement.compile(dialect=sqlite.dialect())+ assert search_query not in str(compiled)+ assert expected_pattern in compiled.params.values()+ # Execute the correlated subqueries as well as compiling the bindings.+ filtered.all()++ @pytest.mark.parametrize("wildcard", ["%", "_"])+ @pytest.mark.parametrize(+ "field", ["title", "filename", "authors", "doi", "resource_title"]+ )+ def test_search_wildcard_matches_literally_in_every_field(+ self,+ library_session,+ mock_upload_source_type,+ mock_collection,+ mocker,+ field,+ wildcard,+ ):+ """A ``%`` or ``_`` in the search text matches only itself, in each+ searched field, through ``get_documents`` on real SQLite rows.++ Two documents hold a value in ``field`` and in no other searched+ column: the target holds the search text (``lit%tok`` or+ ``lit_tok``), the decoy holds ``litXtok``, which the search text+ matches only if its wildcard is left unescaped. Binding the input+ unescaped finds the decoy as well. Dropping the ``escape`` argument+ from the field's ``ilike`` misses the target: SQLite has no default+ LIKE escape character, so it reads the backslash literally.+ """+ import hashlib+ import uuid+ from contextlib import contextmanager++ from local_deep_research.database.models.library import (+ Document,+ DocumentCollection,+ DocumentStatus,)-- service._apply_search_filter(mock_query, mock_model, "test")-- # or_() receives 4 arguments- assert mock_or.call_count == 1- args = mock_or.call_args[0]- assert len(args) == 4-- def test_search_filter_escapes_sql_wildcards(self, mocker):- """SQL special chars (% and _) in query are escaped, not wildcards."""- service = _make_service()- mock_query = MagicMock()- mock_model = MagicMock()-- mocker.patch(- "local_deep_research.research_library.services.library_service.or_",- return_value=MagicMock(),+ from local_deep_research.database.models.research import (+ ResearchHistory,+ ResearchResource,)- mocker.patch(- "local_deep_research.research_library.services.library_service.ResearchResource",- MagicMock(),+ from local_deep_research.research_library.services import (+ library_service,)- service._apply_search_filter(mock_query, mock_model, "100%_test")-- # Both '%' and '_' get backslash-escaped before being wrapped- mock_model.title.ilike.assert_called_once_with(- "%100\\%\\_test%", escape="\\"+ research = ResearchHistory(+ id=str(uuid.uuid4()),+ query="q",+ mode="quick",+ status="completed",+ created_at="2026-01-01T00:00:00",)-- def test_search_filter_returns_filtered_query(self, mocker):- """Return value is the result of query.filter()."""+ library_session.add(research)+ library_session.flush()++ term = f"lit{wildcard}tok"+ ids = {}+ for name, value in (("target", term), ("decoy", "litXtok")):+ # Every document is untitled unless the field is the title, so+ # the unlinked filename document is listed under its filename,+ # the only case in which the filename is searched.+ columns = {+ "title": {"title": f"Report {value}"},+ "filename": {"filename": f"{value}.txt"},+ "authors": {"authors": [f"Ann {value}"]},+ "doi": {"doi": f"10.1000/{value}"},+ "resource_title": {},+ }[field]+ doc = Document(+ id=str(uuid.uuid4()),+ source_type_id=mock_upload_source_type.id,+ document_hash=hashlib.sha256(name.encode()).hexdigest(),+ file_size=1,+ file_type="txt",+ status=DocumentStatus.COMPLETED,+ **columns,+ )+ library_session.add(doc)+ library_session.add(+ DocumentCollection(+ document_id=doc.id, collection_id=mock_collection.id+ )+ )+ if field == "resource_title":+ library_session.add(+ ResearchResource(+ research_id=research.id,+ title=f"Resource {value}",+ url=f"https://example.com/{name}",+ created_at="2026-01-01T00:00:00",+ document_id=doc.id,+ )+ )+ ids[name] = doc.id+ library_session.commit()++ @contextmanager+ def session(*args, **kwargs):+ yield library_session++ mocker.patch.object(library_service, "get_user_db_session", session)service = _make_service()- mock_query = MagicMock()- mock_model = MagicMock()-- mocker.patch(- "local_deep_research.research_library.services.library_service.or_",- return_value=MagicMock(),- )- mocker.patch(- "local_deep_research.research_library.services.library_service.ResearchResource",- MagicMock(),- )- result = service._apply_search_filter(mock_query, mock_model, "test")-- assert result == mock_query.filter.return_value+ def search(text):+ return [+ hit["id"]+ for hit in service.get_documents(+ collection_id=mock_collection.id, search_query=text+ )+ ]++ # The decoy's value is searched, so only the escaping keeps the+ # decoy out of the results for the search text.+ assert search("litXtok") == [ids["decoy"]]+ assert search(term) == [ids["target"]]++ def test_search_filter_returns_filtered_query(self):+ from local_deep_research.database.models.library import Document++ query = MagicMock()+ result = _make_service()._apply_search_filter(query, Document, "test")+ assert result is query.filter.return_valuediff --git a/tests/research_library/test_library_pipeline_contracts.py b/tests/research_library/test_library_pipeline_contracts.pyindex 7fc77b9f3c..2d5f7e2ed1 100644--- a/tests/research_library/test_library_pipeline_contracts.py+++ b/tests/research_library/test_library_pipeline_contracts.py@@ -647,12 +647,22 @@ def _default_library_id(client) -> str:@pytest.mark.timeout(180)class TestUploadedDocumentIsFindable:- """The library list endpoint doubles as the library search box.-- ``GET /library/api/documents?search=`` is what the Library page's- search field calls. The question is not whether it returns 200 -- it- always does -- but whether it can find a document that is- demonstrably sitting in the collection it searches.+ """Can a search find an uploaded document by the name it lists it under?++ Two endpoints search documents and list each hit by name:++ * ``GET /library/search/api/keyword`` -- the keyword leg of the Search+ page ("Search everything") -- lists a hit as ``title or filename``.+ * ``GET /library/api/documents?search=`` lists a document as+ ``document_title``: its title, else a linked resource's title, else+ its filename. No page calls it with ``search``; the Library page's+ search box filters the cards it has already rendered, in the browser.++ No upload path sets ``Document.title``, so both list an upload under+ its filename. The question is not whether they return 200 -- they+ always do -- but whether they find a document that is demonstrably in+ the scope they search by the name they list it under, and never by a+ stored filename they do not list it under."""@pytest.fixture(scope="class")@@ -661,9 +671,10 @@ class TestUploadedDocumentIsFindable:The title is written through the application's own``get_user_db_session`` -- the same session factory the routes- use -- because no upload path sets ``Document.title``. It exists- purely so the *positive* control below has something the search- filter is documented to match on.+ use -- because no upload path sets ``Document.title``. It gives the+ positive control a title to match, and makes the second document+ one that is listed under its title while its stored filename+ (``other_upload_5151.txt``) is not shown as its name."""from local_deep_research.database.models.library import Documentfrom local_deep_research.database.session_context import (@@ -701,21 +712,28 @@ class TestUploadedDocumentIsFindable:assert resp.status_code == 200, resp.text[:300]return {d["id"] for d in resp.json()["documents"]}+ def _keyword_hits(self, client, query):+ """``{id: listed title}`` from the Search page's keyword leg."""+ resp = client.get(+ "/library/search/api/keyword", params={"q": query, "limit": 50}+ )+ assert resp.status_code == 200, resp.text[:300]+ return {r["id"]: r["title"] for r in resp.json()["results"]}+def test_search_matches_a_document_whose_title_column_is_set(self, upload_client, seeded):"""Positive control: the filter works, on the column it reads.- This is what makes the xfail below a statement about *which- columns are searched* rather than about the endpoint being- broken or the harness being unable to see a hit.+ A title match must retain the existing behavior when filename+ search is added, and exclude the unrelated uploaded document."""hits = self._search(upload_client, "FINDME_TITLED_5151")assert seeded["titled"] in hits, hitsassert seeded["untitled"] not in hits, ("the filter is not discriminating at all")- # Case-insensitive, as ilike promises.+ # ilike ignores the case of ASCII letters.assert seeded["titled"] in self._search(upload_client, "findme_titled_5151")@@ -723,7 +741,7 @@ class TestUploadedDocumentIsFindable:def test_both_documents_are_listed_when_no_search_is_given(self, upload_client, seeded):- """Control for the xfail: both really are in the searched scope.+ """Both uploaded documents really are in the searched scope.Same endpoint, same collection, filter absent -- so a later"search found nothing" cannot be explained by the document being@@ -734,33 +752,88 @@ class TestUploadedDocumentIsFindable:listed = {d["id"]: d for d in resp.json()["documents"]}assert seeded["untitled"] in listed, listed.keys()assert seeded["titled"] in listed, listed.keys()- # And the UI is told the untitled document is *called* its filename.+ # And the API lists the untitled document under its filename.assert (listed[seeded["untitled"]]["document_title"]== "FINDME_UNTITLED_5150.txt")- @pytest.mark.xfail(- strict=True,- reason=(- "LibraryService._apply_search_filter matches only Document.title, "- "Document.authors, Document.doi and ResearchResource.title. No "- "upload path ever sets Document.title, yet the API serialises "- "document_title as `doc.title or resource.title or doc.filename` "- "-- so every user-uploaded document is displayed under a name the "- "library search box can never match, and searching for what the "- "UI shows returns nothing. Fix: add Document.filename (and ideally "- "Document.text_content) to the or_() in _apply_search_filter, or "- "populate Document.title from the sanitised filename at upload."- ),- )def test_search_finds_an_uploaded_document_by_its_displayed_title(self, upload_client, seeded):hits = self._search(upload_client, "FINDME_UNTITLED_5150")assert seeded["untitled"] in hits, (- "the library search box cannot find an uploaded document by the "- f"title the same API displays for it; hits={hits}"+ "the documents API cannot find an uploaded document by the "+ f"title it lists it under; hits={hits}"+ )+ assert seeded["titled"] not in hits+ assert seeded["untitled"] in self._search(+ upload_client, "findme_untitled_5150"+ )+ # LIKE wildcards in the query stay literal: as wildcards, "%" and+ # "_" would match the "_" and the "0" of FINDME_UNTITLED_5150.txt.+ assert seeded["untitled"] not in self._search(+ upload_client, "FINDME_UNTITLED%5150"+ )+ assert seeded["untitled"] not in self._search(+ upload_client, "UNTITLED_515_.txt"+ )++ def test_search_skips_a_titled_documents_stored_filename(+ self, upload_client, seeded+ ):+ """A titled document is listed under its title, not its filename.++ The control proves the term is in the stored filename the API+ reports for that document, so the miss is the filter declining a+ name the document is not listed under, not the term being absent.+ """+ resp = upload_client.get("/library/api/documents")+ assert resp.status_code == 200, resp.text[:300]+ titled = {d["id"]: d for d in resp.json()["documents"]}[+ seeded["titled"]+ ]+ assert titled["document_title"] == "FINDME_TITLED_5151"+ assert titled["file_name"] == "other_upload_5151.txt"++ assert seeded["titled"] not in self._search(+ upload_client, "other_upload_5151"+ )++ def test_search_page_finds_an_upload_by_its_listed_filename(+ self, upload_client, seeded+ ):+ """The Search page lists an upload under its filename.++ Its body text does not contain the name, so only the filename can+ produce the hit.+ """+ hits = self._keyword_hits(upload_client, "FINDME_UNTITLED_5150")+ assert hits.get(seeded["untitled"]) == "FINDME_UNTITLED_5150.txt", (+ "the Search page cannot find an uploaded document by the name "+ f"it lists it under; hits={hits}"+ )+ assert seeded["titled"] not in hits+ assert seeded["untitled"] in self._keyword_hits(+ upload_client, "findme_untitled_5150"+ )+ assert seeded["untitled"] not in self._keyword_hits(+ upload_client, "FINDME_UNTITLED%5150"+ )+ assert seeded["untitled"] not in self._keyword_hits(+ upload_client, "UNTITLED_515_.txt"+ )++ def test_search_page_skips_a_titled_documents_stored_filename(+ self, upload_client, seeded+ ):+ """Control first: the titled document is found by, and listed+ under, its title; then its stored filename must not match."""+ hits = self._keyword_hits(upload_client, "FINDME_TITLED_5151")+ assert hits.get(seeded["titled"]) == "FINDME_TITLED_5151", hits++ assert seeded["titled"] not in self._keyword_hits(+ upload_client, "other_upload_5151")