An open source, non-profit web search engine
Match blacklisted domains by suffix, and close the remaining gaps
Daoud Clarke50dd4829ab5d
diff --git a/mwmbl/indexer/blacklist_providers.py b/mwmbl/indexer/blacklist_providers.pyindex 94b443f..c4affff 100644--- a/mwmbl/indexer/blacklist_providers.py+++ b/mwmbl/indexer/blacklist_providers.py@@ -10,6 +10,28 @@ from typing import Optional, Setimport requests+def domain_and_parents(domain: str) -> list[str]:+ """The domain itself followed by each of its parent domains, most specific first.++ The remote lists are apex rules, not host rules - HaGeZi's file header says+ "Syntax: Domains (without subdomains)" and it lives under wildcard/ - so an entry for+ example.com is meant to cover www.example.com and every other subdomain. get_domain()+ hands us the full host, so testing only that host would let every subdomain of a+ blacklisted domain through, starting with the www. form that most sites actually+ serve. Blacklisting is therefore membership of *any* of these.++ The last candidate has two labels: a single-label candidate is a bare TLD, and+ blacklisting one would take out every domain under it.++ >>> domain_and_parents("nyou.booru.org")+ ['nyou.booru.org', 'booru.org']+ """+ parts = domain.split('.')+ if len(parts) < 2:+ return [domain]+ return ['.'.join(parts[i:]) for i in range(len(parts) - 1)]++class BlacklistProvider(ABC):"""Abstract base class for blacklist providers."""@@ -44,8 +66,10 @@ class BuiltInRulesBlacklistProvider(BlacklistProvider):def is_domain_blacklisted(self, domain: str) -> bool:"""Check if domain should be blacklisted based on built-in rules."""- # Check excluded domains- if domain in self.excluded_domains:+ # Check excluded domains. Matched as a suffix, so an apex entry covers its+ # subdomains - the entries written with an explicit www. prefix still only match+ # that host and below, which is what they were added for.+ if any(candidate in self.excluded_domains for candidate in domain_and_parents(domain)):return True# Check regex patterns (adult/spam content)@@ -57,6 +81,13 @@ class BuiltInRulesBlacklistProvider(BlacklistProvider):return False# Spam detection heuristics for SEO spam domains+ #+ # There used to be a second rule here matching any .com host whose first label was+ # 6 or 8 characters long (aimed at brofqpxj.uelinc.com, gzsmjc.fba01.com). It was+ # dropped deliberately: label length says nothing about spam, and it took out+ # groups.google.com, images.example.com and every other three-label .com site with+ # a 6- or 8-character subdomain. Generated-hostname spam is better handled by the+ # threat feed than by guessing at label lengths.domain_parts = domain.split('.')# Domains with all-numeric generated-looking subdomains, e.g. 59648.etnomurcia.com.@@ -126,7 +157,7 @@ class RemoteListBlacklistProvider(BlacklistProvider):def is_domain_blacklisted(self, domain: str) -> bool:domains = self._get_blacklisted_domains()- return domain in domains+ return any(candidate in domains for candidate in domain_and_parents(domain))class HaGeZiBlacklistProvider(RemoteListBlacklistProvider):diff --git a/mwmbl/indexer/blacklist_snapshot.py b/mwmbl/indexer/blacklist_snapshot.pyindex cced95e..4115e7f 100644--- a/mwmbl/indexer/blacklist_snapshot.py+++ b/mwmbl/indexer/blacklist_snapshot.py@@ -48,6 +48,7 @@ from mwmbl.indexer.blacklist_providers import (BuiltInRulesBlacklistProvider,CombinedBlacklistProvider,RemoteListBlacklistProvider,+ domain_and_parents,)logger = getLogger(__name__)@@ -199,6 +200,14 @@ class SnapshotBlacklist:logger.warning("Blacklist snapshot version %s present but blob is missing", version[:12])return False+ if len(blob) % HASH_DTYPE.itemsize != 0:+ # np.frombuffer would raise, and this runs at import time via search_setup, so+ # a truncated blob would stop every web worker from starting. The published+ # snapshot is always a whole number of hashes, so this means a bad write.+ logger.error("Blacklist snapshot version %s is %d bytes, not a multiple of %d; ignoring it",+ version[:12], len(blob), HASH_DTYPE.itemsize)+ return False+array = np.frombuffer(blob, dtype=HASH_DTYPE)self._array = arrayself._version = version@@ -228,7 +237,14 @@ class SnapshotBlacklist:finally:self._loading = False- threading.Thread(target=load, name="blacklist-snapshot-refresh", daemon=True).start()+ try:+ threading.Thread(target=load, name="blacklist-snapshot-refresh", daemon=True).start()+ except RuntimeError:+ # The thread never ran, so nothing will clear _loading, and _maybe_refresh+ # would then return early for the life of the process - this worker would+ # keep filtering against whatever snapshot it last managed to load.+ self._loading = False+ logger.exception("Could not start the blacklist snapshot refresh thread")def filter_blacklisted(self, domains: Iterable[str]) -> set[str]:"""Return the subset of these domains that are blacklisted."""@@ -248,7 +264,18 @@ class SnapshotBlacklist:if not remaining:return blacklisted- hashes = hash_domains(remaining)+ # The lists hold apex rules, so a domain is blacklisted if it *or any parent* is+ # listed - see domain_and_parents. Every candidate goes into one flat array so+ # this stays a single vectorised search; candidate_domains maps each hit back to+ # the domain that was asked about. A typical host contributes 2-3 candidates.+ candidates = []+ candidate_domains = []+ for domain in remaining:+ for candidate in domain_and_parents(domain):+ candidates.append(candidate)+ candidate_domains.append(domain)++ hashes = hash_domains(candidates)positions = np.searchsorted(array, hashes)# searchsorted can return len(array) for a hash above every entry; clamp so the# lookup below stays in bounds. Index 0 is always a safe stand-in because the@@ -256,7 +283,7 @@ class SnapshotBlacklist:positions[positions >= len(array)] = 0found = array[positions] == hashes- blacklisted.update(domain for domain, hit in zip(remaining, found) if hit)+ blacklisted.update(domain for domain, hit in zip(candidate_domains, found) if hit)return blacklisteddef is_domain_blacklisted(self, domain: str) -> bool:diff --git a/mwmbl/indexer/purge_blacklisted.py b/mwmbl/indexer/purge_blacklisted.pyindex a076418..a66f19c 100644--- a/mwmbl/indexer/purge_blacklisted.py+++ b/mwmbl/indexer/purge_blacklisted.py@@ -9,6 +9,15 @@ token hashes to one page - so a document typically lives on a dozen or more pageremoving it from just the page you happened to find it on leaves it retrievable by everyother term. tokenize_document() is a pure function of the url/title/extract/score storedin the index, so recomputing it recovers that full token set exactly.++Not every copy of a document comes from its own tokens, though. index_results_against_query+files documents under the *query's* unigrams and bigrams, and curation files them under the+curated term; those terms are arbitrary and unrecoverable from the document's text. Each+such copy carries the term it was filed under, so the copy that retrieval surfaced is+removed along with the token pages. Other copies of the same URL under other terms are left+for the queries that surface them, which is what makes the loop converge: every purge+removes at least the copy that was queued, so no document can churn through the queue+forever."""from collections import defaultdictfrom logging import getLogger@@ -22,9 +31,16 @@ logger = getLogger(__name__)def pages_for_document(index: TinyIndex, document: Document) -> set[int]:- """Every page this document is filed under."""+ """Every page this copy of the document is filed under.++ The document's own tokens, plus the term it was filed under if it has one - a query+ term or a curated term, neither of which is derivable from the document's text.+ """tokenized = tokenize_document(document.url, document.title, document.extract, document.score)- return {index.get_key_page_index(token) for token in tokenized.tokens}+ pages = {index.get_key_page_index(token) for token in tokenized.tokens}+ if document.term:+ pages.add(index.get_key_page_index(document.term))+ return pagesdef purge_documents(index: TinyIndex, documents: Iterable[Document],@@ -59,7 +75,9 @@ def purge_documents(index: TinyIndex, documents: Iterable[Document],for page_index in pages_for_document(index, document):pages_to_urls[page_index].add(document.url)- removed_by_domain: dict[str, int] = defaultdict(int)+ # Counted by URL, not by (page, document): one document occupies a dozen or more+ # pages, so counting each removal would report an order of magnitude too many.+ removed_urls_by_domain: dict[str, set[str]] = defaultdict(set)for page_index, urls in pages_to_urls.items():page = index.get_page(page_index)kept = [d for d in page if d.url not in urls]@@ -69,12 +87,13 @@ def purge_documents(index: TinyIndex, documents: Iterable[Document],for document in page:if document.url in urls:try:- removed_by_domain[get_domain(document.url)] += 1+ removed_urls_by_domain[get_domain(document.url)].add(document.url)except ValueError:- removed_by_domain[document.url] += 1+ removed_urls_by_domain[document.url].add(document.url)index.store_in_page(page_index, kept)+ removed_by_domain = {domain: len(urls) for domain, urls in removed_urls_by_domain.items()}if removed_by_domain:logger.info("Purged %d documents across %d pages from %d URLs",sum(removed_by_domain.values()), len(pages_to_urls), len(target_urls))- return dict(removed_by_domain)+ return removed_by_domaindiff --git a/mwmbl/indexer/purge_queue.py b/mwmbl/indexer/purge_queue.pyindex d6c390e..b1a7a67 100644--- a/mwmbl/indexer/purge_queue.py+++ b/mwmbl/indexer/purge_queue.py@@ -17,9 +17,13 @@ Two properties matter:the same popular blacklisted document surfacing on a thousand queries is one entry -and MAX_QUEUE_SIZE caps the pathological case where the purge task is not running.-The payload carries exactly the four fields tokenize_document() needs to work out which-index pages a document is filed under. They are read straight out of the index, so the+The payload carries the four fields tokenize_document() needs to work out which index+pages a document is filed under, plus the term it was filed under if it has one - see+purge_blacklisted.pages_for_document. They are read straight out of the index, so theserialised JSON is byte-identical between retrievals and SET dedupe works on it.++The same URL under two different terms is two entries, which is correct: they are two+copies on two pages, and each needs its own removal."""import jsonimport threading@@ -51,8 +55,8 @@ _recently_enqueued: "OrderedDict[str, float]" = OrderedDict()_recently_enqueued_lock = threading.Lock()-def _take_unqueued(payloads: list[str]) -> list[str]:- """Filter out payloads this process queued recently, and record the rest."""+def _unqueued(payloads: list[str]) -> list[str]:+ """The payloads this process has not queued recently, dropping expired records."""now = time.monotonic()with _recently_enqueued_lock:while _recently_enqueued:@@ -61,12 +65,17 @@ def _take_unqueued(payloads: list[str]) -> list[str]:break_recently_enqueued.popitem(last=False)- fresh = [p for p in payloads if p not in _recently_enqueued]- for payload in fresh:+ return [p for p in payloads if p not in _recently_enqueued]+++def _record_enqueued(payloads: list[str]) -> None:+ """Remember that these payloads made it onto the queue."""+ now = time.monotonic()+ with _recently_enqueued_lock:+ for payload in payloads:_recently_enqueued[payload] = nowwhile len(_recently_enqueued) > _MAX_RECENTLY_ENQUEUED:_recently_enqueued.popitem(last=False)- return fresh_redis: Optional[redis.Redis] = None@@ -85,13 +94,14 @@ def _payload(document: Document) -> str:"title": document.title,"extract": document.extract,"score": document.score,+ "term": document.term,}, sort_keys=True)def enqueue_for_purge(documents: Iterable[Document], redis_client: Optional[redis.Redis] = None) -> int:"""Queue these documents for removal from the index. Returns the number of *new*entries added (already-queued duplicates do not count). Never raises."""- payloads = _take_unqueued([_payload(document) for document in documents])+ payloads = _unqueued(list(dict.fromkeys(_payload(document) for document in documents)))if not payloads:return 0@@ -101,11 +111,17 @@ def enqueue_for_purge(documents: Iterable[Document], redis_client: Optional[redilogger.warning("Blacklist purge queue is full (%d); dropping %d documents",MAX_QUEUE_SIZE, len(payloads))return 0- return client.sadd(PURGE_QUEUE_KEY, *payloads)+ added = client.sadd(PURGE_QUEUE_KEY, *payloads)except Exception:logger.warning("Could not enqueue %d documents for purging", len(payloads), exc_info=True)return 0+ # Only now, with the write done. Recording before it would suppress these documents+ # for the whole TTL on the strength of a queueing attempt that never landed, so a+ # Redis blip or a full queue would quietly stall the purge for them.+ _record_enqueued(payloads)+ return added+def drain_purge_queue(limit: int, redis_client: Optional[redis.Redis] = None) -> list[Document]:"""Remove and return up to `limit` queued documents."""@@ -116,8 +132,11 @@ def drain_purge_queue(limit: int, redis_client: Optional[redis.Redis] = None) ->for payload in payloads:try:fields = json.loads(payload)+ # "term" is fetched with .get because entries queued before it joined the+ # payload are still in Redis; those purge by token pages alone, as they did.documents.append(Document(title=fields["title"], url=fields["url"],- extract=fields["extract"], score=fields["score"]))+ extract=fields["extract"], score=fields["score"],+ term=fields.get("term")))except (ValueError, KeyError, TypeError):logger.warning("Discarding unreadable purge queue entry: %r", payload)return documentsdiff --git a/mwmbl/tinysearchengine/super_search.py b/mwmbl/tinysearchengine/super_search.pyindex 558546c..2a76c9e 100644--- a/mwmbl/tinysearchengine/super_search.py+++ b/mwmbl/tinysearchengine/super_search.py@@ -43,7 +43,7 @@ from mwmbl.search_setup import index_path, ltr_modelfrom mwmbl.tinysearchengine.indexer import Documentfrom mwmbl.tinysearchengine.ltr_rank import score_documentsfrom mwmbl.tinysearchengine.mmr_rank import mmr_rerank-from mwmbl.tinysearchengine.rank import score_result_whole+from mwmbl.tinysearchengine.rank import find_blacklisted_urls, score_result_wholefrom mwmbl.tinysearchengine.super_search_sources import SOURCESfrom mwmbl.tokenizer import tokenize@@ -294,6 +294,27 @@ def _doc_passes_term_filter(doc: Document, terms: list[str]) -> bool:return matches > len(terms) / 2+def _drop_blacklisted(docs: list[Document]) -> list[Document]:+ """Documents on blacklisted domains, dropped before they are shown, crawled or indexed.++ Super Search sits outside both of the filters that cover normal search. It reaches the+ index by its own route - _index_results calls index_results_against_query rather than+ index_documents - and it emits its own result frames rather than going through+ Ranker.get_results, so neither the write-path nor the read-path check sees these+ documents. Filtering here is what makes the two guarantees hold for this path too.++ Nothing is queued for purging: these documents come from external search APIs and+ crawls, so there is nothing in the index yet to purge. Dropping them at the point they+ arrive is what keeps it that way.+ """+ blacklisted_urls = find_blacklisted_urls(docs)+ if not blacklisted_urls:+ return docs++ logger.info("Dropped %d blacklisted documents from super search", len(blacklisted_urls))+ return [doc for doc in docs if doc.url not in blacklisted_urls]++def _heuristic_score_docs(query: str, docs: list[Document]) -> list[float]:terms = tokenize(query)if not terms:@@ -376,7 +397,9 @@ async def _follow_links(returnterms = tokenize(query)- proxy_docs = [Document(title=_title_from_url(u), url=u, extract="") for u in raw_links]+ # Filtered before the crawl below, so a blacklisted link is never even fetched.+ proxy_docs = _drop_blacklisted(+ [Document(title=_title_from_url(u), url=u, extract="") for u in raw_links])proxy_scores = [_url_term_score(d.url, terms) for d in proxy_docs]ranked = sorted(zip(proxy_docs, proxy_scores), key=lambda x: -x[1])[:max_links]@@ -516,6 +539,7 @@ async def _run_pipeline(if error is not None:await emit("source_failed", SourceFailedEvent(source=name, error=error))continue+ docs = _drop_blacklisted(docs)await emit("source_returned", SourceReturnedEvent(source=name, count=len(docs)))if not docs:continuediff --git a/test/test_blacklist_providers.py b/test/test_blacklist_providers.pyindex d1c4c94..a17efb7 100644--- a/test/test_blacklist_providers.py+++ b/test/test_blacklist_providers.py@@ -2,15 +2,19 @@Tests for blacklist providers and the abstraction system."""+import re+import pytestimport requestsfrom unittest.mock import patch, MagicMockfrom mwmbl.indexer.blacklist_providers import (+ BuiltInRulesBlacklistProvider,StaticBlacklistProvider,HaGeZiBlacklistProvider,AdultContentBlacklistProvider,- CombinedBlacklistProvider+ CombinedBlacklistProvider,+ domain_and_parents,)from mwmbl.indexer.blacklist import get_default_blacklist_provider@@ -185,3 +189,39 @@ def test_hosts_lines_with_trailing_comments_keep_the_domain():provider = AdultContentBlacklistProvider()assert provider._get_blacklisted_domains() == {'spam.com', 'plain.com'}+++def test_domain_and_parents():+ assert domain_and_parents("nyou.booru.org") == ["nyou.booru.org", "booru.org"]+ assert domain_and_parents("booru.org") == ["booru.org"]+ # Never down to a bare TLD, which would take out everything under it.+ assert "org" not in domain_and_parents("a.b.c.org")+ assert domain_and_parents("localhost") == ["localhost"]+++def test_a_remote_list_entry_covers_subdomains():+ """The lists are apex rules, so www.spam.com must be caught by an entry for spam.com."""+ 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('www.spam.com') is True+ assert provider.is_domain_blacklisted('cdn.images.spam.com') is True+ assert provider.is_domain_blacklisted('notspam.com') is False+ assert provider.is_domain_blacklisted('spam.com.example.org') is False+++def test_excluded_domains_cover_subdomains():+ """EXCLUDED_DOMAINS entries are written apex-first; the www. form must still match."""+ with patch.object(BuiltInRulesBlacklistProvider, '__init__', lambda self: None):+ provider = BuiltInRulesBlacklistProvider()+ provider.excluded_domains = {'fineartteens.com'}+ provider.blacklist_regex = re.compile(r"^$")+ provider.trusted_domains = set()++ assert provider.is_domain_blacklisted('fineartteens.com') is True+ assert provider.is_domain_blacklisted('www.fineartteens.com') is True+ assert provider.is_domain_blacklisted('otherfineartteens.com') is Falsediff --git a/test/test_blacklist_snapshot.py b/test/test_blacklist_snapshot.pyindex ca7fd3c..167e754 100644--- a/test/test_blacklist_snapshot.py+++ b/test/test_blacklist_snapshot.py@@ -161,3 +161,66 @@ def test_hashes_above_every_entry_do_not_index_out_of_bounds(redis_client):# Try enough domains that at least one hashes above and one below the single entry.candidates = [f"candidate{i}.test" for i in range(100)]assert blacklist.filter_blacklisted(candidates) == set()+++# ---------------------------------------------------------------------------+# Subdomain matching+# ---------------------------------------------------------------------------+#+# The remote lists are apex rules - HaGeZi's file header says "Syntax: Domains (without+# subdomains)" - so an entry has to cover the subdomains of that domain too, starting+# with the www. form most sites actually serve.++def apex_blacklist(redis_client):+ refresh_snapshot(CombinedBlacklistProvider([FakeRemoteProvider({"badsite.test"})]), redis_client)+ blacklist = SnapshotBlacklist(built_in_rules=StaticBlacklistProvider(set()),+ redis_client=redis_client)+ blacklist.load_now()+ return blacklist++[email protected]("domain", [+ "badsite.test",+ "www.badsite.test",+ "images.badsite.test",+ "a.deeply.nested.badsite.test",+])+def test_an_apex_entry_covers_its_subdomains(apex_blacklist, domain):+ assert apex_blacklist.is_domain_blacklisted(domain) is True++[email protected]("domain", [+ "badsite.test.example.com", # the entry is a prefix, not a suffix+ "notbadsite.test", # suffix of the string, but not a parent domain+ "example.test", # shares only the TLD+])+def test_an_apex_entry_does_not_cover_unrelated_domains(apex_blacklist, domain):+ assert apex_blacklist.is_domain_blacklisted(domain) is False+++def test_a_tld_is_never_a_candidate(redis_client):+ """Matching down to a bare TLD would take out every domain under it."""+ refresh_snapshot(CombinedBlacklistProvider([FakeRemoteProvider({"test"})]), redis_client)+ blacklist = SnapshotBlacklist(built_in_rules=StaticBlacklistProvider(set()),+ redis_client=redis_client)+ blacklist.load_now()++ assert blacklist.is_domain_blacklisted("innocent.test") is False+++def test_a_truncated_blob_is_ignored_rather_than_raising(provider, redis_client):+ """load_now() runs at import time via search_setup, so raising here would stop every+ web worker from starting."""+ refresh_snapshot(provider, redis_client)+ blacklist = SnapshotBlacklist(built_in_rules=StaticBlacklistProvider(set()),+ redis_client=redis_client)+ blacklist.load_now()+ assert blacklist.is_domain_blacklisted("badsite.test") is True++ redis_client.set(SNAPSHOT_KEY, redis_client.get(SNAPSHOT_KEY)[:-3])+ redis_client.set(SNAPSHOT_VERSION_KEY, "a-new-version")++ assert blacklist.load_now() is False+ # The good array it already had is kept rather than being replaced by a bad one.+ assert blacklist.is_domain_blacklisted("badsite.test") is Truediff --git a/test/test_purge_blacklisted.py b/test/test_purge_blacklisted.pyindex 7c2ff90..7bc6d3f 100644--- a/test/test_purge_blacklisted.py+++ b/test/test_purge_blacklisted.py@@ -1,7 +1,7 @@import pytestfrom mwmbl.indexer.index import tokenize_document-from mwmbl.indexer.index_batches import index_pages, preprocess_documents+from mwmbl.indexer.index_batches import index_pages, index_results_against_query, preprocess_documentsfrom mwmbl.indexer.purge_blacklisted import pages_for_document, purge_documentsfrom mwmbl.tinysearchengine.indexer import Document, PAGE_SIZE, TinyIndex@@ -37,15 +37,11 @@ def test_purge_removes_a_document_from_every_page_it_is_filed_under(index_path):assert len(pages_for_document(tiny_index, BAD)) > 1removed = purge_documents(tiny_index, [BAD])- assert removed == {"badsite.test": len(pages_for_document_count(index_path, BAD))}+ # One document removed, however many pages it took to do it.+ assert removed == {"badsite.test": 1}assert "https://badsite.test/apples" not in urls_in_index(index_path)-def pages_for_document_count(index_path, document):- with TinyIndex(Document, index_path, 'r') as tiny_index:- return pages_for_document(tiny_index, document)--def test_purge_leaves_other_documents_on_shared_pages_alone(index_path):"""The bad and good documents share almost all their tokens, so they share pages.Purging must remove by URL, not by re-testing the page against the blacklist -@@ -104,3 +100,65 @@ def test_pages_for_document_matches_the_indexer(index_path):tokens = tokenize_document(BAD.url, BAD.title, BAD.extract, BAD.score).tokensexpected = {tiny_index.get_key_page_index(token) for token in tokens}assert pages_for_document(tiny_index, BAD) == expected+++# ---------------------------------------------------------------------------+# Copies filed under a term rather than under the document's own tokens+# ---------------------------------------------------------------------------+#+# index_results_against_query files a document under the *query's* terms, and curation+# files it under the curated term. Those terms are arbitrary, so recomputing+# tokenize_document() does not find those pages: without the term on the document, the+# purge removes nothing and the next query re-queues it, forever.++def test_purge_removes_the_copy_filed_under_a_query_term(index_path):+ # index_results_against_query matches a query term against the document's *full* token+ # set, but a document is filed under only the first 10 tokens (plus bigrams). "zebra"+ # is past that cut, so it names a page that recomputing tokenize_document never finds.+ wordy = Document(title="Bad page about apples", url="https://badsite.test/apples",+ extract="apples and oranges and bananas here are many more words "+ "including zebra", score=1.0)+ assert "zebra" not in tokenize_document(wordy.url, wordy.title, wordy.extract, wordy.score).tokens++ index_results_against_query([wordy], "zebra", index_path)++ with TinyIndex(Document, index_path, 'r') as tiny_index:+ term_page = tiny_index.get_key_page_index("zebra")+ assert [d.url for d in tiny_index.get_page(term_page)] == [wordy.url]++ queued = Document(title=wordy.title, url=wordy.url, extract=wordy.extract,+ score=wordy.score, term="zebra")+ with TinyIndex(Document, index_path, 'w') as tiny_index:+ assert purge_documents(tiny_index, [queued]) == {"badsite.test": 1}++ assert wordy.url not in urls_in_index(index_path)+++def test_a_document_with_no_term_still_purges_by_its_tokens(index_path):+ index(index_path, [BAD, GOOD])++ with TinyIndex(Document, index_path, 'w') as tiny_index:+ assert purge_documents(tiny_index, [BAD]) == {"badsite.test": 1}++ assert BAD.url not in urls_in_index(index_path)+++def test_removal_counts_are_per_url_not_per_page(index_path):+ """A document lives on a dozen or more pages; counting each removal would report an+ order of magnitude more documents purged than there were."""+ index(index_path, [BAD])++ with TinyIndex(Document, index_path, 'w') as tiny_index:+ assert len(pages_for_document(tiny_index, BAD)) > 1+ assert purge_documents(tiny_index, [BAD]) == {"badsite.test": 1}+++def test_pages_for_document_includes_the_term_page(index_path):+ with TinyIndex(Document, index_path, 'r') as tiny_index:+ without_term = pages_for_document(tiny_index, BAD)+ with_term = pages_for_document(+ tiny_index,+ Document(title=BAD.title, url=BAD.url, extract=BAD.extract, score=BAD.score,+ term="wibble"))++ assert with_term == without_term | {tiny_index.get_key_page_index("wibble")}diff --git a/test/test_rank_blacklist.py b/test/test_rank_blacklist.pyindex ce4fd7c..a00caba 100644--- a/test/test_rank_blacklist.py+++ b/test/test_rank_blacklist.py@@ -178,3 +178,38 @@ def test_a_redis_failure_does_not_break_search(blacklist):assert BAD.url not in urlsassert GOOD.url in urls+++def test_a_failed_enqueue_is_retried_rather_than_suppressed(blacklist, redis_client):+ """The recently-queued record exists to stop re-queueing what is already on the queue.+ Recording a document before the Redis write lands would suppress it for the whole TTL+ on the strength of an attempt that failed, stalling the purge for it."""+ class BrokenRedis:+ def scard(self, key):+ raise ConnectionError("redis is down")++ with patch("mwmbl.tinysearchengine.rank.get_snapshot_blacklist", return_value=blacklist):+ with patch.object(purge_queue, "get_redis", return_value=BrokenRedis()):+ ranker = HeuristicRanker(FakeIndex([BAD, GOOD]), FakeCompleter())+ ranker.search("bananas", [])++ # Redis is back. The next query must queue the document rather than skip it.+ with patch.object(purge_queue, "get_redis", return_value=redis_client):+ ranker.search("bananas", [])++ assert [d.url for d in drain_purge_queue(10, redis_client)] == [BAD.url]+++def test_a_full_queue_does_not_suppress_the_next_attempt(blacklist, redis_client):+ with patch("mwmbl.tinysearchengine.rank.get_snapshot_blacklist", return_value=blacklist), \+ patch.object(purge_queue, "get_redis", return_value=redis_client), \+ patch.object(purge_queue, "MAX_QUEUE_SIZE", 0):+ ranker = HeuristicRanker(FakeIndex([BAD, GOOD]), FakeCompleter())+ ranker.search("bananas", [])+ assert redis_client.scard(PURGE_QUEUE_KEY) == 0++ with patch("mwmbl.tinysearchengine.rank.get_snapshot_blacklist", return_value=blacklist), \+ patch.object(purge_queue, "get_redis", return_value=redis_client):+ ranker.search("bananas", [])++ assert [d.url for d in drain_purge_queue(10, redis_client)] == [BAD.url]diff --git a/test/test_super_search.py b/test/test_super_search.pyindex 24de687..1844a64 100644--- a/test/test_super_search.py+++ b/test/test_super_search.py@@ -10,6 +10,7 @@ import asyncioimport jsonfrom pathlib import Pathfrom unittest.mock import patch+from urllib.parse import urlparseimport pytestfrom allauth.account.models import EmailAddress@@ -622,3 +623,109 @@ def test_super_search_module_has_no_blocking_imports():source = path.read_text()assert "\nimport requests" not in source and "\nfrom requests " not in sourceassert "time.sleep" not in source+++# ---------------------------------------------------------------------------+# Blacklist+# ---------------------------------------------------------------------------+#+# Super Search bypasses both of the filters that cover normal search: it indexes via+# index_results_against_query rather than index_documents, and it emits its own result+# frames rather than going through Ranker.get_results.++def _stub_blacklist(monkeypatch, domains: set[str]):+ import mwmbl.tinysearchengine.super_search as ss++ def fake_find(documents):+ return {d.url for d in documents if urlparse(d.url).netloc in domains}++ monkeypatch.setattr(ss, "find_blacklisted_urls", fake_find)+++def test_blacklisted_source_results_are_not_shown(client, api_key, monkeypatch):+ cache.delete(_super_search_monthly_key(api_key.user.id))+ _stub_sources(monkeypatch, {+ "hn": [+ Document(title="Bad", url="https://badsite.test/x", extract="bad"),+ Document(title="Good", url="https://good.test/x", extract="good"),+ ],+ })+ _stub_scoring(monkeypatch, [0.9, 0.5] + [0.0] * 20)+ _stub_blacklist(monkeypatch, {"badsite.test"})+ monkeypatch.setattr(+ "mwmbl.tinysearchengine.super_search.crawl_url",+ lambda url, redis: {"url": url, "status": 200, "timestamp": 0, "content": None, "error": None})++ response = client.get("/api/v2/super-search/?q=python", HTTP_X_API_KEY=api_key.raw_key)+ events = _parse_sse(_read_stream(response))++ urls = [d["url"] for t, d in events if t == "result_promoted"]+ for _, data in events:+ if data and "results" in data:+ urls.extend(r["url"] for r in data["results"])++ assert "https://badsite.test/x" not in urls+ assert "https://good.test/x" in urls+++def test_blacklisted_results_are_not_indexed(client, api_key, monkeypatch):+ """_index_results calls index_results_against_query directly, so the index-time+ filter in index_documents never sees these documents."""+ cache.delete(_super_search_monthly_key(api_key.user.id))+ _stub_sources(monkeypatch, {+ "hn": [+ Document(title="Bad", url="https://badsite.test/x", extract="bad"),+ Document(title="Good", url="https://good.test/x", extract="good"),+ ],+ })+ _stub_scoring(monkeypatch, [0.9, 0.5] + [0.0] * 20)+ _stub_blacklist(monkeypatch, {"badsite.test"})+ monkeypatch.setattr(+ "mwmbl.tinysearchengine.super_search.crawl_url",+ lambda url, redis: {"url": url, "status": 200, "timestamp": 0, "content": None, "error": None})++ indexed = []++ def fake_index(docs, query, path):+ indexed.extend(d.url for d in docs)+ return len(docs)++ monkeypatch.setattr("mwmbl.tinysearchengine.super_search.index_results_against_query", fake_index)++ response = client.get("/api/v2/super-search/?q=python", HTTP_X_API_KEY=api_key.raw_key)+ _read_stream(response)++ assert indexed == ["https://good.test/x"]+++def test_blacklisted_links_are_not_crawled(client, api_key, monkeypatch):+ """Links are filtered before the crawl, so a blacklisted page is never fetched."""+ cache.delete(_super_search_monthly_key(api_key.user.id))+ _stub_sources(monkeypatch, {+ "hn": [Document(title="Parent", url="https://good.test/", extract="parent")],+ })+ _stub_scoring(monkeypatch, [0.9] + [0.0] * 20)+ _stub_blacklist(monkeypatch, {"badsite.test"})++ crawled = []++ def fake_crawl(url, redis):+ crawled.append(url)+ if url == "https://good.test/":+ return {"url": url, "status": 200, "timestamp": 0, "error": None,+ "content": {"title": "Parent", "extract": "parent",+ "links": ["https://badsite.test/x", "https://other.test/y"],+ "extra_links": []}}+ return {"url": url, "status": 200, "timestamp": 0, "error": None,+ "content": {"title": "Child", "extract": "child", "links": [], "extra_links": []}}++ monkeypatch.setattr("mwmbl.tinysearchengine.super_search.crawl_url", fake_crawl)++ response = client.get("/api/v2/super-search/?q=python", HTTP_X_API_KEY=api_key.raw_key)+ _read_stream(response)++ assert "https://badsite.test/x" not in crawled+ assert "https://other.test/y" in crawled