An open source, non-profit web search engine
Stop live search waiting out Wikipedia's rate limit
Claude1f2a91815687
diff --git a/mwmbl/rankeval/evaluation/compare_combined_providers.py b/mwmbl/rankeval/evaluation/compare_combined_providers.pyindex 36ac9eb..f3f95d8 100644--- a/mwmbl/rankeval/evaluation/compare_combined_providers.py+++ b/mwmbl/rankeval/evaluation/compare_combined_providers.py@@ -204,7 +204,7 @@ def collect(dataset: pd.DataFrame, fraction: float, include_brave: bool, judge:continuegold = gold_scores_for(rankings)staan_docs = get_staan_results(query)- wiki_docs = get_wiki_results(query)+ wiki_docs = get_wiki_results(query, wait_out_rate_limits=True)lists = {name: arm(query, staan_docs, wiki_docs) for name, arm in arms.items()}pool = {result["url"]: result for results in lists.values() for result in results}diff --git a/mwmbl/tinysearchengine/rank.py b/mwmbl/tinysearchengine/rank.pyindex 3aac63a..bf894ee 100644--- a/mwmbl/tinysearchengine/rank.py+++ b/mwmbl/tinysearchengine/rank.py@@ -2,8 +2,6 @@ import htmlimport jsonimport mathimport re-import threading-import timeimport urllibfrom abc import abstractmethodfrom collections import defaultdict@@ -16,8 +14,8 @@ from urllib.parse import urlparseimport numpy as npimport requestsfrom django.conf import settings+from django.core.cache import cachefrom requests.adapters import HTTPAdapter, Retry-from requests.exceptions import RetryErrorfrom mwmbl.format import get_query_regexfrom mwmbl.hn_top_domains_filtered import DOMAINS@@ -527,11 +525,15 @@ WIKI_FETCH_LIMIT = NUM_WIKI_RESULTS# on (max_wiki_results=5 there). Changing it changes a trained-on feature: retrain.WIKI_TOP_SCORE = 6.0-# Wikipedia rate-limits (HTTP 429, with a non-JSON body) bursts of search-API-# 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 months (see mwmbl.indexer.external_cache).+# Live search does not retry Wikipedia. It used to retry 429s, honouring Retry-After, on+# the theory that live search never bursts - but it does, and in October 2026 Wikipedia+# answered about three calls in four with a 429 and a Retry-After of tens of seconds. Each+# such search slept through every retry, over a minute in all, and since sync views share+# one thread per worker, every request queued behind it waited too: searches, page loads,+# and the token refreshes whose failure logs users out.+#+# Evaluation runs can afford to wait, and need the results they would otherwise drop, so+# they opt into this with wait_out_rate_limits.WIKI_RETRY = Retry(total=4,backoff_factor=0.5,@@ -540,41 +542,38 @@ WIKI_RETRY = Retry(respect_retry_after_header=True,)-# If Wikipedia has already rate-limited us hard enough that WIKI_RETRY exhausted its-# retries, hammering it again on the very next query just makes things worse. Trip a-# process-local circuit breaker instead: stop calling Wikipedia for a cooldown period-# and let the rate limit clear, rather than every subsequent request paying for its own-# doomed retry-with-backoff sequence.-WIKI_CIRCUIT_COOLDOWN_SECONDS = 60-_wiki_circuit_lock = threading.Lock()-_wiki_blocked_until = 0.0+WIKI_TIMEOUT_SECONDS = 5++# A 429 pauses every live Wikipedia call for as long as Wikipedia asks. Held in Redis rather+# than per process, so that one worker's 429 spares the others from collecting their own.+WIKI_CIRCUIT_KEY = "wiki-circuit-open"+WIKI_CIRCUIT_DEFAULT_SECONDS = 60+# A Retry-After this long is more likely a mistake than a request; don't let one switch+# Wikipedia off for the day.+WIKI_CIRCUIT_MAX_SECONDS = 600def _wiki_circuit_open() -> bool:- return time.monotonic() < _wiki_blocked_until+ return cache.get(WIKI_CIRCUIT_KEY) is not None-def _trip_wiki_circuit():- global _wiki_blocked_until- with _wiki_circuit_lock:- _wiki_blocked_until = time.monotonic() + WIKI_CIRCUIT_COOLDOWN_SECONDS+def _trip_wiki_circuit(seconds: int):+ cache.set(WIKI_CIRCUIT_KEY, 1, timeout=seconds)-def get_wiki_url(title: str):- return WIKI_URL_FORMAT.format(title=title.replace(" ", "_"))+def _wiki_cooldown_seconds(response: requests.Response) -> int:+ """How long to pause for, from the 429's Retry-After.+ Retry-After may also be an HTTP date; Wikipedia sends seconds, so anything else gets+ the default rather than a date parser.+ """+ retry_after = response.headers.get("Retry-After", "")+ seconds = int(retry_after) if retry_after.isdigit() else WIKI_CIRCUIT_DEFAULT_SECONDS+ return min(max(seconds, 1), WIKI_CIRCUIT_MAX_SECONDS)-def _is_wiki_rate_limited(e: RetryError) -> bool:- """True if a RetryError was caused by exhausting retries on 429s specifically.- Inspects the wrapped MaxRetryError's `reason` (e.g. "too many 429 error- responses") rather than str(e). str(e) also embeds the request URL - and with- it the user's (private) query - which both risks logging it and means a query- that happens to contain the substring "429" would be misread as a rate limit.- """- cause = e.args[0] if e.args else None- reason = getattr(cause, "reason", None)- return reason is not None and "429" in str(reason)+def get_wiki_url(title: str):+ return WIKI_URL_FORMAT.format(title=title.replace(" ", "_"))HTML_TAG_REGEX = re.compile(r"<[^>]+>")@@ -589,7 +588,9 @@ def wiki_score(rank: int) -> float:return WIKI_TOP_SCORE - rank-def get_wiki_results(s: str, max_wiki_results: int = NUM_WIKI_RESULTS) -> list[Document]:+def get_wiki_results(+ s: str, max_wiki_results: int = NUM_WIKI_RESULTS, *, wait_out_rate_limits: bool = False+) -> 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]@@ -606,27 +607,26 @@ def get_wiki_results(s: str, max_wiki_results: int = NUM_WIKI_RESULTS) -> list[Ddocument.score = wiki_score(rank)return wiki_results- if _wiki_circuit_open():+ if not wait_out_rate_limits and _wiki_circuit_open():return []escaped_query = urllib.parse.quote(query, safe="")headers = {"User-Agent": "Mwmbl/0.1.0 (https://mwmbl.org; [email protected])"}try:with requests.Session() as session:- session.mount("https://en.wikipedia.org", HTTPAdapter(max_retries=WIKI_RETRY))+ if wait_out_rate_limits:+ session.mount("https://en.wikipedia.org", HTTPAdapter(max_retries=WIKI_RETRY))response = session.get(- WIKI_SEARCH_API_URL.format(query=escaped_query, limit=WIKI_FETCH_LIMIT), headers=headers, timeout=5+ WIKI_SEARCH_API_URL.format(query=escaped_query, limit=WIKI_FETCH_LIMIT),+ headers=headers,+ timeout=WIKI_TIMEOUT_SECONDS,)+ if response.status_code == 429:+ cooldown_seconds = _wiki_cooldown_seconds(response)+ _trip_wiki_circuit(cooldown_seconds)+ logger.warning("Wikipedia is rate-limiting us; pausing wiki lookups for %ds", cooldown_seconds)+ return []wiki_response = response.json()- except RetryError as e:- if _is_wiki_rate_limited(e):- _trip_wiki_circuit()- logger.warning("Wikipedia is rate-limiting us; pausing wiki lookups for %ds", WIKI_CIRCUIT_COOLDOWN_SECONDS)- else:- # Don't log str(e)/exc_info here - RetryError embeds the request URL, which- # embeds the (private) user query, and logger.exception would log both.- logger.warning("Failed to fetch Wikipedia results: %s", type(e).__name__)- return []except Exception as e:logger.warning("Failed to fetch Wikipedia results: %s", type(e).__name__)return []diff --git a/scripts/combined_search_haiku/wiki_pool.py b/scripts/combined_search_haiku/wiki_pool.pyindex 6473a7f..bc846de 100644--- a/scripts/combined_search_haiku/wiki_pool.py+++ b/scripts/combined_search_haiku/wiki_pool.py@@ -16,7 +16,7 @@ judge = Judge(Path(settings.SUPER_SEARCH_JUDGE_MODEL_DIR))out = {}for r in rows:q = r["query"]- docs = get_wiki_results(q)+ docs = get_wiki_results(q, wait_out_rate_limits=True)scores = judge.score(q, [doc_text(d.title, d.extract) for d in docs]) if docs else []out[q] = [{"url": d.url, "title": d.title, "extract": d.extract, "minilm": float(s)} for d, s in zip(docs, scores)]json.dump(out, open("devdata/combined_providers_eval/engb/wiki_pool.json", "w"))diff --git a/test/test_external_cache.py b/test/test_external_cache.pyindex 801ac4b..d1735cb 100644--- a/test/test_external_cache.py+++ b/test/test_external_cache.py@@ -15,6 +15,7 @@ from pathlib import Pathfrom unittest.mock import MagicMock, patchimport pytest+from django.core.cache import cachefrom django.test import override_settingsfrom mwmbl.apps import create_index@@ -505,11 +506,11 @@ 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 noreason to withhold it."""store_external_results(DocumentSource.WIKIPEDIA, "python", [PYTHON])- rank._trip_wiki_circuit()+ rank._trip_wiki_circuit(60)try:results = get_wiki_results("python", 3)finally:- rank._wiki_blocked_until = 0.0+ cache.delete(rank.WIKI_CIRCUIT_KEY)assert [document.url for document in results] == [PYTHON.url]diff --git a/test/test_rank.py b/test/test_rank.pyindex 4b3ed70..dfe816f 100644--- a/test/test_rank.py+++ b/test/test_rank.py@@ -3,9 +3,8 @@ from pathlib import Pathfrom unittest.mock import MagicMock, patchimport pytest+from django.core.cache import cachefrom django.test import override_settings-from requests.exceptions import RetryError-from urllib3.exceptions import MaxRetryError, ResponseErrorfrom mwmbl.tinysearchengine import rankfrom mwmbl.tinysearchengine.indexer import Document, DocumentSource@@ -103,62 +102,81 @@ def test_a_staan_copy_from_the_index_keeps_its_source():assert result.source == DocumentSource.STAAN_INDEXED-def _make_retry_error(status_code: int) -> RetryError:- reason = ResponseError(f"too many {status_code} error responses")- max_retry_error = MaxRetryError(- pool=None, url="https://en.wikipedia.org/w/api.php?srsearch=secret-query", reason=reason- )- return RetryError(max_retry_error)--@pytest.fixture(autouse=True)def _reset_wiki_circuit():- rank._wiki_blocked_until = 0.0+ cache.delete(rank.WIKI_CIRCUIT_KEY)yield- rank._wiki_blocked_until = 0.0+ cache.delete(rank.WIKI_CIRCUIT_KEY)+++def _wiki_response(status_code: int, headers: dict | None = None) -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.headers = headers or {}+ response.json.return_value = {"query": {"search": []}}+ return response-def _get_wiki_results_with_session(session):+def _get_wiki_results_with_session(session, **kwargs):# 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(EXTERNAL_CACHE_ENABLED=False), patch.object(rank.requests, "Session") as mock_session:mock_session.return_value.__enter__.return_value = session- return get_wiki_results("query", 5)+ return get_wiki_results("query", 5, **kwargs)-def test_wiki_429_retry_error_trips_circuit_breaker():+def test_a_wiki_429_trips_the_circuit_for_as_long_as_retry_after_says():session = MagicMock()- session.get.side_effect = _make_retry_error(429)+ session.get.return_value = _wiki_response(429, {"Retry-After": "43"})- results = _get_wiki_results_with_session(session)+ with patch.object(rank.cache, "set") as cache_set:+ results = _get_wiki_results_with_session(session)assert results == []- assert rank._wiki_circuit_open()+ cache_set.assert_called_once_with(rank.WIKI_CIRCUIT_KEY, 1, timeout=43)-def test_wiki_non_429_retry_error_does_not_trip_circuit_breaker():+def test_live_search_does_not_retry_or_wait_on_a_wiki_429():+ """Regression: retrying with Retry-After held a search for over a minute, and with it+ every request queued on the same worker."""session = MagicMock()- session.get.side_effect = _make_retry_error(503)+ session.get.return_value = _wiki_response(429, {"Retry-After": "43"})- results = _get_wiki_results_with_session(session)+ _get_wiki_results_with_session(session)- assert results == []- assert not rank._wiki_circuit_open()+ session.mount.assert_not_called()+ assert session.get.call_count == 1+ assert rank._wiki_circuit_open()+++ ("retry_after", "expected"),+ [+ ("11", 11),+ ("0", 1),+ ("86400", rank.WIKI_CIRCUIT_MAX_SECONDS),+ ("Wed, 21 Oct 2026 07:28:00 GMT", rank.WIKI_CIRCUIT_DEFAULT_SECONDS),+ (None, rank.WIKI_CIRCUIT_DEFAULT_SECONDS),+ ],+)+def test_the_cooldown_comes_from_retry_after_within_bounds(retry_after, expected):+ headers = {} if retry_after is None else {"Retry-After": retry_after}+ assert rank._wiki_cooldown_seconds(_wiki_response(429, headers)) == expected-def test_wiki_query_text_containing_429_is_not_mistaken_for_rate_limit():- # Regression: matching on str(e) (which embeds the request URL/query) meant a- # query merely containing "429" could be misread as a 429 rate limit.++def test_a_wiki_error_other_than_429_does_not_trip_the_circuit():session = MagicMock()- session.get.side_effect = _make_retry_error(503)+ session.get.side_effect = ConnectionError("reset")- _get_wiki_results_with_session(session)+ results = _get_wiki_results_with_session(session)+ assert results == []assert not rank._wiki_circuit_open()def test_open_wiki_circuit_short_circuits_without_calling_wikipedia():- rank._trip_wiki_circuit()+ rank._trip_wiki_circuit(60)with override_settings(EXTERNAL_CACHE_ENABLED=False), patch.object(rank.requests, "Session") as mock_session:results = get_wiki_results("query", 5)@@ -167,12 +185,16 @@ def test_open_wiki_circuit_short_circuits_without_calling_wikipedia():assert results == []-def test_is_wiki_rate_limited_detects_429_reason():- assert rank._is_wiki_rate_limited(_make_retry_error(429))+def test_waiting_out_rate_limits_retries_and_ignores_the_circuit():+ """Evaluation runs would rather wait than lose a query's wiki results."""+ rank._trip_wiki_circuit(60)+ session = MagicMock()+ session.get.return_value = _wiki_response(200)+ _get_wiki_results_with_session(session, wait_out_rate_limits=True)-def test_is_wiki_rate_limited_ignores_non_429_reason():- assert not rank._is_wiki_rate_limited(_make_retry_error(503))+ session.mount.assert_called_once()+ assert session.get.call_count == 1# ---------------------------------------------------------------------------