An open source, non-profit web search engine
Cache Wikipedia results in a dedicated index, off the keystroke path
Daoud Clarkef60ff9740495
diff --git a/.gitignore b/.gitignoreindex bfdff88..4ea090d 100644--- a/.gitignore+++ b/.gitignore@@ -166,6 +166,8 @@ devdata/rankeval-2024-06/remote-datasets/devdata/*.bloomdevdata/*.sqlitedevdata/request_cache/+# Generated by apps.ready(); holds cached Wikipedia responses, not source.+devdata/wiki-cache.tinysearchdevdata/rankeval-*/front-end/node_modules/diff --git a/app.json b/app.jsonindex 6fb409a..5142598 100644--- a/app.json+++ b/app.json@@ -11,7 +11,7 @@"path": "/api/v1/search/?s=rydnik","attempts": 1,"interval": 600,- "grace": 0,+ "grace": 60,"timeout": 10}]diff --git a/mwmbl/apps.py b/mwmbl/apps.pyindex c51665f..87c51f8 100644--- a/mwmbl/apps.py+++ b/mwmbl/apps.py@@ -8,23 +8,37 @@ from mwmbl.database import Databasefrom mwmbl.indexer.indexdb import IndexDatabase-def create_index():+def create_index(index_name, num_pages, rebuild_on_mismatch=False):+ """Create the index file if it is missing, and check an existing one is the right shape.++ rebuild_on_mismatch is for indexes whose contents are disposable. The search index is+ not one of them - a size that disagrees with settings there means somebody changed+ NUM_PAGES against a 400 GB file holding the only copy of the crawl, and refusing to+ start is the right answer. The Wikipedia cache is the opposite case: resizing it should+ be a config change, not a startup crash, and the cost of rebuilding is re-fetching.+ """# Imports here to avoid AppRegistryNotReady exceptionfrom mwmbl.tinysearchengine.indexer import TinyIndex, Document, PAGE_SIZE- index_path = Path(settings.DATA_PATH) / settings.INDEX_NAME+ index_path = Path(settings.DATA_PATH) / index_nametry:existing_index = TinyIndex(item_factory=Document, index_path=index_path)print("======================================")print(f"Found existing index at {index_path}")print("======================================")- if existing_index.page_size != PAGE_SIZE or existing_index.num_pages != settings.NUM_PAGES:- raise ValueError(f"Existing index page sizes ({existing_index.page_size}) or number of pages "- f"({existing_index.num_pages}) do not match")+ if existing_index.page_size != PAGE_SIZE or existing_index.num_pages != num_pages:+ message = (f"Existing index page sizes ({existing_index.page_size}) or number of pages "+ f"({existing_index.num_pages}) do not match")+ if not rebuild_on_mismatch:+ raise ValueError(message)+ print(f"{message} - rebuilding {index_path}")+ index_path.unlink()+ TinyIndex.create(item_factory=Document, index_path=index_path, num_pages=num_pages,+ page_size=PAGE_SIZE)except FileNotFoundError:print("======================================")print("Index not found - creating a new index")print("======================================")- TinyIndex.create(item_factory=Document, index_path=index_path, num_pages=settings.NUM_PAGES,+ TinyIndex.create(item_factory=Document, index_path=index_path, num_pages=num_pages,page_size=PAGE_SIZE)@@ -39,7 +53,11 @@ class MwmblConfig(AppConfig):verbose_name = "Mwmbl Application"def ready(self):- create_index()+ create_index(settings.INDEX_NAME, settings.NUM_PAGES)+ # Note this writes num_pages * 4 KB page by page rather than sparsely, so the first+ # boot after a size change pays for the whole file up front.+ create_index(settings.WIKI_CACHE_INDEX_NAME, settings.WIKI_CACHE_NUM_PAGES,+ rebuild_on_mismatch=True)if settings.HAS_DATABASE:create_index_db()import mwmbl.signals # noqa: F401 - connects the post_save receiversdiff --git a/mwmbl/indexer/blacklist_providers.py b/mwmbl/indexer/blacklist_providers.pyindex 1141948..0ce2c49 100644--- a/mwmbl/indexer/blacklist_providers.py+++ b/mwmbl/indexer/blacklist_providers.py@@ -149,10 +149,11 @@ class RemoteListBlacklistProvider(BlacklistProvider):# cache rooted at settings.REQUEST_CACHE_PATH = f"{DATA_PATH}/request_cache" - the# same volume that holds the multi-hundred-GB index. These blocklists are tens of# megabytes each, so caching them there fills that volume, and once it is full- # *every* user of request_cache breaks - including get_wiki_results(), which runs- # on the normal search path and then retries a live fetch 4 times per uncached- # query (WIKI_RETRY, 5s timeout each) until the worker is killed. A big periodic- # download has no business in a shared small-response cache on the index volume.+ # *every* user of request_cache breaks - and it shares that volume with the index+ # itself. (get_wiki_results() used to be the worst of those, retrying a live fetch+ # 4 times per uncached query on the search path; it now has a cache of its own, see+ # mwmbl.indexer.wiki_cache.) A big periodic download has no business in a shared+ # small-response cache on the index volume.response = requests.get(self.url, timeout=60)response.raise_for_status()diff --git a/mwmbl/indexer/wiki_cache.py b/mwmbl/indexer/wiki_cache.pynew file mode 100644index 0000000..c61f856--- /dev/null+++ b/mwmbl/indexer/wiki_cache.py@@ -0,0 +1,181 @@+"""Wikipedia search results, cached in a TinyIndex of their own.++get_wiki_results() used to cache through mwmbl.utils.request_cache, a requests-cache+*filesystem* session rooted at REQUEST_CACHE_PATH - the same volume as the 400 GB index -+with no LRU, no size cap and nothing ever calling delete(expired=True), so it grew without+bound. Because the stored JSON holds the whole request, it also wrote the raw user query+to disk, where it sat for the length of the expiry.++This is a *separate* index file, not the search index. Caching into the search index was+tried in #357 and measured in #359: a cache entry and a real document compete for the same+4 KB page, and on a dense index storing one evicts about as much as it adds (-0.0054 NDCG+overall, -0.1927 on the queries where it fired). A file of its own also means a cache entry+can never surface in /raw or in the candidate pool for somebody else's query, which is what+lets this module keep a negative-cache sentinel - see WIKI_CACHE_EMPTY_URL.++Entries are keyed by a hash of the query, so the file holds no query text. Be straight+about what that does and does not do: it removes the query *text*, not the fact that+somebody searched in that area, since an entry still holds the articles that came back.+That is strictly less than the disk cache gave away.+"""+import hashlib+import hmac+import time+from logging import getLogger+from pathlib import Path+from typing import Optional++from django.conf import settings++from mwmbl.tinysearchengine.indexer import Document, DocumentState, TinyIndex+from mwmbl.tokenizer import tokenize++logger = getLogger(__name__)+++# Terms under this prefix are cache entries rather than words anybody searched for.+WIKI_CACHE_TERM_PREFIX = "#wiki-"++# A query Wikipedia returned nothing for is stored as a single document under this URL, so+# that "we asked and there was nothing" stays distinguishable from "we never asked".+# Without it those queries are re-fetched forever. It is filtered out on read and never+# leaves this module.+WIKI_CACHE_EMPTY_URL = "mwmbl:wiki-cache-empty"+++def wiki_cache_path() -> Path:+ return Path(settings.DATA_PATH) / settings.WIKI_CACHE_INDEX_NAME+++_cache_index: Optional[TinyIndex] = None+_cache_index_path: Optional[Path] = None+++def get_cache_index() -> TinyIndex:+ """The read handle for this process, opened once and left open.++ Same lifetime as the main index in search_setup - mmap'd read-only for the life of the+ worker. Writers open their own short-lived 'w' handle instead, as every other writer in+ the codebase does; see store_wiki_results.++ Keyed on the path so that override_settings in the tests gets a fresh handle rather+ than whichever index the first test to run happened to open.+ """+ global _cache_index, _cache_index_path+ path = wiki_cache_path()+ if _cache_index is None or _cache_index_path != path:+ if _cache_index is not None:+ _cache_index.__exit__(None, None, None)+ _cache_index = TinyIndex(item_factory=Document, index_path=path)+ _cache_index.__enter__()+ _cache_index_path = path+ return _cache_index+++def wiki_cache_term(query: str) -> str:+ """The term a query's Wikipedia results are cached under.++ Keyed on SECRET_KEY rather than a bare digest: a plain hash of a one- or two-word query+ is trivially brute-forced from a wordlist, so a dump of the file would hand over the+ queries. Keyed, the mapping is not reproducible without the key. Rotating SECRET_KEY+ invalidates the cache, which is harmless - it is a cache.++ The query is normalised through tokenize() first, so "Python" and " python " share an+ entry. The disk cache keyed on the request URL built from the raw string, so they did+ not.+ """+ normalised = " ".join(tokenize(query))+ digest = hmac.new(settings.SECRET_KEY.encode("utf8"), normalised.encode("utf8"), hashlib.sha256)+ return WIKI_CACHE_TERM_PREFIX + digest.hexdigest()[:16]+++def is_fresh(document: Document, now: int) -> bool:+ """Whether a cached document is still within its TTL. Untimestamped means stale."""+ ttl = (settings.WIKI_CACHE_NEGATIVE_TTL_SECONDS if document.url == WIKI_CACHE_EMPTY_URL+ else settings.WIKI_CACHE_TTL_SECONDS)+ return document.last_crawled is not None and now - document.last_crawled < ttl+++def get_cached_wiki_results(query: str, now: Optional[int] = None) -> Optional[list[Document]]:+ """A query's cached Wikipedia results.++ None means we have nothing for this query and should ask Wikipedia. A list - possibly+ empty - means we already asked; an empty one is a query Wikipedia had nothing for.+ """+ if not settings.WIKI_CACHE_ENABLED:+ return None++ now = int(time.time()) if now is None else now+ term = wiki_cache_term(query)+ try:+ stored = get_cache_index().retrieve(term)+ except FileNotFoundError:+ logger.warning("No Wikipedia cache index at %s", wiki_cache_path())+ return None+ except Exception:+ # A cache we cannot read is a cache miss, never a failed search. retrieve() already+ # absorbs an unreadable page; this covers the file itself going away underneath us.+ logger.exception("Could not read the Wikipedia cache index")+ return None++ # retrieve() hands back the whole page, which is shared with every other query that+ # hashes to it, and it also lets through documents with no term at all.+ entries = [document for document in stored if document.term == term and is_fresh(document, now)]+ if not entries:+ return None++ # Handed back with term set to the query, exactly as a live fetch builds them. The+ # hashed term is how the entry is stored, not something the ranker should ever see.+ results = [Document(title=document.title, url=document.url, extract=document.extract,+ score=document.score, term=query, state=document.state)+ for document in entries if document.url != WIKI_CACHE_EMPTY_URL]+ return sorted(results, key=lambda document: -(document.score or 0.0))+++def store_wiki_results(query: str, documents: list[Document], now: Optional[int] = None) -> None:+ """Store a query's Wikipedia results, replacing any existing entry for it.++ Never raises. A cache write that fails costs a re-fetch later; it must not cost a+ search its results.+ """+ if not settings.WIKI_CACHE_ENABLED:+ return++ now = int(time.time()) if now is None else now+ term = wiki_cache_term(query)+ entries = _entries_to_store(term, documents, now)++ try:+ with TinyIndex(item_factory=Document, index_path=wiki_cache_path(), mode='w') as index:+ page_index = index.get_key_page_index(term)+ with index.page(page_index) as page:+ # Newest first. store() drops the tail that does not fit, so ordering by+ # age is what makes eviction fall on the oldest entries on the page.+ # Emphatically not the ranker's ordering, which would evict by relevance.+ # Dropping stale entries here is also the whole of expiry: a page under+ # write pressure cleans itself, and a page nobody rewrites is not under+ # pressure, so there is no sweep to schedule.+ kept = sorted(+ (document for document in page.documents+ if document.term != term and is_fresh(document, now)),+ key=lambda document: -(document.last_crawled or 0))+ stored = page.store(entries + kept)+ if stored < len(entries):+ logger.warning(+ "Wiki cache page %d held only %d of %d entries for one query",+ page_index, stored, len(entries))+ except Exception:+ logger.exception("Could not store Wikipedia results in the cache index")+++def _entries_to_store(term: str, documents: list[Document], now: int) -> list[Document]:+ """The documents to write for this query, or the empty-result sentinel if there are none."""+ usable = [document for document in documents if document.url and document.title]+ if not usable:+ return [Document(title="", url=WIKI_CACHE_EMPTY_URL, extract="", score=0.0, term=term,+ state=DocumentState.FROM_WIKI, last_crawled=now)]++ return [Document(title=document.title, url=document.url, extract=document.extract,+ score=document.score, term=term, state=DocumentState.FROM_WIKI,+ last_crawled=now)+ for document in usable]diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.pyindex faa3566..afc5e15 100644--- a/mwmbl/settings_common.py+++ b/mwmbl/settings_common.py@@ -336,3 +336,13 @@ BLACKLIST_PURGE_BATCH_SIZE = 1000 # documents removed from the index pe# through submissions in batches, so the delay collapses a batch into one rebuild rather# than one per approval - see mwmbl.signals.BLACKLIST_SNAPSHOT_APPROVAL_DELAY_SECONDS = 600++# Wikipedia results are cached in a TinyIndex of their own (see mwmbl.indexer.wiki_cache).+# A dedicated file rather than the search index because a cache entry competing with real+# documents for a shared page evicts them - #359 measured that as a net NDCG loss - and+# because a separate file never enters the candidate pool for anyone else's query.+WIKI_CACHE_ENABLED = os.environ.get("WIKI_CACHE_ENABLED", "true").lower() != "false"+WIKI_CACHE_TTL_SECONDS = 26 * 7 * 24 * 60 * 60 # 6 months; the disk cache kept 10 weeks+# A query Wikipedia has nothing for is worth remembering too, or it is re-fetched forever.+# Shorter, because an article appearing is a likelier change than an existing one moving.+WIKI_CACHE_NEGATIVE_TTL_SECONDS = 7 * 24 * 60 * 60diff --git a/mwmbl/settings_dev.py b/mwmbl/settings_dev.pyindex 48741b7..9b44028 100644--- a/mwmbl/settings_dev.py+++ b/mwmbl/settings_dev.py@@ -22,6 +22,9 @@ INDEX_NAME = 'index-v2.tinysearch'NUM_PAGES = 2560+WIKI_CACHE_INDEX_NAME = 'wiki-cache.tinysearch'+WIKI_CACHE_NUM_PAGES = 2560+URLS_BLOOM_FILTER_PATH = str(Path(DATA_PATH) / "urls-{year}-{month}.bloom")URLS_BLOOM_FILTER_FALLBACK_PATH = str(Path(DATA_PATH) / "urls.bloom")NUM_URLS_IN_BLOOM_FILTER = 100_000diff --git a/mwmbl/settings_prod.py b/mwmbl/settings_prod.pyindex 66a43b6..caf1261 100644--- a/mwmbl/settings_prod.py+++ b/mwmbl/settings_prod.py@@ -31,6 +31,11 @@ INDEX_NAME = 'index-v2-400G.tinysearch'# 400GB indexNUM_PAGES = 102400000+WIKI_CACHE_INDEX_NAME = 'wiki-cache.tinysearch'+# 4GB. ~12 entries fit a 4KB page, but pages are hash-assigned, so keep the load factor+# well under that: this holds a few million queries before collisions start evicting early.+WIKI_CACHE_NUM_PAGES = 1_000_000+URLS_BLOOM_FILTER_PATH = str(Path(DATA_PATH) / "urls-{year}-{month}.bloom")URLS_BLOOM_FILTER_FALLBACK_PATH = str(Path(DATA_PATH) / "urls.bloom")NUM_URLS_IN_BLOOM_FILTER = 200_000_000diff --git a/mwmbl/settings_test.py b/mwmbl/settings_test.pyindex 6d17034..9716918 100644--- a/mwmbl/settings_test.py+++ b/mwmbl/settings_test.py@@ -11,6 +11,8 @@ HAS_DATABASE = FalseDATA_PATH = "/tmp/test_mwmbl_data"INDEX_NAME = "index-v2.tinysearch"NUM_PAGES = 10+WIKI_CACHE_INDEX_NAME = "wiki-cache.tinysearch"+WIKI_CACHE_NUM_PAGES = 10# Use fakeredis for cache so tests don't need a real Redis serverCACHES = {diff --git a/mwmbl/templates/_search_bar.html b/mwmbl/templates/_search_bar.htmlnew file mode 100644index 0000000..279b70a--- /dev/null+++ b/mwmbl/templates/_search_bar.html@@ -0,0 +1,53 @@+{# The search bar, shared by index.html and base.html. It used to be duplicated between+ them and had already drifted, so change it here only. #}+<header class="search-menu compact">+ <a href="/" class="branding">+ <img class="brand-icon" src="/static/images/logo.svg" width="40" height="40" alt="mwmbl logo">+ <span class="brand-title">Mwmbl</span>+ </a>+ <form class="search-bar">+ <i class="ph-magnifying-glass-bold"></i>+ {# Fires on every keystroke and renders index results only - no Wikipedia call. #}+ <input+ type='search'+ name='q'+ class='search-bar-input'+ placeholder='Search on Mwmbl...'+ title='Use "CTRL+K" or "/" to focus.'+ autocomplete='off'+ value='{{ query|default_if_none:"" }}'+ hx-get="/app/home/"+ hx-trigger="keyup changed delay:100ms"+ hx-target=".main"+ hx-sync="closest form:replace"+ >+ {# The same view again, once the query has settled, and this one may call Wikipedia.+ Typing a 15-character query used to cost a Wikipedia call per keystroke to answer a+ single question, and 92% of those prefixes are ones nobody ever searches for, so no+ cache can absorb them.++ It renders the whole fragment rather than injecting wiki results into the existing+ list: result.html's hidden inputs are what hx-include=".result" serialises back to+ _get_documents on a curate, so a partial swap would let an approve fire against a+ truncated document list.++ It lives here in the header rather than inside .main because .main's contents are+ replaced on every keystroke, which would destroy and re-arm this element each time.+ hx-sync on both keeps a slow response from landing on top of a newer fast one. #}+ <span+ class="external-search"+ hx-get="/app/home/?external=1"+ hx-trigger="keyup delay:800ms from:.search-bar-input"+ hx-target=".main"+ hx-include=".search-bar-input"+ hx-sync="closest form:replace"+ ></span>+ </form>+ {% if user.is_authenticated %}+ <p class="login-info">Logged in as {{ user.username }}</p>+ <a class="button" href="/accounts/logout/">Log out</a>+ {% else %}+ <a class="button" href="/accounts/login/">Login</a>+ <a class="button" href="/accounts/signup/">Sign up</a>+ {% endif %}+</header>diff --git a/mwmbl/templates/base.html b/mwmbl/templates/base.htmlindex 289b85b..974b36c 100644--- a/mwmbl/templates/base.html+++ b/mwmbl/templates/base.html@@ -48,34 +48,7 @@<body>{% csrf_token %}<mwmbl-app></mwmbl-app>- <header class="search-menu compact">- <a href="/" class="branding">- <img class="brand-icon" src="/static/images/logo.svg" width="40" height="40" alt="mwmbl logo">- <span class="brand-title">Mwmbl</span>- </a>- <form class="search-bar">- <i class="ph-magnifying-glass-bold"></i>- <input- type='search'- name='q'- class='search-bar-input'- placeholder='Search on Mwmbl...'- title='Use "CTRL+K" or "/" to focus.'- autocomplete='off'- value='{{ query|default_if_none:"" }}'- hx-get="/app/home/"- hx-trigger="keyup changed delay:100ms"- hx-target=".main"- >- </form>- {% if user.is_authenticated %}- <p class="login-info">Logged in as {{ user.username }}</p>- <a class="button" href="/accounts/logout/">Log out</a>- {% else %}- <a class="button" href="/accounts/login/">Login</a>- <a class="button" href="/accounts/signup/">Sign up</a>- {% endif %}- </header>+ {% include "_search_bar.html" %}<main><div class="main">{% block content %}{% endblock %}diff --git a/mwmbl/templates/index.html b/mwmbl/templates/index.htmlindex d8e7f4d..470b834 100644--- a/mwmbl/templates/index.html+++ b/mwmbl/templates/index.html@@ -45,34 +45,7 @@<body>{% csrf_token %}<mwmbl-app></mwmbl-app>- <header class="search-menu compact">- <a href="/" class="branding">- <img class="brand-icon" src="/static/images/logo.svg" width="40" height="40" alt="mwmbl logo">- <span class="brand-title">Mwmbl</span>- </a>- <form class="search-bar">- <i class="ph-magnifying-glass-bold"></i>- <input- type='search'- name='q'- class='search-bar-input'- placeholder='Search on Mwmbl...'- title='Use "CTRL+K" or "/" to focus.'- autocomplete='off'- value='{{ query|default_if_none:"" }}'- hx-get="/app/home/"- hx-trigger="keyup changed delay:100ms"- hx-target=".main"- >- </form>- {% if user.is_authenticated %}- <p class="login-info">Logged in as {{ user.username }}</p>- <a class="button" href="/accounts/logout/">Log out</a>- {% else %}- <a class="button" href="/accounts/login/">Login</a>- <a class="button" href="/accounts/signup/">Sign up</a>- {% endif %}- </header>+ {% include "_search_bar.html" %}<main><div class="main">{% include "home.html" %}diff --git a/mwmbl/tinysearchengine/mmr_rank.py b/mwmbl/tinysearchengine/mmr_rank.pyindex 3659980..6ad6b79 100644--- a/mwmbl/tinysearchengine/mmr_rank.py+++ b/mwmbl/tinysearchengine/mmr_rank.py@@ -89,8 +89,9 @@ class MMRRanker:def __init__(self, ranker: Ranker):self.ranker = ranker- def search(self, s: str, additional_results: list[Document]) -> list[Document]:- return mmr_rerank(self.ranker.search(s, additional_results))+ def search(self, s: str, additional_results: list[Document],+ use_external_search: bool = True) -> list[Document]:+ return mmr_rerank(self.ranker.search(s, additional_results, use_external_search))def complete(self, q: str):return self.ranker.complete(q)diff --git a/mwmbl/tinysearchengine/rank.py b/mwmbl/tinysearchengine/rank.pyindex 5c45595..09ec4b4 100644--- a/mwmbl/tinysearchengine/rank.py+++ b/mwmbl/tinysearchengine/rank.py@@ -7,13 +7,13 @@ import timeimport urllibfrom abc import abstractmethodfrom collections import defaultdict-from datetime import timedeltafrom logging import getLoggerfrom operator import itemgetterfrom pathlib import Pathfrom urllib.parse import urlparseimport numpy as np+import requestsfrom django.conf import settingsfrom requests.adapters import HTTPAdapter, Retryfrom requests.exceptions import RetryError@@ -22,10 +22,11 @@ from mwmbl.format import get_query_regexfrom mwmbl.hn_top_domains_filtered import DOMAINSfrom mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklistfrom mwmbl.indexer.purge_queue import enqueue_for_purge+from mwmbl.indexer.wiki_cache import get_cached_wiki_results, store_wiki_resultsfrom mwmbl.tinysearchengine.completer import Completerfrom mwmbl.tinysearchengine.indexer import TinyIndex, Document, DocumentStatefrom mwmbl.tokenizer import tokenize, get_bigrams-from mwmbl.utils import get_domain, request_cache+from mwmbl.utils import get_domainlogger = getLogger(__name__)@@ -277,8 +278,12 @@ class Ranker:def order_results(self, terms: list[str], pages: list[Document], is_complete: bool):pass- def search(self, s: str, additional_results: list[Document]) -> list[Document]:- results, terms, _ = self.get_results(s, additional_results)+ def search(self, s: str, additional_results: list[Document],+ use_external_search: bool = True) -> list[Document]:+ # use_external_search=False is how the search-as-you-type path avoids a Wikipedia+ # call per keystroke; get_results has taken the flag all along, but only complete()+ # could reach it. See mwmbl.views.+ results, terms, _ = self.get_results(s, additional_results, use_external_search)ranked_results = []seen_urls = set()@@ -428,7 +433,7 @@ WIKI_URL_FORMAT = "https://en.wikipedia.org/wiki/{title}"# calls — e.g. an evaluation run that queries it once per gold query. Retry with# backoff, honouring any Retry-After, so a transient 429 doesn't silently drop a# query's wiki results. Live search never bursts, so this adds no latency in-# normal operation. Successful responses are cached for weeks (see request_cache).+# normal operation. Successful responses are cached for months (see mwmbl.indexer.wiki_cache).WIKI_RETRY = Retry(total=4, backoff_factor=0.5, status_forcelist=(429, 502, 503, 504),allowed_methods=frozenset({"GET"}), respect_retry_after_header=True)@@ -477,15 +482,25 @@ def clean_html(s: str):def get_wiki_results(s: str, max_wiki_results: int) -> list[Document]:+ # MAX_QUERY_CHARS was only ever applied in HeuristicAndWikiRanker, which is the eval+ # ranker - the production LTRRanker path sent the untruncated query straight out.+ query = s[:MAX_QUERY_CHARS]++ # Ahead of the circuit breaker deliberately: a cache hit costs Wikipedia nothing, so it+ # should still be served while we are backing off from a rate limit.+ cached = get_cached_wiki_results(query)+ if cached is not None:+ return cached[:max_wiki_results]+if _wiki_circuit_open():return []- escaped_query = urllib.parse.quote(s, safe='')+ escaped_query = urllib.parse.quote(query, safe='')headers = {- 'User-Agent': 'Mwmbl/0.1.0 (https://mwmbl.org; [email protected]) requests-cache'+ 'User-Agent': 'Mwmbl/0.1.0 (https://mwmbl.org; [email protected])'}try:- with request_cache(timedelta(weeks=10)) as session:+ with requests.Session() as session:session.mount("https://en.wikipedia.org", HTTPAdapter(max_retries=WIKI_RETRY))response = session.get(WIKI_SEARCH_API_URL.format(query=escaped_query), headers=headers, timeout=5)wiki_response = response.json()@@ -512,8 +527,13 @@ def get_wiki_results(s: str, max_wiki_results: int) -> list[Document]:return []wiki_results = [Document(result['title'], get_wiki_url(result['title']), clean_html(result['snippet']),- max_wiki_results + 1 - i, s, state=DocumentState.FROM_WIKI)+ max_wiki_results + 1 - i, query, state=DocumentState.FROM_WIKI)for i, result in enumerate(wiki_response['query']['search'][:max_wiki_results])]++ # Only a well-formed answer is stored, including one with no results in it. Every path+ # above returns [] without storing, so a transient failure is never remembered as+ # "Wikipedia has nothing for this".+ store_wiki_results(query, wiki_results)return wiki_results@@ -530,10 +550,11 @@ class HeuristicAndWikiRanker(HeuristicRanker):self.return_none_if_no_mwmbl_results = return_none_if_no_mwmbl_resultsself.max_wiki_results = max_wiki_results- def search(self, s: str, additional_results: list[Document]) -> list[Document]:+ def search(self, s: str, additional_results: list[Document],+ use_external_search: bool = True) -> list[Document]:s_shortened = s[:MAX_QUERY_CHARS]- wiki_results = get_wiki_results(s_shortened, self.max_wiki_results)+ wiki_results = get_wiki_results(s_shortened, self.max_wiki_results) if use_external_search else []results = super().search(s_shortened, additional_results=wiki_results)if len(results) == 0 and self.return_none_if_no_mwmbl_results:diff --git a/mwmbl/views.py b/mwmbl/views.pyindex 1cc295f..8706101 100644--- a/mwmbl/views.py+++ b/mwmbl/views.py@@ -78,7 +78,7 @@ def _prepare_results(results: Optional[list[Document]]) -> Optional[dict[str, lidef index(request):- activity, query, results = _get_results_and_activity(request)+ activity, query, results = _get_results_and_activity(request, use_external_search=True)return render(request, "index.html", {"results": _prepare_results(results),"query": query,@@ -89,7 +89,12 @@ def index(request):def home_fragment(request):- activity, query, results = _get_results_and_activity(request)+ # Two triggers reach this view. The one on every keystroke asks for index results only;+ # a second, longer-debounced one passes external=1 once the query has settled, and that+ # is the only one that may call Wikipedia. Without the split, typing a 15-character+ # query cost us a dozen Wikipedia calls to answer one question - see mwmbl.templates.+ use_external_search = request.GET.get("external") == "1"+ activity, query, results = _get_results_and_activity(request, use_external_search)response = render(request, "home.html", {"results": _prepare_results(results),"query": query,@@ -106,7 +111,7 @@ def home_fragment(request):return response-def _get_results_and_activity(request):+def _get_results_and_activity(request, use_external_search: bool):query = request.GET.get("q")if query:# There may be extra results in the request that we need to add in@@ -124,7 +129,8 @@ def _get_results_and_activity(request):for i, (title, url, extract) in enumerate(zip(titles, urls, extracts))]- results = ranker.search(query, additional_results=additional_results)+ results = ranker.search(query, additional_results=additional_results,+ use_external_search=use_external_search)activity = Noneelse:results = Nonediff --git a/test/test_mmr_rank.py b/test/test_mmr_rank.pyindex 11befbc..1da7804 100644--- a/test/test_mmr_rank.py+++ b/test/test_mmr_rank.py@@ -64,8 +64,8 @@ class _FakeRanker:self.completed = Noneself.raw_queried = None- def search(self, s, additional_results):- self.searched = (s, additional_results)+ def search(self, s, additional_results, use_external_search=True):+ self.searched = (s, additional_results, use_external_search)return self._resultsdef complete(self, q):diff --git a/test/test_rank.py b/test/test_rank.pyindex dbd2117..05055e6 100644--- a/test/test_rank.py+++ b/test/test_rank.py@@ -1,6 +1,7 @@from unittest.mock import MagicMock, patchimport pytest+from django.test import override_settingsfrom requests.exceptions import RetryErrorfrom urllib3.exceptions import MaxRetryError, ResponseError@@ -70,8 +71,11 @@ def _reset_wiki_circuit():def _get_wiki_results_with_session(session):- with patch.object(rank, "request_cache") as mock_request_cache:- mock_request_cache.return_value.__enter__.return_value = session+ # The cache is off in these tests: they are about what the fetch does when Wikipedia+ # misbehaves, and a hit would return before the fetch ever ran.+ with override_settings(WIKI_CACHE_ENABLED=False), \+ patch.object(rank.requests, "Session") as mock_session:+ mock_session.return_value.__enter__.return_value = sessionreturn get_wiki_results("query", 5)@@ -109,10 +113,11 @@ def test_wiki_query_text_containing_429_is_not_mistaken_for_rate_limit():def test_open_wiki_circuit_short_circuits_without_calling_wikipedia():rank._trip_wiki_circuit()- with patch.object(rank, "request_cache") as mock_request_cache:+ with override_settings(WIKI_CACHE_ENABLED=False), \+ patch.object(rank.requests, "Session") as mock_session:results = get_wiki_results("query", 5)- mock_request_cache.assert_not_called()+ mock_session.assert_not_called()assert results == []diff --git a/test/test_wiki_cache.py b/test/test_wiki_cache.pynew file mode 100644index 0000000..988cb24--- /dev/null+++ b/test/test_wiki_cache.py@@ -0,0 +1,436 @@+"""Tests for the dedicated Wikipedia cache index (mwmbl.indexer.wiki_cache).++Where these overlap with the tests on the #357 branch they are deliberately the same+assertions - the term derivation and the freshness rule are carried over unchanged. What is+gone is everything that existed only because cache entries shared a file with real index+content: the anonymisation gate, the Redis queue, the general-indexing path, and the guards+stopping a cache term reaching curation or /raw.+"""+import random+import string+import time+from unittest.mock import MagicMock, patch++import pytest+from django.test import override_settings++from mwmbl.apps import create_index+from mwmbl.indexer.wiki_cache import (+ WIKI_CACHE_EMPTY_URL,+ WIKI_CACHE_TERM_PREFIX,+ get_cached_wiki_results,+ is_fresh,+ store_wiki_results,+ wiki_cache_path,+ wiki_cache_term,+)+from mwmbl.tinysearchengine import rank+from mwmbl.tinysearchengine.indexer import PAGE_SIZE, Document, DocumentState, TinyIndex+from mwmbl.tinysearchengine.rank import Ranker, get_wiki_results++NUM_PAGES = 8++PYTHON = Document("Python (programming language)", "https://en.wikipedia.org/wiki/Python",+ "A high-level programming language.", 3.0)+MONTY = Document("Monty Python", "https://en.wikipedia.org/wiki/Monty_Python",+ "A British comedy troupe.", 2.0)+++def cache_index(tmp_path):+ """A real, empty wiki cache index that the module-level helpers will pick up."""+ with override_settings(DATA_PATH=str(tmp_path), WIKI_CACHE_INDEX_NAME="wiki-cache.tinysearch",+ WIKI_CACHE_NUM_PAGES=NUM_PAGES, WIKI_CACHE_ENABLED=True):+ TinyIndex.create(item_factory=Document, index_path=str(wiki_cache_path()),+ num_pages=NUM_PAGES, page_size=PAGE_SIZE)+ yield str(wiki_cache_path())+++def _wiki_api_response(*titles):+ return {"query": {"search": [{"title": title, "snippet": f"<b>{title}</b> snippet"}+ for title in titles]}}+++def _patched_wikipedia(response):+ """Stand in for the Wikipedia API, returning `response` (or raising, if it is an error)."""+ session = MagicMock()+ if isinstance(response, Exception):+ session.get.side_effect = response+ else:+ session.get.return_value.json.return_value = response+ mock = patch.object(rank.requests, "Session")+ started = mock.start()+ started.return_value.__enter__.return_value = session+ return mock, session+++# ---------------------------------------------------------------------------+# The cache term+# ---------------------------------------------------------------------------++def test_cache_term_is_stable_and_normalised():+ """Whitespace and case must not split one query across several entries. The disk cache+ keyed on the raw request URL, so " python " and "Python" missed each other."""+ assert wiki_cache_term("python") == wiki_cache_term(" PYTHON ")+ assert wiki_cache_term("monty python") == wiki_cache_term("Monty Python")+ assert wiki_cache_term("python") != wiki_cache_term("monty python")+++def test_cache_term_does_not_contain_the_query():+ term = wiki_cache_term("something private")+ assert term.startswith(WIKI_CACHE_TERM_PREFIX)+ assert "something" not in term+ assert "private" not in term+++def test_cache_term_is_keyed_so_it_cannot_be_recomputed_without_the_secret():+ """A bare digest of a one-word query is brute-forceable from a wordlist; keyed on+ SECRET_KEY the term->query mapping is not reproducible without the key."""+ with override_settings(SECRET_KEY="one"):+ first = wiki_cache_term("bananas")+ with override_settings(SECRET_KEY="two"):+ second = wiki_cache_term("bananas")++ assert first != second+++# ---------------------------------------------------------------------------+# Round trip+# ---------------------------------------------------------------------------++def test_results_come_back_from_the_index(cache_index):+ store_wiki_results("python", [PYTHON, MONTY])++ cached = get_cached_wiki_results("python")++ assert [document.url for document in cached] == [PYTHON.url, MONTY.url] # descending score+ assert [document.score for document in cached] == [3.0, 2.0]+ assert all(document.state == DocumentState.FROM_WIKI for document in cached)+++def test_a_hit_is_indistinguishable_from_a_live_fetch(cache_index):+ """The hashed term is a storage detail. Handing it to the ranker would make a cached+ result differ from the identical one fetched live."""+ store_wiki_results("python", [PYTHON])++ cached = get_cached_wiki_results("python")++ assert [document.term for document in cached] == ["python"]+++def test_a_normalised_variant_of_the_query_hits_the_same_entry(cache_index):+ store_wiki_results("Monty Python", [MONTY])++ assert get_cached_wiki_results(" monty python ") is not None+++def test_a_query_we_have_never_asked_about_is_a_miss(cache_index):+ store_wiki_results("python", [PYTHON])++ assert get_cached_wiki_results("something else entirely") is None+++def test_the_file_holds_no_query_text(cache_index):+ store_wiki_results("something private", [PYTHON])++ with open(cache_index, "rb") as index_file:+ raw = index_file.read()++ assert b"something private" not in raw+++# ---------------------------------------------------------------------------+# Freshness+# ---------------------------------------------------------------------------++def test_a_stale_entry_is_not_a_cache_hit(cache_index):+ now = int(time.time())+ store_wiki_results("python", [PYTHON], now=now)++ fresh = get_cached_wiki_results("python", now=now + 60)+ stale = get_cached_wiki_results("python", now=now + 27 * 7 * 24 * 60 * 60)++ assert fresh is not None+ assert stale is None+++def test_an_untimestamped_document_is_stale():+ """A document with no last_crawled predates the cache or came from somewhere else;+ treating it as fresh would pin it forever."""+ assert not is_fresh(Document("t", "u", "e", 1.0), int(time.time()))+++def test_stale_entries_are_dropped_when_the_page_is_rewritten(cache_index):+ """Expiry is entirely this: a page under write pressure cleans itself, so there is no+ sweep to schedule and nothing accumulates on a page nobody writes to."""+ now = int(time.time())+ old_query, new_query = _colliding_queries(cache_index)+ store_wiki_results(old_query, [PYTHON], now=now)++ much_later = now + 27 * 7 * 24 * 60 * 60+ store_wiki_results(new_query, [MONTY], now=much_later)++ with TinyIndex(Document, cache_index, 'r') as index:+ page = index.get_page(index.get_key_page_index(wiki_cache_term(new_query)))++ assert [document.url for document in page] == [MONTY.url]+++# ---------------------------------------------------------------------------+# Negative caching+# ---------------------------------------------------------------------------++def test_a_query_wikipedia_has_nothing_for_is_remembered(cache_index):+ """Without this the query is re-fetched forever - #357 listed it as unfixable, because+ a sentinel in the search index would surface in /raw and in every candidate list."""+ store_wiki_results("nonsense query", [])++ assert get_cached_wiki_results("nonsense query") == []+++def test_an_empty_entry_is_not_returned_as_a_result(cache_index):+ store_wiki_results("nonsense query", [])++ cached = get_cached_wiki_results("nonsense query")++ assert [document.url for document in cached] == []+ assert WIKI_CACHE_EMPTY_URL not in [document.url for document in cached]+++def test_an_empty_entry_expires_sooner_than_a_real_one(cache_index):+ """An article appearing is a likelier change than an existing one moving."""+ now = int(time.time())+ store_wiki_results("nonsense query", [], now=now)+ store_wiki_results("python", [PYTHON], now=now)++ later = now + 8 * 24 * 60 * 60 # past the negative TTL, well inside the positive one++ assert get_cached_wiki_results("nonsense query", now=later) is None+ assert get_cached_wiki_results("python", now=later) is not None+++def test_documents_without_a_url_or_title_are_not_stored(cache_index):+ store_wiki_results("python", [Document("", "", "", 1.0)])++ assert get_cached_wiki_results("python") == []+++# ---------------------------------------------------------------------------+# The fetch path+# ---------------------------------------------------------------------------++def test_a_cache_miss_calls_wikipedia_and_stores_the_result(cache_index):+ mock, session = _patched_wikipedia(_wiki_api_response("Python (programming language)"))+ try:+ results = get_wiki_results("python", 3)+ finally:+ mock.stop()++ assert session.get.call_count == 1+ assert [document.url for document in results] == ["https://en.wikipedia.org/wiki/Python_(programming_language)"]+ assert get_cached_wiki_results("python") is not None+++def test_a_cache_hit_does_not_call_wikipedia(cache_index):+ store_wiki_results("python", [PYTHON])++ mock, session = _patched_wikipedia(_wiki_api_response("Python"))+ try:+ results = get_wiki_results("python", 3)+ finally:+ mock.stop()++ assert session.get.call_count == 0+ assert [document.url for document in results] == [PYTHON.url]+++def test_a_hit_is_served_while_the_circuit_breaker_is_open(cache_index):+ """A cached answer costs Wikipedia nothing, so backing off from a rate limit is no+ reason to withhold it."""+ store_wiki_results("python", [PYTHON])+ rank._trip_wiki_circuit()+ try:+ results = get_wiki_results("python", 3)+ finally:+ rank._wiki_blocked_until = 0.0++ assert [document.url for document in results] == [PYTHON.url]+++def test_a_failed_fetch_is_not_remembered_as_an_empty_result(cache_index):+ """Only a well-formed answer from Wikipedia is worth storing. Caching a transient+ failure would suppress the query for a week."""+ mock, _ = _patched_wikipedia(ValueError("connection reset"))+ try:+ assert get_wiki_results("python", 3) == []+ finally:+ mock.stop()++ assert get_cached_wiki_results("python") is None+++def test_an_error_response_is_not_remembered_as_an_empty_result(cache_index):+ mock, _ = _patched_wikipedia({"error": {"code": "whatever"}})+ try:+ assert get_wiki_results("python", 3) == []+ finally:+ mock.stop()++ assert get_cached_wiki_results("python") is None+++def test_a_broken_cache_write_does_not_break_the_search(cache_index):+ """A cache write that fails costs a re-fetch later. It must not cost a search its+ results."""+ mock, _ = _patched_wikipedia(_wiki_api_response("Python"))+ try:+ with patch("mwmbl.indexer.wiki_cache.TinyIndex", side_effect=OSError("disk gone")):+ results = get_wiki_results("python", 3)+ finally:+ mock.stop()++ assert len(results) == 1+++def test_the_query_is_truncated_before_it_reaches_wikipedia(cache_index):+ """MAX_QUERY_CHARS was applied only in HeuristicAndWikiRanker, which is the eval ranker;+ the production LTRRanker path sent the whole thing."""+ mock, session = _patched_wikipedia(_wiki_api_response("Python"))+ try:+ get_wiki_results("x" * 500, 3)+ finally:+ mock.stop()++ requested_url = session.get.call_args[0][0]+ assert "x" * rank.MAX_QUERY_CHARS in requested_url+ assert "x" * (rank.MAX_QUERY_CHARS + 1) not in requested_url+++# ---------------------------------------------------------------------------+# The kill switch+# ---------------------------------------------------------------------------++def test_the_kill_switch_stops_reads_and_writes(cache_index):+ with override_settings(WIKI_CACHE_ENABLED=False):+ store_wiki_results("python", [PYTHON])+ assert get_cached_wiki_results("python") is None++ assert get_cached_wiki_results("python") is None+++def test_a_missing_cache_file_is_a_miss_rather_than_an_error(tmp_path):+ with override_settings(DATA_PATH=str(tmp_path), WIKI_CACHE_INDEX_NAME="absent.tinysearch",+ WIKI_CACHE_ENABLED=True):+ assert get_cached_wiki_results("python") is None+++# ---------------------------------------------------------------------------+# Page competition+# ---------------------------------------------------------------------------++def _colliding_queries(index_path):+ """Two queries whose cache terms land on the same page."""+ with TinyIndex(Document, index_path, 'r') as index:+ first = "collide-0"+ first_page = index.get_key_page_index(wiki_cache_term(first))+ for i in range(1, 10000):+ candidate = f"collide-{i}"+ if index.get_key_page_index(wiki_cache_term(candidate)) == first_page:+ return first, candidate+ raise AssertionError("No colliding query found")+++def _filler(size):+ """Incompressible text. Repeated filler zstd-compresses away and the page never fills."""+ return "".join(random.choices(string.ascii_letters, k=size))+++def test_the_newest_entry_survives_a_full_page_and_the_oldest_is_evicted(cache_index):+ """store() drops the tail that does not fit, so entries are written newest-first. That+ ordering is the whole of the eviction policy - and it is deliberately not the ranker's+ ordering, which would evict by relevance instead of by age."""+ old_query, new_query = _colliding_queries(cache_index)+ now = int(time.time())+ bulky = [Document(f"Title {i}", f"https://en.wikipedia.org/wiki/{i}", _filler(2000), 3.0)+ for i in range(4)]++ store_wiki_results(old_query, bulky, now=now)+ assert get_cached_wiki_results(old_query, now=now) is not None++ store_wiki_results(new_query, bulky, now=now + 1)++ assert get_cached_wiki_results(new_query, now=now + 1) is not None+ assert get_cached_wiki_results(old_query, now=now + 1) is None+++def test_an_entry_replaces_its_own_previous_results(cache_index):+ store_wiki_results("python", [PYTHON, MONTY])+ store_wiki_results("python", [MONTY])++ assert [document.url for document in get_cached_wiki_results("python")] == [MONTY.url]+++# ---------------------------------------------------------------------------+# Keeping Wikipedia off the keystroke path+# ---------------------------------------------------------------------------++class _RecordingRanker(Ranker):+ """The smallest thing that exercises Ranker.search's external_search plumbing, which is+ what LTRRanker inherits and what the production ranker therefore uses."""++ def __init__(self, tiny_index):+ super().__init__(tiny_index, completer=MagicMock(**{"complete.return_value": []}))+ self.external_search_calls = []++ def order_results(self, terms, pages, is_complete):+ return pages++ def external_search(self, q):+ self.external_search_calls.append(q)+ return []+++def test_search_does_not_call_external_search_when_it_is_turned_off(cache_index):+ """The search-as-you-type trigger passes use_external_search=False. Typing a+ 15-character query otherwise costs a Wikipedia call per keystroke, and 92% of those+ prefixes are ones nobody ever searches for, so no cache can absorb them."""+ with TinyIndex(Document, cache_index, 'r') as index:+ ranker = _RecordingRanker(index)+ ranker.search("python", [], use_external_search=False)++ assert ranker.external_search_calls == []+++def test_search_calls_external_search_by_default(cache_index):+ with TinyIndex(Document, cache_index, 'r') as index:+ ranker = _RecordingRanker(index)+ ranker.search("python", [])++ assert ranker.external_search_calls == ["python"]+++# ---------------------------------------------------------------------------+# Bootstrap+# ---------------------------------------------------------------------------++def test_a_resized_cache_index_is_rebuilt_rather_than_crashing_startup(tmp_path):+ """Resizing a cache should be a config change, not a startup crash - the cost of+ rebuilding is re-fetching."""+ path = tmp_path / "wiki-cache.tinysearch"+ TinyIndex.create(item_factory=Document, index_path=str(path), num_pages=4, page_size=PAGE_SIZE)++ with override_settings(DATA_PATH=str(tmp_path)):+ create_index("wiki-cache.tinysearch", 16, rebuild_on_mismatch=True)++ with TinyIndex(Document, str(path), 'r') as index:+ assert index.num_pages == 16+++def test_a_resized_search_index_still_refuses_to_start(tmp_path):+ """The search index is the opposite case: a size that disagrees with settings means+ somebody changed NUM_PAGES against the only copy of the crawl."""+ path = tmp_path / "index.tinysearch"+ TinyIndex.create(item_factory=Document, index_path=str(path), num_pages=4, page_size=PAGE_SIZE)++ with override_settings(DATA_PATH=str(tmp_path)), pytest.raises(ValueError):+ create_index("index.tinysearch", 16)