An open source, non-profit web search engine
Harden Wikipedia rate-limit detection and add test coverage
Daoud Clarkef5808e2c9e39
diff --git a/mwmbl/tinysearchengine/rank.py b/mwmbl/tinysearchengine/rank.pyindex a96f1c8..58ac061 100644--- a/mwmbl/tinysearchengine/rank.py+++ b/mwmbl/tinysearchengine/rank.py@@ -393,6 +393,19 @@ def get_wiki_url(title: str):return WIKI_URL_FORMAT.format(title=title.replace(" ", "_"))+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)++HTML_TAG_REGEX = re.compile(r'<[^>]+>')@@ -414,7 +427,7 @@ def get_wiki_results(s: str, max_wiki_results: int) -> list[Document]:response = session.get(WIKI_SEARCH_API_URL.format(query=escaped_query), headers=headers, timeout=5)wiki_response = response.json()except RetryError as e:- if "429" in str(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_SECONDSdiff --git a/test/test_rank.py b/test/test_rank.pyindex 36c6789..dbd2117 100644--- a/test/test_rank.py+++ b/test/test_rank.py@@ -1,5 +1,12 @@+from unittest.mock import MagicMock, patch++import pytest+from requests.exceptions import RetryError+from urllib3.exceptions import MaxRetryError, ResponseError++from mwmbl.tinysearchengine import rankfrom mwmbl.tinysearchengine.indexer import Document-from mwmbl.tinysearchengine.rank import HeuristicRanker+from mwmbl.tinysearchengine.rank import HeuristicRanker, get_wiki_resultsdef test_order_result():@@ -15,3 +22,103 @@ def test_order_result():ordered_results = ranker.order_results(["bananas"], documents, True)assert ordered_results[0].title == 'Bananas and apples'+++class _TrackingRanker(HeuristicRanker):+ """A ranker whose external_search (e.g. live Wikipedia lookups) is trackable."""++ def __init__(self):+ tiny_index = MagicMock()+ tiny_index.retrieve.return_value = []+ completer = MagicMock()+ completer.complete.return_value = []+ super().__init__(tiny_index, completer)+ self.external_search_calls = []++ def external_search(self, q):+ self.external_search_calls.append(q)+ return []+++def test_complete_never_triggers_external_search():+ # Autocomplete fires on every keystroke, so it must never call external_search+ # (e.g. a live Wikipedia lookup) - see fix-wiki-overuse.+ ranker = _TrackingRanker()+ ranker.complete("some quer")+ assert ranker.external_search_calls == []+++def test_search_still_triggers_external_search():+ ranker = _TrackingRanker()+ ranker.search("some query", [])+ assert ranker.external_search_calls == ["some query"]+++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)++[email protected](autouse=True)+def _reset_wiki_circuit():+ rank._wiki_blocked_until = 0.0+ yield+ rank._wiki_blocked_until = 0.0+++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+ return get_wiki_results("query", 5)+++def test_wiki_429_retry_error_trips_circuit_breaker():+ session = MagicMock()+ session.get.side_effect = _make_retry_error(429)++ results = _get_wiki_results_with_session(session)++ assert results == []+ assert rank._wiki_circuit_open()+++def test_wiki_non_429_retry_error_does_not_trip_circuit_breaker():+ session = MagicMock()+ session.get.side_effect = _make_retry_error(503)++ results = _get_wiki_results_with_session(session)++ assert results == []+ assert not rank._wiki_circuit_open()+++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.+ session = MagicMock()+ session.get.side_effect = _make_retry_error(503)++ _get_wiki_results_with_session(session)++ assert not rank._wiki_circuit_open()+++def test_open_wiki_circuit_short_circuits_without_calling_wikipedia():+ rank._trip_wiki_circuit()++ with patch.object(rank, "request_cache") as mock_request_cache:+ results = get_wiki_results("query", 5)++ mock_request_cache.assert_not_called()+ assert results == []+++def test_is_wiki_rate_limited_detects_429_reason():+ assert rank._is_wiki_rate_limited(_make_retry_error(429))+++def test_is_wiki_rate_limited_ignores_non_429_reason():+ assert not rank._is_wiki_rate_limited(_make_retry_error(503))