An open source, non-profit web search engine
Index Staan results from Combined Search and report pages_indexed
Claude889627a0f6f0
diff --git a/mwmbl/tinysearchengine/combined_search.py b/mwmbl/tinysearchengine/combined_search.pyindex b528333..2f73957 100644--- a/mwmbl/tinysearchengine/combined_search.py+++ b/mwmbl/tinysearchengine/combined_search.py@@ -18,9 +18,10 @@ There is no separate Wikipedia fetch: Staan already returns Wikipedia pages whenrelevant, and evaluation found the extra fetch roughly neutral on quality (seemwmbl/rankeval/combined-search-handover.md).-Nothing found here is written back to the search index. Super Search indexes what it finds;-whether third-party SERP results belong in our index is a separate question with its own-answer, and this endpoint does not pre-empt it.+Staan's results are written back to the search index, against the query's unigrams and+bigrams, exactly as Super Search indexes what it finds: a page Staan found for one person's+query then becomes a candidate for every search, plain /search/ included. The write runs+alongside ranking, and the response reports how many new pages it added."""import asyncio@@ -30,14 +31,19 @@ from asgiref.sync import sync_to_asyncfrom django.conf import settingsfrom ninja import Routerfrom ninja.errors import HttpError+from pydantic import Fieldfrom mwmbl.format import format_result_v2+from mwmbl.indexer.index_batches import index_results_against_queryfrom mwmbl.quota import (check_rate_limit,decrement_monthly_combined_search,increment_monthly_combined_search,)from mwmbl.search_auth import authenticate_user+from mwmbl.search_setup import index_path+from mwmbl.tinysearchengine.indexer import Document+from mwmbl.tinysearchengine.rank import find_blacklisted_urlsfrom mwmbl.tinysearchengine.search import SearchResponsefrom mwmbl.tinysearchengine.staan import get_staan_results@@ -46,6 +52,15 @@ logger = getLogger(__name__)router = Router(tags=["Combined Search"])+class CombinedSearchResponse(SearchResponse):+ pages_indexed: int = Field(+ description="Number of distinct new pages (URLs) added to the Mwmbl index from EUSP's "+ "results for this search. Pages are indexed against the query's unigrams and bigrams, "+ "so a repeated query usually adds none.",+ examples=[3],+ )++DESCRIPTION = ("Search the Mwmbl index and EUSP (European Search Perspective) in one request and ""return the ranked union.\n\n"@@ -62,6 +77,8 @@ DESCRIPTION = ("Authentication is required: a search-scoped API key in `X-API-Key`, or a JWT bearer ""token. Obtain a key via `POST /api/v1/platform/api-keys/`. A per-user monthly quota ""applies; `monthly_usage` and `monthly_limit` report it on every response.\n\n"+ "EUSP's results are added to the Mwmbl index; `pages_indexed` reports how many new "+ "pages that added.\n\n""If EUSP is down or unconfigured, the request loses its extra recall, not its ""results: the index's results are ranked and returned as usual.\n\n""**Query parameter:** `q` - the search query string (required)."@@ -79,10 +96,31 @@ OPENAPI_EXTRA = {}+def index_staan_results(query: str, staan_results: list[Document]) -> int:+ """Index Staan's results against the query, returning the number of new pages added.++ Blacklisted domains are dropped first: index_results_against_query bypasses the+ blacklist check in index_documents, and the ranker's read-path filter only stops these+ pages being shown, not being written.++ Never raises: a failed index write costs the index its new pages, not the caller its+ search.+ """+ blacklisted_urls = find_blacklisted_urls(staan_results)+ allowed = [document for document in staan_results if document.url not in blacklisted_urls]+ if not allowed:+ return 0+ try:+ return index_results_against_query(allowed, query, str(index_path))+ except Exception:+ logger.exception("combined-search failed to index Staan results")+ return 0++def init_router(ranker) -> None:@router.get("",- response=SearchResponse,+ response=CombinedSearchResponse,# Handled manually in the view so both an API key and a JWT work under an async# view - the same reason Super Search does it this way.auth=None,@@ -115,13 +153,18 @@ def init_router(ranker) -> None:asyncio.to_thread(ranker.retrieve, q),asyncio.to_thread(get_staan_results, q),)- results = await asyncio.to_thread(ranker.search_retrieved, retrieval, staan_results)+ # Ranking only reads what was already retrieved, so the index write can overlap it.+ results, pages_indexed = await asyncio.gather(+ asyncio.to_thread(ranker.search_retrieved, retrieval, staan_results),+ asyncio.to_thread(index_staan_results, q, staan_results),+ )formatted = [format_result_v2(result, i + 1, q) for i, result in enumerate(results)]- return SearchResponse(+ return CombinedSearchResponse(query=q,number_of_results=len(formatted),results=formatted,monthly_usage=monthly_usage,monthly_limit=monthly_limit,+ pages_indexed=pages_indexed,)diff --git a/mwmbl/tinysearchengine/staan.py b/mwmbl/tinysearchengine/staan.pyindex 2b7d9ce..d742771 100644--- a/mwmbl/tinysearchengine/staan.py+++ b/mwmbl/tinysearchengine/staan.py@@ -10,8 +10,7 @@ same machinery as every other candidate. The cache file is already namespaced byDocumentSource, so Staan entries and Wikipedia entries share a page without seeing eachother - see the external_cache module docstring.-Nothing here writes to the search index: these are somebody else's results, and indexing-them is a separate decision with its own quality question.+Nothing here writes to the search index; Combined Search does that with what this returns."""from logging import getLoggerdiff --git a/test/test_combined_search.py b/test/test_combined_search.pyindex bc9cad5..492b808 100644--- a/test/test_combined_search.py+++ b/test/test_combined_search.py@@ -9,6 +9,8 @@ atomically."""import threading+from pathlib import Path+from urllib.parse import urlparseimport pytestfrom allauth.account.models import EmailAddress@@ -20,7 +22,7 @@ from ninja_jwt.tokens import RefreshTokenimport mwmbl.tinysearchengine.combined_search as combined_searchfrom mwmbl.models import ApiKey, generate_api_keyfrom mwmbl.quota import _combined_search_monthly_key-from mwmbl.tinysearchengine.indexer import Document, DocumentSource, DocumentState+from mwmbl.tinysearchengine.indexer import Document, DocumentSource, DocumentState, TinyIndexUser = get_user_model()@@ -85,7 +87,7 @@ def stub_sources(monkeypatch):"""calls = {}- def configure(staan=(STAAN_RESULT,), index=(INDEX_RESULT,)):+ def configure(staan=(STAAN_RESULT,), index=(INDEX_RESULT,), pages_indexed=1):def fake_staan(query, *args, **kwargs):calls["staan_query"] = queryif isinstance(staan, Exception):@@ -100,7 +102,16 @@ def stub_sources(monkeypatch):calls["additional_results"] = additional_resultsreturn retrieval + list(additional_results)+ def fake_index(documents, query, path):+ calls["indexed"] = [document.url for document in documents]+ calls["indexed_query"] = query+ if isinstance(pages_indexed, Exception):+ raise pages_indexed+ return pages_indexed+monkeypatch.setattr(combined_search, "get_staan_results", fake_staan)+ monkeypatch.setattr(combined_search, "index_results_against_query", fake_index)+ monkeypatch.setattr(combined_search, "find_blacklisted_urls", lambda documents: set())# The router closed over the ranker at registration time, so the ranker instance# itself is what has to be patched, not the name in search_setup.from mwmbl.search_setup import combined_ranker@@ -298,3 +309,69 @@ def test_an_empty_pool_is_an_empty_response_not_an_error(client, api_key, fresh_assert body["results"] == []assert body["number_of_results"] == 0+++# ---------------------------------------------------------------------------+# Indexing Staan's results+# ---------------------------------------------------------------------------+++def test_staan_results_are_indexed_against_the_query(client, api_key, fresh_quota, stub_sources):+ calls = stub_sources(pages_indexed=3)++ body = _get(client, api_key, query="rust").json()++ assert calls["indexed"] == [STAAN_RESULT.url]+ assert calls["indexed_query"] == "rust"+ assert body["pages_indexed"] == 3+++def test_blacklisted_staan_results_are_not_indexed(client, api_key, fresh_quota, stub_sources, monkeypatch):+ """index_results_against_query bypasses index_documents' blacklist check."""+ bad = Document("Bad", "https://badsite.test/x", "bad", 5.0, source=DocumentSource.STAAN)+ calls = stub_sources(staan=(bad, STAAN_RESULT))+ monkeypatch.setattr(+ combined_search,+ "find_blacklisted_urls",+ lambda documents: {d.url for d in documents if urlparse(d.url).netloc == "badsite.test"},+ )++ _get(client, api_key)++ assert calls["indexed"] == [STAAN_RESULT.url]+++def test_nothing_from_staan_indexes_nothing(client, api_key, fresh_quota, stub_sources):+ calls = stub_sources(staan=())++ body = _get(client, api_key).json()++ assert "indexed" not in calls+ assert body["pages_indexed"] == 0+++def test_a_failed_index_write_still_serves_the_results(client, api_key, fresh_quota, stub_sources):+ stub_sources(pages_indexed=OSError("disk full"))++ body = _get(client, api_key).json()++ assert body["pages_indexed"] == 0+ assert [result["url"] for result in body["results"]] == [INDEX_RESULT.url, STAAN_RESULT.url]+++def test_index_staan_results_writes_new_pages_once(tmp_path, monkeypatch):+ index_path = Path(tmp_path) / "index.tinysearch"+ with TinyIndex.create(Document, str(index_path), num_pages=64, page_size=4096):+ pass+ monkeypatch.setattr(combined_search, "index_path", index_path)+ monkeypatch.setattr(combined_search, "find_blacklisted_urls", lambda documents: set())++ assert combined_search.index_staan_results("tokio", [STAAN_RESULT]) == 1+ assert combined_search.index_staan_results("tokio", [STAAN_RESULT]) == 0++ with TinyIndex(Document, str(index_path), "r") as index:+ assert [document.url for document in index.retrieve("tokio")] == [STAAN_RESULT.url]diff --git a/test/test_openapi.py b/test/test_openapi.pyindex 524aac0..0955020 100644--- a/test/test_openapi.py+++ b/test/test_openapi.py@@ -220,9 +220,10 @@ def test_combined_search_is_documented():assert [(p["name"], p["in"], p["required"]) for p in operation["parameters"]] == [("q", "query", True)]assert operation["responses"]["200"]["content"]["application/json"]["schema"] == {- "$ref": "#/components/schemas/SearchResponse"+ "$ref": "#/components/schemas/CombinedSearchResponse"}- for expected in ("X-API-Key", "monthly_limit", "eusp", "wikipedia"):+ assert "pages_indexed" in spec["components"]["schemas"]["CombinedSearchResponse"]["required"]+ for expected in ("X-API-Key", "monthly_limit", "pages_indexed", "eusp", "wikipedia"):assert expected in operation["description"]# The provider agreement labels its results EUSP; its own name stays out of the public docs.assert "staan" not in operation["description"].lower()