An open source, non-profit web search engine
Let the caller own the cost of the remote blocklists
Daoud Clarkefee3f539ef60
diff --git a/mwmbl/background.py b/mwmbl/background.pyindex 5b5cedb..337d149 100644--- a/mwmbl/background.py+++ b/mwmbl/background.py@@ -21,9 +21,13 @@ from django.core.cache import cachefrom mwmbl import pricingfrom mwmbl.indexer import index_batches, historicalfrom mwmbl.indexer.batch_cache import BatchCache+from mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklist, refresh_snapshot+from mwmbl.indexer.purge_blacklisted import purge_documents+from mwmbl.indexer.purge_queue import drain_purge_queue, queue_sizefrom mwmbl.models import OldIndex, UsageBucketfrom mwmbl.quota import MONTHLY_TTL, _monthly_key, get_all_monthly_keysfrom mwmbl.tinysearchengine.copy_index import copy_pages+from mwmbl.tinysearchengine.indexer import Document, TinyIndexNUM_PAGES_TO_COPY = 1024@@ -148,8 +152,6 @@ def refresh_blacklist_snapshot():parsed. Search workers only ever read the ~11 MB hash array this publishes to Redis,so no query ever waits on a blocklist fetch. See mwmbl.indexer.blacklist_snapshot."""- from mwmbl.indexer.blacklist_snapshot import refresh_snapshot-refresh_snapshot()@@ -162,11 +164,6 @@ def purge_blacklisted_from_queue():documents are not re-filtered on every future query. The queue is best-effort, andthat is fine: anything lost is re-queued the next time a query surfaces it."""- from mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklist- from mwmbl.indexer.purge_blacklisted import purge_documents- from mwmbl.indexer.purge_queue import drain_purge_queue, queue_size- from mwmbl.tinysearchengine.indexer import Document, TinyIndex-documents = drain_purge_queue(settings.BLACKLIST_PURGE_BATCH_SIZE)if not documents:returndiff --git a/mwmbl/indexer/blacklist_providers.py b/mwmbl/indexer/blacklist_providers.pyindex aea61e6..94b443f 100644--- a/mwmbl/indexer/blacklist_providers.py+++ b/mwmbl/indexer/blacklist_providers.py@@ -5,17 +5,10 @@ This module provides different ways to check if domains should be blacklisted,making the system more flexible and testable."""-import timefrom abc import ABC, abstractmethod-from typing import Set+from typing import Optional, Setimport requests-# Parsed remote lists (~950k+ lines) are expensive to re-parse, and get_default_blacklist_provider()-# is now called on every index_documents() call (indexing needs to check the blacklist too, not just-# crawling), so the parsed result is cached here at module level - shared across every-# RemoteListBlacklistProvider instance, however many get constructed - keyed by URL.-_parsed_domains_cache: dict[str, tuple[float, Set[str]]] = {}-class BlacklistProvider(ABC):"""Abstract base class for blacklist providers."""@@ -76,22 +69,37 @@ class BuiltInRulesBlacklistProvider(BlacklistProvider):class RemoteListBlacklistProvider(BlacklistProvider):- """Provider that fetches a remote newline-delimited domain list, with caching.+ """Provider that fetches a remote newline-delimited domain list.Handles both plain domain-per-line lists and hosts-file format(``0.0.0.0 domain.com``), which is what most public blocklists use.++ Downloading and parsing one of these lists costs tens of megabytes of transfer and+ ~100 MB of resident domain strings, so an instance is deliberately expensive to+ construct-and-use and the caller owns how long that cost is amortised over. There is+ no cache behind this module: an earlier version kept the parsed set in a module-level+ dict keyed by URL, which made `get_default_blacklist_provider()` look cheap enough to+ call from anywhere - including a request handler, where the first call blocks on the+ download and the worker then holds the domain strings for its lifetime. Instead, the+ fetch happens once per instance, and the only long-lived instance lives in the+ background snapshot task. Everything on the search and indexing paths reads the+ published snapshot (mwmbl.indexer.blacklist_snapshot) instead of coming here."""- def __init__(self, url: str, cache_expire_days: int = 1):+ def __init__(self, url: str):self.url = url- self.cache_expire_days = cache_expire_days+ self._domains: Optional[Set[str]] = Nonedef _get_blacklisted_domains(self) -> Set[str]:- cached = _parsed_domains_cache.get(self.url)- if cached is not None:- fetched_at, domains = cached- if time.monotonic() - fetched_at < self.cache_expire_days * 86400:- return domains+ """The parsed domain set, fetched on first use and held for this instance's life.++ Raises requests.RequestException if the list cannot be fetched. Callers must not+ turn that into an empty set: a silently empty list is indistinguishable from a+ list that blacklists nothing, and build_snapshot() would publish the result as+ though it were complete.+ """+ if self._domains is not None:+ return self._domains# Deliberately NOT using mwmbl.utils.request_cache here. That is a *filesystem*# cache rooted at settings.REQUEST_CACHE_PATH = f"{DATA_PATH}/request_cache" - the@@ -100,29 +108,21 @@ class RemoteListBlacklistProvider(BlacklistProvider):# *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;- # the module-level parsed cache above already gives us reuse without touching disk.- try:- response = requests.get(self.url, timeout=60)- response.raise_for_status()-- domains = set()- for line in response.text.split('\n'):- line = line.strip()- if not line or line.startswith('#'):- continue- # Hosts format: "0.0.0.0 domain.com" or "127.0.0.1 domain.com"- parts = line.split()- domains.add(parts[1] if len(parts) == 2 and parts[0] in ('0.0.0.0', '127.0.0.1') else parts[0])-- _parsed_domains_cache[self.url] = (time.monotonic(), domains)- return domains- except requests.RequestException as e:- # Log the error but don't fail. Fall back to the last known-good parsed set- # rather than caching an empty one - a transient fetch error shouldn't silently- # disable this provider's coverage until the next successful fetch.- print(f"Warning: Failed to fetch blacklist from {self.url}: {e}")- return cached[1] if cached is not None else set()+ # 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()++ domains = set()+ for line in response.text.split('\n'):+ line = line.split('#')[0].strip()+ if not line:+ continue+ # Hosts format: "0.0.0.0 domain.com" or "127.0.0.1 domain.com"+ parts = line.split()+ domains.add(parts[1] if len(parts) >= 2 and parts[0] in ('0.0.0.0', '127.0.0.1') else parts[0])++ self._domains = domains+ return domainsdef is_domain_blacklisted(self, domain: str) -> bool:domains = self._get_blacklisted_domains()@@ -162,11 +162,11 @@ class HaGeZiBlacklistProvider(RemoteListBlacklistProvider):'tif_mini': 'https://raw.githubusercontent.com/hagezi/dns-blocklists/main/wildcard/tif.mini-onlydomains.txt',}- def __init__(self, list_type: str = 'tif_medium', cache_expire_days: int = 1):+ def __init__(self, list_type: str = 'tif_medium'):if list_type not in self.HAGEZI_URLS:raise ValueError(f"Invalid list_type. Must be one of: {list(self.HAGEZI_URLS.keys())}")- super().__init__(self.HAGEZI_URLS[list_type], cache_expire_days)+ super().__init__(self.HAGEZI_URLS[list_type])class AdultContentBlacklistProvider(RemoteListBlacklistProvider):@@ -179,8 +179,8 @@ class AdultContentBlacklistProvider(RemoteListBlacklistProvider):URL = 'https://raw.githubusercontent.com/blocklistproject/Lists/master/porn.txt'- def __init__(self, cache_expire_days: int = 7):- super().__init__(self.URL, cache_expire_days)+ def __init__(self):+ super().__init__(self.URL)class CombinedBlacklistProvider(BlacklistProvider):diff --git a/mwmbl/indexer/blacklist_snapshot.py b/mwmbl/indexer/blacklist_snapshot.pyindex 9ef7309..cced95e 100644--- a/mwmbl/indexer/blacklist_snapshot.py+++ b/mwmbl/indexer/blacklist_snapshot.py@@ -42,6 +42,7 @@ import numpy as npimport redisfrom django.conf import settings+from mwmbl.indexer.blacklist import get_default_blacklist_providerfrom mwmbl.indexer.blacklist_providers import (BlacklistProvider,BuiltInRulesBlacklistProvider,@@ -89,6 +90,10 @@ def collect_remote_domains(provider: BlacklistProvider) -> set[str]:get_default_blacklist_provider() without knowing how it is composed. Providers thatare not remote lists (the built-in rules) have no enumerable domain set and areskipped - they are evaluated locally instead, see the module docstring.++ A failed fetch propagates rather than contributing an empty set: the union of the+ lists is what gets published, so one list silently returning nothing would replace+ every worker's snapshot with one missing hundreds of thousands of domains."""if isinstance(provider, CombinedBlacklistProvider):domains = set()@@ -103,7 +108,8 @@ def collect_remote_domains(provider: BlacklistProvider) -> set[str]:def build_snapshot(provider: BlacklistProvider) -> bytes:"""Download/parse the remote lists and return the sorted hash array as bytes."""domains = collect_remote_domains(provider)- hashes = np.unique(hash_domains(domains)) # np.unique sorts, which is what we need+ all_hashes = hash_domains(domains)+ hashes = np.unique(all_hashes) # np.unique sorts, which is what we needlogger.info("Built blacklist snapshot: %d domains, %d unique hashes, %.1f MB",len(domains), len(hashes), hashes.nbytes / 1e6)return hashes.astype(HASH_DTYPE).tobytes()@@ -127,9 +133,9 @@ def publish_snapshot(blob: bytes, redis_client: Optional[redis.Redis] = None) ->def refresh_snapshot(provider: Optional[BlacklistProvider] = None,redis_client: Optional[redis.Redis] = None) -> str:if provider is None:- from mwmbl.indexer.blacklist import get_default_blacklist_providerprovider = get_default_blacklist_provider()- return publish_snapshot(build_snapshot(provider), redis_client)+ blob = build_snapshot(provider)+ return publish_snapshot(blob, redis_client)# ---------------------------------------------------------------------------@@ -201,7 +207,7 @@ class SnapshotBlacklist:def _maybe_refresh(self):"""Kick off a refresh in the background if it has been long enough."""- interval = getattr(settings, "BLACKLIST_SNAPSHOT_CHECK_SECONDS", 300)+ interval = settings.BLACKLIST_SNAPSHOT_CHECK_SECONDSif time.monotonic() - self._last_checked < interval:returndiff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.pyindex 290f45e..db0bb76 100644--- a/mwmbl/indexer/index_batches.py+++ b/mwmbl/indexer/index_batches.py@@ -13,7 +13,7 @@ from 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.blacklist import get_default_blacklist_provider+from mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklistfrom mwmbl.indexer.index import tokenize_document, prepare_url_for_tokenizingfrom mwmbl.indexer.indexdb import BatchStatusfrom mwmbl.tinysearchengine.indexer import Document, TinyIndex, DocumentState, CURATED_STATES@@ -77,7 +77,12 @@ def index_documents(documents, index_path):a submitted batch or a direct /results submission can contain a blacklisted domain'spages regardless of whether that domain was ever handed out to be crawled (e.g. abrowser-extension user organically visiting the site), so indexing needs its own check- rather than relying on those upstream gates."""+ rather than relying on those upstream gates.++ The check reads the published snapshot rather than constructing the remote providers.+ POST /crawler/results calls this from a gunicorn worker, and the providers download+ tens of megabytes and hold ~156 MB of domain strings for the process's life - see+ blacklist_snapshot."""documents = filter_blacklisted_documents(documents)page_documents = preprocess_documents(documents, index_path)new_page_doc_counts = index_pages(index_path, page_documents)@@ -86,15 +91,19 @@ def index_documents(documents, index_path):def filter_blacklisted_documents(documents: list[Document]) -> list[Document]:- blacklist_provider = get_default_blacklist_provider()- kept = []+ domains_by_url = {}for document in documents:try:- domain = get_domain(document.url)+ domains_by_url[document.url] = get_domain(document.url)except ValueError:- kept.append(document)+ # Unparseable URL - keep it, matching rank.find_blacklisted_urls.continue- if blacklist_provider.is_domain_blacklisted(domain):++ blacklisted_domains = get_snapshot_blacklist().filter_blacklisted(domains_by_url.values())+ kept = []+ for document in documents:+ domain = domains_by_url.get(document.url)+ if domain in blacklisted_domains:logger.info(f"Skipping indexing for blacklisted domain {domain}: {document.url}")continuekept.append(document)diff --git a/mwmbl/tinysearchengine/rank.py b/mwmbl/tinysearchengine/rank.pyindex 052a4db..5c45595 100644--- a/mwmbl/tinysearchengine/rank.py+++ b/mwmbl/tinysearchengine/rank.py@@ -20,6 +20,8 @@ from requests.exceptions import RetryErrorfrom mwmbl.format import get_query_regexfrom mwmbl.hn_top_domains_filtered import DOMAINS+from mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklist+from mwmbl.indexer.purge_queue import enqueue_for_purgefrom mwmbl.tinysearchengine.completer import Completerfrom mwmbl.tinysearchengine.indexer import TinyIndex, Document, DocumentStatefrom mwmbl.tokenizer import tokenize, get_bigrams@@ -224,8 +226,6 @@ def find_blacklisted_urls(documents: list[Document]) -> set[str]:Cost is ~94us for a typical query's ~200 distinct domains - see blacklist_snapshot."""- from mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklist-domains_to_urls = defaultdict(set)for document in documents:try:@@ -371,7 +371,7 @@ class Ranker:a Wikipedia or Super Search result, and nothing to purge for the caller-suppliedadditional_results either."""- if not getattr(settings, "BLACKLIST_FILTER_AT_RETRIEVAL", True):+ if not settings.BLACKLIST_FILTER_AT_RETRIEVAL:return candidates, curated_itemsblacklisted_urls = find_blacklisted_urls(candidates + curated_items)@@ -380,7 +380,6 @@ class Ranker:logger.info("Filtered %d blacklisted documents from results", len(blacklisted_urls))- from mwmbl.indexer.purge_queue import enqueue_for_purgeenqueue_for_purge([d for d in index_items if d.url in blacklisted_urls])return ([d for d in candidates if d.url not in blacklisted_urls],diff --git a/test/test_blacklist_providers.py b/test/test_blacklist_providers.pyindex a19dea7..d1c4c94 100644--- a/test/test_blacklist_providers.py+++ b/test/test_blacklist_providers.py@@ -6,7 +6,6 @@ import pytestimport requestsfrom unittest.mock import patch, MagicMock-from mwmbl.indexer import blacklist_providersfrom mwmbl.indexer.blacklist_providers import (StaticBlacklistProvider,HaGeZiBlacklistProvider,@@ -16,17 +15,6 @@ from mwmbl.indexer.blacklist_providers import (from mwmbl.indexer.blacklist import get_default_blacklist_provider[email protected](autouse=True)-def clear_shared_domains_cache():- """_parsed_domains_cache is a module-level dict shared across every- RemoteListBlacklistProvider instance (see blacklist_providers.py) so that- index_documents() can call get_default_blacklist_provider() cheaply on every call.- Clear it around each test so a mocked response in one test can't leak into another."""- blacklist_providers._parsed_domains_cache.clear()- yield- blacklist_providers._parsed_domains_cache.clear()--def test_static_blacklist_provider():"""Test StaticBlacklistProvider with is_domain_blacklisted method."""test_domains = {'spam.com', 'malware.example'}@@ -156,18 +144,44 @@ def test_remote_lists_do_not_use_the_shared_filesystem_request_cache():assert mock_get.called-def test_fetch_failure_falls_back_to_last_good_list():- """A transient fetch failure must not silently blank out the provider's coverage."""+def test_fetch_failure_propagates():+ """A failed fetch must not look like a list that blacklists nothing.++ build_snapshot() publishes the union of these lists to every search worker, so a+ provider that swallowed the error and returned an empty set would replace a good+ snapshot with one missing its entire contribution."""+ provider = HaGeZiBlacklistProvider('light')+ with patch('mwmbl.indexer.blacklist_providers.requests.get',+ side_effect=requests.RequestException("boom")):+ with pytest.raises(requests.RequestException):+ provider.is_domain_blacklisted('spam.com')+++def test_the_list_is_fetched_once_per_instance():+ """The cost of a remote list is owned by whoever holds the provider.++ There is no cache behind the module - that made get_default_blacklist_provider() look+ cheap enough to call from a request handler. Reuse comes from holding the instance."""with patch('mwmbl.indexer.blacklist_providers.requests.get') as mock_get:mock_response = MagicMock()mock_response.text = "spam.com\n"mock_get.return_value = mock_response+provider = HaGeZiBlacklistProvider('light')assert provider.is_domain_blacklisted('spam.com') is True+ assert provider.is_domain_blacklisted('other.com') is False+ assert mock_get.call_count == 1- # Expire the module-level cache so the next call refetches, and make that fetch fail.- blacklist_providers._parsed_domains_cache[provider.url] = (- -10**9, blacklist_providers._parsed_domains_cache[provider.url][1])- with patch('mwmbl.indexer.blacklist_providers.requests.get',- side_effect=requests.RequestException("boom")):- assert provider.is_domain_blacklisted('spam.com') is True # still covered+ # A second instance is a second download - nothing is shared between them.+ assert HaGeZiBlacklistProvider('light').is_domain_blacklisted('spam.com') is True+ assert mock_get.call_count == 2+++def test_hosts_lines_with_trailing_comments_keep_the_domain():+ with patch('mwmbl.indexer.blacklist_providers.requests.get') as mock_get:+ mock_response = MagicMock()+ mock_response.text = "0.0.0.0 spam.com # added 2026-01-01\n# a comment line\nplain.com\n"+ mock_get.return_value = mock_response++ provider = AdultContentBlacklistProvider()+ assert provider._get_blacklisted_domains() == {'spam.com', 'plain.com'}diff --git a/test/test_index_batches.py b/test/test_index_batches.pyindex 9137d0d..ec4859f 100644--- a/test/test_index_batches.py+++ b/test/test_index_batches.py@@ -2,9 +2,11 @@ from pathlib import Pathfrom tempfile import TemporaryDirectoryfrom unittest.mock import patch+import fakeredisimport pytestfrom mwmbl.indexer.blacklist_providers import StaticBlacklistProvider+from mwmbl.indexer.blacklist_snapshot import SnapshotBlacklistfrom mwmbl.indexer.index_batches import (sort_documents, combine_documents, _merge_user_ids, MAX_USER_IDS,index_results_against_query, index_documents,@@ -216,7 +218,19 @@ def test_combine_documents_propagates_user_ids_to_winner():# blacklisted domain, they don't stop a submitted batch that already contains one of its# pages, so indexing needs its own blacklist check.-PATCH_TARGET = "mwmbl.indexer.index_batches.get_default_blacklist_provider"+PATCH_TARGET = "mwmbl.indexer.index_batches.get_snapshot_blacklist"+++def snapshot_blacklist(domains: set[str]) -> SnapshotBlacklist:+ """A blacklist backed by the given domains alone.++ index_documents() reads the published snapshot rather than constructing the remote+ providers, so the double it gets has to be a SnapshotBlacklist. Supplying the domains+ as its built-in rules keeps these tests off the snapshot machinery, which+ test_blacklist_snapshot.py covers.+ """+ return SnapshotBlacklist(built_in_rules=StaticBlacklistProvider(domains),+ redis_client=fakeredis.FakeRedis())@pytest.fixture@@ -240,7 +254,7 @@ def test_index_documents_skips_blacklisted_domain(index_path):Document(title="Good", url="https://example.com/y", extract="a good page"),]- with patch(PATCH_TARGET, return_value=StaticBlacklistProvider({"fineartteens.com"})):+ with patch(PATCH_TARGET, return_value=snapshot_blacklist({"fineartteens.com"})):index_documents(documents, index_path)urls = _all_urls(index_path)@@ -251,7 +265,7 @@ def test_index_documents_skips_blacklisted_domain(index_path):def test_index_documents_keeps_everything_when_nothing_blacklisted(index_path):documents = [Document(title="Good", url="https://example.com/y", extract="a good page")]- with patch(PATCH_TARGET, return_value=StaticBlacklistProvider(set())):+ with patch(PATCH_TARGET, return_value=snapshot_blacklist(set())):index_documents(documents, index_path)assert "https://example.com/y" in _all_urls(index_path)diff --git a/test/test_rank_blacklist.py b/test/test_rank_blacklist.pyindex b5b07af..ce4fd7c 100644--- a/test/test_rank_blacklist.py+++ b/test/test_rank_blacklist.py@@ -60,7 +60,7 @@ def blacklist(redis_client):@pytest.fixturedef ranker(blacklist, redis_client, request):documents = getattr(request, "param", [BAD, GOOD])- with patch("mwmbl.indexer.blacklist_snapshot.get_snapshot_blacklist", return_value=blacklist), \+ with patch("mwmbl.tinysearchengine.rank.get_snapshot_blacklist", return_value=blacklist), \patch.object(purge_queue, "get_redis", return_value=redis_client):yield HeuristicRanker(FakeIndex(documents), FakeCompleter())@@ -133,7 +133,7 @@ def test_curated_blacklisted_documents_are_dropped(blacklist, redis_client):extract="bananas", score=1.0, term="bananas",state=DocumentState.ORGANIC_APPROVED)- with patch("mwmbl.indexer.blacklist_snapshot.get_snapshot_blacklist", return_value=blacklist), \+ with patch("mwmbl.tinysearchengine.rank.get_snapshot_blacklist", return_value=blacklist), \patch.object(purge_queue, "get_redis", return_value=redis_client):ranker = HeuristicRanker(FakeIndex([curated, GOOD]), FakeCompleter())urls = [result.url for result in ranker.search("bananas", [])]@@ -148,7 +148,7 @@ def test_additional_results_are_filtered_but_not_queued(blacklist, redis_client)additional = Document(title="Bananas", url=f"https://{BLACKLISTED_DOMAIN}/from-google",extract="bananas", score=1.0, state=DocumentState.FROM_GOOGLE)- with patch("mwmbl.indexer.blacklist_snapshot.get_snapshot_blacklist", return_value=blacklist), \+ with patch("mwmbl.tinysearchengine.rank.get_snapshot_blacklist", return_value=blacklist), \patch.object(purge_queue, "get_redis", return_value=redis_client):ranker = HeuristicRanker(FakeIndex([GOOD]), FakeCompleter())urls = [result.url for result in ranker.search("bananas", [additional])]@@ -171,7 +171,7 @@ def test_a_redis_failure_does_not_break_search(blacklist):def scard(self, key):raise ConnectionError("redis is down")- with patch("mwmbl.indexer.blacklist_snapshot.get_snapshot_blacklist", return_value=blacklist), \+ with patch("mwmbl.tinysearchengine.rank.get_snapshot_blacklist", return_value=blacklist), \patch.object(purge_queue, "get_redis", return_value=BrokenRedis()):ranker = HeuristicRanker(FakeIndex([BAD, GOOD]), FakeCompleter())urls = [result.url for result in ranker.search("bananas", [])]