An open source, non-profit web search engine
Index super search results
Daoud Clarke13ddd9275417
diff --git a/devdata/index-v2.tinysearch b/devdata/index-v2.tinysearchindex ae3aa95..7d5675f 100644Binary files a/devdata/index-v2.tinysearch and b/devdata/index-v2.tinysearch differdiff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.pyindex 8097d67..89817a6 100644--- a/mwmbl/indexer/index_batches.py+++ b/mwmbl/indexer/index_batches.py@@ -7,15 +7,17 @@ from datetime import datetimefrom functools import reducefrom logging import getLoggerfrom typing import Collection, Iterable, Optional+from urllib.parse import unquotefrom mwmbl.crawler.batch import HashedBatch, Itemfrom mwmbl.crawler.urls import URLStatusfrom mwmbl.indexer import process_batchfrom mwmbl.indexer.batch_cache import BatchCache-from mwmbl.indexer.index import tokenize_document+from mwmbl.indexer.index import tokenize_document, prepare_url_for_tokenizingfrom mwmbl.indexer.indexdb import BatchStatusfrom mwmbl.tinysearchengine.indexer import Document, TinyIndex, DocumentState, CURATED_STATESfrom mwmbl.tinysearchengine.rank import score_result, DOCUMENT_FREQUENCIES, N_DOCUMENTS, HeuristicRanker+from mwmbl.tokenizer import tokenize, get_bigramsfrom mwmbl.utils import add_term_infoslogger = getLogger(__name__)@@ -88,6 +90,63 @@ def index_pages(index_path: str, page_documents: dict[int, list[Document]], markreturn term_new_doc_counts+def _document_token_set(doc: Document) -> set[str]:+ """Unigram tokens of a document's title, URL and extract (no bigrams)."""+ prepared_url = prepare_url_for_tokenizing(unquote(doc.url))+ return (set(tokenize(doc.title))+ | set(tokenize(prepared_url))+ | set(tokenize(doc.extract)))+++def index_results_against_query(documents: list[Document], query: str, index_path: str) -> int:+ """Index each document against the query unigrams/bigrams it matches.++ A query term matches a document when all of the term's words are present in+ the document's token set (unigram: the token; bigram: both words, in any+ order). Matching docs are stored against that term via index_pages(), which+ applies the normal combine/prioritise path. Returns the number of distinct+ URLs newly added to the index.++ The count is computed in the read pass, before combine/store, so a candidate+ later dropped by URL/title dedup or by the full-page trim is still counted;+ the figure is therefore a slight upper bound on what is persisted.+ """+ tokens = tokenize(query)+ if not tokens or not documents:+ return 0++ # term string -> the set of words that must all be present to match.+ query_terms: dict[str, frozenset[str]] = {t: frozenset((t,)) for t in tokens}+ for bigram in get_bigrams(len(tokens), tokens):+ query_terms[bigram] = frozenset(bigram.split())++ # Read pass: build per-page candidates and track which (term, url) are new.+ page_documents: dict[int, list[Document]] = defaultdict(list)+ new_urls: set[str] = set()+ with TinyIndex(Document, index_path, 'r') as indexer:+ existing_keys: dict[int, set[tuple]] = {}+ for doc in documents:+ if not (doc.url and doc.title and doc.extract):+ continue+ doc_tokens = _document_token_set(doc)+ for term, words in query_terms.items():+ if not (words <= doc_tokens):+ continue+ page = indexer.get_key_page_index(term)+ page_documents[page].append(Document(+ doc.title, doc.url, doc.extract,+ term=term, last_crawled=doc.last_crawled,+ ))+ if page not in existing_keys:+ existing_keys[page] = {(d.term, d.url) for d in indexer.get_page(page)}+ if (term, doc.url) not in existing_keys[page]:+ new_urls.add(doc.url)++ if page_documents:+ index_pages(index_path, page_documents) # reuse the existing write path+ return len(new_urls)++def combine_documents(existing_documents, documents, mark_synced, ranker):sorted_documents = sort_documents(documents, existing_documents, ranker)diff --git a/mwmbl/tinysearchengine/super_search.py b/mwmbl/tinysearchengine/super_search.pyindex d1830bf..f8ff367 100644--- a/mwmbl/tinysearchengine/super_search.py+++ b/mwmbl/tinysearchengine/super_search.py@@ -31,13 +31,14 @@ from ninja.errors import HttpErrorfrom pydantic import BaseModel, Fieldfrom mwmbl.crawler.retrieve import crawl_url+from mwmbl.indexer.index_batches import index_results_against_queryfrom mwmbl.quota import (check_rate_limit,decrement_monthly_super_search,increment_monthly_super_search,)from mwmbl.search_auth import authenticate_user-from mwmbl.search_setup import ltr_model+from mwmbl.search_setup import index_path, ltr_modelfrom mwmbl.tinysearchengine.indexer import Documentfrom mwmbl.tinysearchengine.ltr_rank import score_documentsfrom mwmbl.tinysearchengine.rank import score_result_whole@@ -184,6 +185,14 @@ class DoneEvent(Schema):monthly_usage: int = Field(description="Caller's Super Search requests used this month ""(including this one).", examples=[3])monthly_limit: int = Field(description="Caller's monthly Super Search quota.", examples=[100])+ pages_indexed: int = Field(+ default=0,+ description="Number of distinct new pages (URLs) added to the Mwmbl index as a "+ "result of this search. Can exceed the number of results returned, "+ "since a page may match a unigram or bigram of the query without "+ "matching the whole query.",+ examples=[7],+ )# Maps each SSE event name to the model describing its `data` payload. Used both@@ -420,6 +429,23 @@ async def _emit_final_results())+async def _index_results(query: str, docs: list[Document]) -> int:+ """Index everything Super Search found against the query's unigrams/bigrams.++ Runs the blocking index write off the event loop and never lets an indexing+ failure break the response. Returns the number of distinct new pages indexed.+ """+ if not docs:+ return 0+ try:+ return await asyncio.to_thread(+ index_results_against_query, docs, query, str(index_path)+ )+ except Exception:+ logger.exception("super-search failed to index results")+ return 0++async def _run_pipeline(query: str, emit, all_docs: list[Document], last_results_key: list, lock: asyncio.Lock) -> None:@@ -500,6 +526,7 @@ async def _sse_stream(query: str, monthly_usage: int, monthly_limit: int):queue: asyncio.Queue = asyncio.Queue()started = time.monotonic()reason = "complete"+ pages_indexed = 0all_docs: list[Document] = []last_results_key: list = [None]results_lock = asyncio.Lock()@@ -508,7 +535,7 @@ async def _sse_stream(query: str, monthly_usage: int, monthly_limit: int):await queue.put((event_type, data))async def producer():- nonlocal reason+ nonlocal reason, pages_indexedtry:await asyncio.wait_for(_run_pipeline(query, emit, all_docs, last_results_key, results_lock),@@ -529,6 +556,7 @@ async def _sse_stream(query: str, monthly_usage: int, monthly_limit: int):await _emit_final_results(query, all_docs, emit, last_results_key, results_lock)except Exception:logger.exception("super-search failed to emit final results")+ pages_indexed = await _index_results(query, all_docs)await queue.put(_SENTINEL)task = asyncio.create_task(producer())@@ -550,6 +578,7 @@ async def _sse_stream(query: str, monthly_usage: int, monthly_limit: int):elapsed_seconds=round(time.monotonic() - started, 3),monthly_usage=monthly_usage,monthly_limit=monthly_limit,+ pages_indexed=pages_indexed,))finally:if not task.done():@@ -594,7 +623,7 @@ def init_router() -> None:"| `link_followed` | `{url, from}` | An outbound link from a crawled page was fetched and added to the candidate pool. |\n""| `results` | `{results[], count}` | The current authoritative ranking (items have `origin=\"final\"`). Emitted progressively after each source and once more at the end — **replace** your displayed list on each. |\n""| `error` | `{message}` | The pipeline crashed; the stream ends. |\n"- "| `done` | `{reason, elapsed_seconds, monthly_usage, monthly_limit}` | Terminal event. `reason` is `complete`, `timed_out`, `cancelled` or `error`. |\n\n"+ "| `done` | `{reason, elapsed_seconds, monthly_usage, monthly_limit, pages_indexed}` | Terminal event. `reason` is `complete`, `timed_out`, `cancelled` or `error`; `pages_indexed` is the number of new pages added to the Mwmbl index by this search. |\n\n""The exact JSON shape of every payload is given by the `oneOf` schema ""of the 200 response below."),diff --git a/test/test_index_batches.py b/test/test_index_batches.pyindex 66d01ef..013ea51 100644--- a/test/test_index_batches.py+++ b/test/test_index_batches.py@@ -1,5 +1,11 @@-from mwmbl.indexer.index_batches import sort_documents, combine_documents, _merge_user_ids, MAX_USER_IDS-from mwmbl.tinysearchengine.indexer import Document, DocumentState+from pathlib import Path+from tempfile import TemporaryDirectory++from mwmbl.indexer.index_batches import (+ sort_documents, combine_documents, _merge_user_ids, MAX_USER_IDS,+ index_results_against_query,+)+from mwmbl.tinysearchengine.indexer import Document, DocumentState, TinyIndexclass UrlRanker:@@ -83,6 +89,44 @@ def test_sort_documents_duplicates_keep_synced_state():]+# ---------------------------------------------------------------------------+# index_results_against_query+# ---------------------------------------------------------------------------++def test_index_results_against_query():+ # "rust", "async" and the bigram "rust async" land on distinct pages here,+ # so cross-term URL dedup within a page does not interfere with the asserts.+ num_pages = 64+ a = Document(title="Rust async runtime", url="http://a.example/page", extract="an async runtime")+ b = Document(title="Rust systems guide", url="http://b.example", extract="low level")+ c = Document(title="Async patterns", url="http://c.example", extract="concurrency primitives")+ docs = [a, b, c]++ with TemporaryDirectory() as temp_dir:+ index_path = str(Path(temp_dir) / 'temp-index.tinysearch')+ with TinyIndex.create(Document, index_path, num_pages=num_pages, page_size=4096):+ pass++ new_count = index_results_against_query(docs, "rust async", index_path)++ # All three pages are newly added (each matches at least one term).+ assert new_count == 3++ with TinyIndex(Document, index_path, 'r') as indexer:+ rust_urls = {d.url for d in indexer.retrieve("rust")}+ async_urls = {d.url for d in indexer.retrieve("async")}+ bigram_urls = {d.url for d in indexer.retrieve("rust async")}++ # Unigram "rust" matches A and B; "async" matches A and C.+ assert rust_urls == {a.url, b.url}+ assert async_urls == {a.url, c.url}+ # The bigram needs both words present, so only A matches.+ assert bigram_urls == {a.url}++ # Re-indexing the same results adds nothing new.+ assert index_results_against_query(docs, "rust async", index_path) == 0++# ---------------------------------------------------------------------------# _merge_user_ids# ---------------------------------------------------------------------------diff --git a/test/test_super_search.py b/test/test_super_search.pyindex db825f4..471293a 100644--- a/test/test_super_search.py+++ b/test/test_super_search.py@@ -303,6 +303,42 @@ def test_final_results_event_emitted(client, api_key, monkeypatch):assert event_types.index("results") < event_types.index("done")+def test_done_reports_pages_indexed(client, api_key, monkeypatch):+ """Results are indexed at the end and the count is reported in 'done'."""+ import mwmbl.tinysearchengine.super_search as ss++ cache.delete(_super_search_monthly_key(api_key.user.id))+ _stub_sources(monkeypatch, {+ "hn": [Document(title="Python intro", url="https://py.example/", extract="A guide")],+ })+ _stub_scoring(monkeypatch, [0.5] + [0.0] * 20)+ monkeypatch.setattr(+ "mwmbl.tinysearchengine.super_search.crawl_url",+ lambda url: {"url": url, "status": 200, "timestamp": 0, "content": None, "error": None},+ )++ captured = {}++ def fake_index(documents, query, index_path):+ captured["query"] = query+ captured["urls"] = {d.url for d in documents}+ return 4++ monkeypatch.setattr(ss, "index_results_against_query", fake_index)++ response = client.get("/api/v2/super-search/?q=python", HTTP_X_API_KEY=api_key.raw_key)+ assert response.status_code == 200+ events = _parse_sse(_read_stream(response))++ done = next(d for t, d in events if t == "done")+ assert done["reason"] == "complete"+ assert done["pages_indexed"] == 4+ # The collected results are what gets indexed, against the original query.+ assert captured["query"] == "python"+ assert "https://py.example/" in captured["urls"]++@pytest.mark.django_dbdef test_source_failure_emits_source_failed(client, api_key, monkeypatch):cache.delete(_super_search_monthly_key(api_key.user.id))