Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Count blacklisted documents removed from the index

Daoud Clarke01d11a9960bf
diff --git a/mwmbl/background.py b/mwmbl/background.py
index 337d149..0b68016 100644
--- a/mwmbl/background.py
+++ b/mwmbl/background.py
@@ -17,8 +17,10 @@ from time import sleep
from background_task import background
from django.conf import settings
from django.core.cache import cache
+from redis import Redis
from mwmbl import pricing
+from mwmbl.crawler.stats import StatsManager
from mwmbl.indexer import index_batches, historical
from mwmbl.indexer.batch_cache import BatchCache
from mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklist, refresh_snapshot
@@ -35,6 +37,8 @@ NUM_PAGES_TO_COPY = 1024
basicConfig(stream=sys.stdout, level=logging.INFO)
logger = getLogger(__name__)
+stats_manager = StatsManager(Redis.from_url(settings.REDIS_URL, decode_responses=True))
+
def run(data_path: str):
logger.info("Started background process")
@@ -173,8 +177,11 @@ def purge_blacklisted_from_queue():
with TinyIndex(Document, str(index_path), 'w') as index:
removed_by_domain = purge_documents(index, documents, blacklist.is_domain_blacklisted)
+ num_removed = sum(removed_by_domain.values())
+ stats_manager.record_blacklisted_removed(num_removed)
+
logger.info("Purged %d documents from the index across %d domains; %d still queued",
- sum(removed_by_domain.values()), len(removed_by_domain), queue_size())
+ num_removed, len(removed_by_domain), queue_size())
@background(schedule=0)
diff --git a/mwmbl/crawler/stats.py b/mwmbl/crawler/stats.py
index 8c9b61d..92c6e04 100644
--- a/mwmbl/crawler/stats.py
+++ b/mwmbl/crawler/stats.py
@@ -31,6 +31,7 @@ RESULTS_COUNT_KEY = "results-count-{date}"
USER_RESULTS_COUNT_KEY = "user-results-count-{date}"
DATASET_QUERIES_COUNT_KEY = "dataset-queries-count-{date}"
DATASET_RESULTS_COUNT_KEY = "dataset-results-count-{date}"
+BLACKLISTED_REMOVED_COUNT_KEY = "blacklisted-removed-count-{date}"
SHORT_EXPIRE_SECONDS = 60 * 60 * 24
LONG_EXPIRE_SECONDS = 60 * 60 * 24 * 30
@@ -59,6 +60,7 @@ class MwmblStats(BaseModel):
results_in_index_daily: dict[str, int]
dataset_queries_daily: dict[str, int]
dataset_results_daily: dict[str, int]
+ blacklisted_results_removed_daily: dict[str, int]
# New stats we want per domain:
@@ -150,6 +152,7 @@ class StatsManager:
results_indexed_daily = {}
dataset_queries_daily = {}
dataset_results_daily = {}
+ blacklisted_results_removed_daily = {}
for i in range(29, -1, -1):
date_i = date - timedelta(days=i)
url_count_key = URL_DATE_COUNT_KEY.format(date=date_i)
@@ -180,6 +183,12 @@ class StatsManager:
dataset_results_count = 0
dataset_results_daily[str(date_i)] = dataset_results_count
+ blacklisted_removed_count_key = BLACKLISTED_REMOVED_COUNT_KEY.format(date=date_i)
+ blacklisted_removed_count = self.redis.get(blacklisted_removed_count_key)
+ if blacklisted_removed_count is None:
+ blacklisted_removed_count = 0
+ blacklisted_results_removed_daily[str(date_i)] = blacklisted_removed_count
+
hour_counts = []
for i in range(date_time.hour + 1):
hour = datetime(date_time.year, date_time.month, date_time.day, i)
@@ -212,6 +221,7 @@ class StatsManager:
top_user_results=user_results_counts,
dataset_queries_daily=dataset_queries_daily,
dataset_results_daily=dataset_results_daily,
+ blacklisted_results_removed_daily=blacklisted_results_removed_daily,
**index_stats,
)
@@ -263,6 +273,18 @@ class StatsManager:
self.redis.zincrby(user_result_count_key, num_results, username)
self.redis.expire(user_result_count_key, SHORT_EXPIRE_SECONDS)
+ def record_blacklisted_removed(self, num_results: int) -> None:
+ """Record documents removed from the index by the background blacklist purge.
+
+ This is the only visibility we have on the purge loop: retrieval filters
+ blacklisted domains out of results whether or not the removal ever happens, so
+ a count that stays at zero while queries are being filtered means the loop is
+ broken.
+ """
+ blacklisted_removed_count_key = BLACKLISTED_REMOVED_COUNT_KEY.format(date=datetime.utcnow().date())
+ self.redis.incrby(blacklisted_removed_count_key, num_results)
+ self.redis.expire(blacklisted_removed_count_key, LONG_EXPIRE_SECONDS)
+
def record_dataset(self, hashed_dataset) -> None:
"""Record dataset statistics from a dataset submission."""
from datetime import datetime
diff --git a/test/test_stats_blacklisted_removed.py b/test/test_stats_blacklisted_removed.py
new file mode 100644
index 0000000..c8b5714
--- /dev/null
+++ b/test/test_stats_blacklisted_removed.py
@@ -0,0 +1,82 @@
+"""
+Tests for the daily count of blacklisted documents removed from the index.
+
+Retrieval filters blacklisted domains out of results whether or not the background purge
+ever removes them, so a broken purge loop is invisible from the search results alone.
+This counter is the only signal that the removals are actually happening.
+"""
+from datetime import datetime
+from unittest.mock import patch
+
+import fakeredis
+
+from mwmbl.crawler.stats import BLACKLISTED_REMOVED_COUNT_KEY, LONG_EXPIRE_SECONDS, StatsManager
+
+NO_INDEX_COUNTS = {
+ "urls_in_index_daily": {},
+ "domains_in_index_daily": {},
+ "results_in_index_daily": {},
+}
+
+
+def test_recorded_removals_appear_in_the_stats_for_today():
+ redis = fakeredis.FakeRedis(decode_responses=True)
+ stats_manager = StatsManager(redis)
+
+ stats_manager.record_blacklisted_removed(3)
+ stats_manager.record_blacklisted_removed(4)
+
+ with patch("mwmbl.crawler.stats.get_counts", return_value=NO_INDEX_COUNTS):
+ stats = stats_manager.get_stats()
+
+ today = str(datetime.utcnow().date())
+ assert stats.blacklisted_results_removed_daily[today] == 7
+
+
+def test_stats_report_zero_removals_for_days_with_no_purge():
+ redis = fakeredis.FakeRedis(decode_responses=True)
+ stats_manager = StatsManager(redis)
+
+ with patch("mwmbl.crawler.stats.get_counts", return_value=NO_INDEX_COUNTS):
+ stats = stats_manager.get_stats()
+
+ assert len(stats.blacklisted_results_removed_daily) == 30
+ assert set(stats.blacklisted_results_removed_daily.values()) == {0}
+
+
+def test_the_daily_count_expires_so_it_cannot_grow_without_bound():
+ redis = fakeredis.FakeRedis(decode_responses=True)
+ StatsManager(redis).record_blacklisted_removed(1)
+
+ key = BLACKLISTED_REMOVED_COUNT_KEY.format(date=datetime.utcnow().date())
+ assert 0 < redis.ttl(key) <= LONG_EXPIRE_SECONDS
+
+
+def test_the_purge_task_records_what_it_removed():
+ """The count has to come from the purge itself, not from what was queued: documents
+ whose domain came off the blacklist while queued are dropped without being removed."""
+ redis = fakeredis.FakeRedis(decode_responses=True)
+ queued = [object()]
+
+ with patch("mwmbl.background.drain_purge_queue", return_value=queued), \
+ patch("mwmbl.background.get_snapshot_blacklist"), \
+ patch("mwmbl.background.TinyIndex"), \
+ patch("mwmbl.background.queue_size", return_value=0), \
+ patch("mwmbl.background.purge_documents", return_value={"bad.test": 2, "worse.test": 3}), \
+ patch("mwmbl.background.stats_manager", StatsManager(redis)):
+ from mwmbl.background import purge_blacklisted_from_queue
+ purge_blacklisted_from_queue.now()
+
+ key = BLACKLISTED_REMOVED_COUNT_KEY.format(date=datetime.utcnow().date())
+ assert redis.get(key) == "5"
+
+
+def test_the_purge_task_records_nothing_when_the_queue_is_empty():
+ redis = fakeredis.FakeRedis(decode_responses=True)
+
+ with patch("mwmbl.background.drain_purge_queue", return_value=[]), \
+ patch("mwmbl.background.stats_manager", StatsManager(redis)):
+ from mwmbl.background import purge_blacklisted_from_queue
+ purge_blacklisted_from_queue.now()
+
+ assert redis.get(BLACKLISTED_REMOVED_COUNT_KEY.format(date=datetime.utcnow().date())) is None