An open source, non-profit web search engine
Count unique URLs in the index with a HyperLogLog, weekly
Claude31e11c5faf19
diff --git a/mwmbl/apps.py b/mwmbl/apps.pyindex cf944b4..aae5332 100644--- a/mwmbl/apps.py+++ b/mwmbl/apps.py@@ -141,6 +141,7 @@ class MwmblConfig(AppConfig):from background_task.models import Taskfrom mwmbl.background import (+ count_index_urls,purge_blacklisted_from_queue,refresh_blacklist_snapshot,report_usage_to_polar,@@ -153,6 +154,7 @@ class MwmblConfig(AppConfig):BLACKLIST_SNAPSHOT_TASK = "mwmbl.background.refresh_blacklist_snapshot"BLACKLIST_PURGE_TASK = "mwmbl.background.purge_blacklisted_from_queue"MODERATION_RETRAIN_TASK = "mwmbl.background.retrain_domain_moderation_model"+ INDEX_COUNT_TASK = "mwmbl.background.count_index_urls"# Sync search counts once per hour (3600 seconds)if not Task.objects.filter(task_name=SYNC_TASK).exists():@@ -187,6 +189,12 @@ class MwmblConfig(AppConfig):repeat_until=None,)+ # Count the unique URLs in the index. The task runs every few minutes but only+ # starts a new scan once a week; most runs either carry on with a scan or do+ # nothing - see mwmbl.count_urls.+ if not Task.objects.filter(task_name=INDEX_COUNT_TASK).exists():+ count_index_urls(repeat=settings.INDEX_COUNT_RUN_INTERVAL_SECONDS, repeat_until=None)+except Exception:# Don't prevent startup if background task scheduling failslog.exception("Failed to schedule background tasks")diff --git a/mwmbl/background.py b/mwmbl/background.pyindex 70f313f..f0ebf98 100644--- a/mwmbl/background.py+++ b/mwmbl/background.py@@ -6,6 +6,7 @@ Django Background Tasks for periodic maintenance:- report_usage_to_polar: reports billable usage overage to Polar once per hour- refresh_blacklist_snapshot: rebuilds the blacklist the search path filters against- purge_blacklisted_from_queue: removes retrieval-filtered documents from the index+ - count_index_urls: counts the unique URLs and domains in the index once a week"""import logging@@ -23,6 +24,7 @@ from django.db import transactionfrom redis import Redisfrom mwmbl import pricing+from mwmbl.count_urls import count_urls_step, get_redisfrom mwmbl.crawler.stats import StatsManagerfrom mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklist, refresh_snapshotfrom mwmbl.indexer.purge_blacklisted import purge_documents@@ -144,6 +146,23 @@ def sync_search_counts():logger.exception("Error syncing search count for key %s", key)+# ---------------------------------------------------------------------------+# Index statistics (Django Background Tasks)+# ---------------------------------------------------------------------------+++@background(schedule=0)+def count_index_urls():+ """+ Read the next slice of the index into the weekly count of its unique URLs.++ Each run stops after INDEX_COUNT_SECONDS_PER_RUN, so the hours-long scan is spread+ over many runs rather than blocking the hourly tasks queued behind it.+ """+ index_path = Path(settings.DATA_PATH) / settings.INDEX_NAME+ count_urls_step(get_redis(), index_path, settings.INDEX_COUNT_SECONDS_PER_RUN)++# ---------------------------------------------------------------------------# Blacklisted-domain maintenance (Django Background Tasks)# ---------------------------------------------------------------------------diff --git a/mwmbl/count_urls.py b/mwmbl/count_urls.pyindex 0e2befe..a11dedf 100644--- a/mwmbl/count_urls.py+++ b/mwmbl/count_urls.py@@ -1,13 +1,24 @@+"""+Count the unique URLs and domains in the index, and the results it holds.++A URL is stored once for every term it is indexed under, spread over many pages, so the+only way to count distinct URLs is to read every page. The URLs and domains go into Redis+HyperLogLogs, which count distinct members to within about 1% in 12 KB each.++Reading the whole index takes many hours, and the background task queue runs one task at+a time, so a single scan would hold up everything else in it. Instead the scan is done a+slice at a time: each run of mwmbl.background.count_index_urls reads pages for a fixed+time budget and records how far it got, and the next run carries on from there. A new+scan starts once the previous one is INDEX_COUNT_INTERVAL_DAYS old.+"""+import os-from collections import Counter-from datetime import datetime, timedelta, timezone+from datetime import date, timedeltafrom logging import getLoggerfrom pathlib import Path-from random import Random-from time import sleep+from time import monotonicfrom django.conf import settings-from pydistinct.stats_estimators import smoothed_jackknife_estimatorfrom redis import Redisfrom mwmbl.tinysearchengine.indexer import Document, PageError, TinyIndex@@ -18,78 +29,119 @@ INDEX_DOMAIN_COUNT_KEY = "index-domain-count-{date}"INDEX_URL_COUNT_KEY = "index-url-count-{date}"INDEX_DOMAIN_RESULT_COUNT_KEY = "index-domain-result-count-{date}"+# The scan in progress: a hash of the next page to read and the results counted so far,+# and the two HyperLogLogs being filled.+INDEX_SCAN_KEY = "index-count-scan"+INDEX_SCAN_URL_HLL_KEY = "index-count-scan-urls"+INDEX_SCAN_DOMAIN_HLL_KEY = "index-count-scan-domains"+INDEX_SCAN_LAST_STARTED_KEY = "index-count-scan-last-started"+LONG_EXPIRE_SECONDS = 60 * 60 * 24 * 30-PAGE_PROPORTION_TO_SAMPLE = 0.01+# Pages read between progress updates. The time budget is checked once per batch, and a+# batch is also the most that is read twice if the process dies mid-run.+NUM_PAGES_IN_BATCH = 1024logger = getLogger(__name__)-random = Random(1)def get_redis():return Redis.from_url(os.environ.get("REDIS_URL", "redis://127.0.0.1:6379"), decode_responses=True)-def count_urls_continuously():- while True:- start_time = datetime.now(timezone.utc)- count_urls()- end_time = datetime.now(timezone.utc)- total_time = end_time - start_time- time_remaining = 60 * 60 * 24 - total_time.total_seconds()- logger.info(f"Counting took {total_time}. Sleeping for {timedelta(seconds=time_remaining)}.")- sleep(time_remaining)+def count_urls_step(redis: Redis, index_path: Path, time_budget_seconds: float):+ """Advance the index scan by up to time_budget_seconds, starting one if it is due.--def count_urls():- start_time = datetime.now(timezone.utc)-- index_path = Path(settings.DATA_PATH) / settings.INDEX_NAME+ When the scan reaches the last page, the counts are published under today's date.+ """+ scan = redis.hgetall(INDEX_SCAN_KEY)+ if scan:+ next_page = int(scan["next_page"])+ elif _scan_due(redis):+ _start_scan(redis)+ next_page = 0+ else:+ return++ deadline = monotonic() + time_budget_seconds+ first_page = next_pagewith TinyIndex(item_factory=Document, index_path=index_path) as index:- page_sample = set()- num_pages_to_sample = max(100, int(index.num_pages * PAGE_PROPORTION_TO_SAMPLE))- logger.info(f"Sampling {num_pages_to_sample} pages.")- while len(page_sample) < num_pages_to_sample:- page_sample.add(random.randrange(index.num_pages))-- url_counts = Counter()- domain_counts = Counter()- total_docs = 0- for i in page_sample:- try:- page = index.get_page(i)- except PageError:- # An unlocked read while the indexer is writing, so most of these are torn- # rather than damaged. Count the page as empty, as retrieve() does, rather- # than abandoning the sample.- logger.warning("Could not read index page %d while counting URLs", i)- continue- url_counts.update({doc.url for doc in page})- domains = [parse_url(doc.url).netloc for doc in page]- domain_counts.update(domains)- total_docs += len(page)-- num_results_estimate = int(total_docs / PAGE_PROPORTION_TO_SAMPLE)- url_count_estimate = smoothed_jackknife_estimator(attributes=dict(url_counts.items()), n_pop=num_results_estimate)- domain_count_estimate = smoothed_jackknife_estimator(- attributes=dict(domain_counts.items()), n_pop=num_results_estimate- )+ num_pages = index.num_pages+ # The budget is checked after each batch rather than before, so every run reads+ # at least one batch however long the one before it overran.+ while next_page < num_pages:+ end_page = min(next_page + NUM_PAGES_IN_BATCH, num_pages)+ _count_pages(redis, index, next_page, end_page)+ next_page = end_page+ if monotonic() >= deadline:+ break++ logger.info(f"Counted URLs in index pages {first_page} to {next_page} of {num_pages}.")++ if next_page >= num_pages:+ _finish_scan(redis)+++def _scan_due(redis: Redis) -> bool:+ last_started = redis.get(INDEX_SCAN_LAST_STARTED_KEY)+ if last_started is None:+ return True+ days_since_last_scan = utc_today() - date.fromisoformat(last_started)+ return days_since_last_scan >= timedelta(days=settings.INDEX_COUNT_INTERVAL_DAYS)+++def _start_scan(redis: Redis):+ logger.info("Starting a scan to count the URLs in the index.")+ pipeline = redis.pipeline()+ pipeline.delete(INDEX_SCAN_URL_HLL_KEY, INDEX_SCAN_DOMAIN_HLL_KEY)+ pipeline.hset(INDEX_SCAN_KEY, mapping={"next_page": 0, "num_results": 0})+ pipeline.set(INDEX_SCAN_LAST_STARTED_KEY, str(utc_today()))+ pipeline.execute()+++def _count_pages(redis: Redis, index: TinyIndex, start_page: int, end_page: int):+ urls = set()+ domains = set()+ num_results = 0+ for i in range(start_page, end_page):+ try:+ page = index.get_page(i)+ except PageError:+ # An unlocked read while the indexer is writing, so most of these are torn+ # rather than damaged. Count the page as empty, as retrieve() does, rather+ # than abandoning the scan.+ logger.warning("Could not read index page %d while counting URLs", i)+ continue+ urls |= {doc.url for doc in page}+ domains |= {parse_url(doc.url).netloc for doc in page}+ num_results += len(page)++ # One transaction, so the results are never counted twice: either this batch is+ # recorded along with the page it got up to, or neither is and it is read again.+ pipeline = redis.pipeline()+ pipeline.pfadd(INDEX_SCAN_URL_HLL_KEY, *urls)+ pipeline.pfadd(INDEX_SCAN_DOMAIN_HLL_KEY, *domains)+ pipeline.hincrby(INDEX_SCAN_KEY, "num_results", num_results)+ pipeline.hset(INDEX_SCAN_KEY, "next_page", end_page)+ pipeline.execute()+++def _finish_scan(redis: Redis):+ url_count = redis.pfcount(INDEX_SCAN_URL_HLL_KEY)+ domain_count = redis.pfcount(INDEX_SCAN_DOMAIN_HLL_KEY)+ num_results = int(redis.hget(INDEX_SCAN_KEY, "num_results"))logger.info(- f"Estimated {url_count_estimate} unique URLs, {domain_count_estimate} unique domains, "- f"and {num_results_estimate} results in the index."+ f"Counted {url_count} unique URLs, {domain_count} unique domains and {num_results} results in the index.")- redis = get_redis()-today = utc_today()- _set_count(INDEX_URL_COUNT_KEY, redis, today, int(url_count_estimate))- _set_count(INDEX_DOMAIN_COUNT_KEY, redis, today, int(domain_count_estimate))- _set_count(INDEX_RESULT_COUNT_KEY, redis, today, num_results_estimate)+ _set_count(INDEX_URL_COUNT_KEY, redis, today, url_count)+ _set_count(INDEX_DOMAIN_COUNT_KEY, redis, today, domain_count)+ _set_count(INDEX_RESULT_COUNT_KEY, redis, today, num_results)- end_time = datetime.now(timezone.utc)- logger.info(f"Counting took {end_time - start_time}.")+ redis.delete(INDEX_SCAN_KEY, INDEX_SCAN_URL_HLL_KEY, INDEX_SCAN_DOMAIN_HLL_KEY)def _set_count(key, redis, today, count):@@ -134,17 +186,3 @@ def _get_count(redis, count_dict, key, date_i):count = redis.get(key.format(date=date_i))if count is not None:count_dict[str(date_i)] = int(count)---if __name__ == "__main__":- # configure logging- import logging-- logging.basicConfig(level=logging.INFO)-- count_urls()- counts = get_counts()- print("Counts", counts, sep="\n")-- github_count = get_domain_result_count("github.com")- print("GitHub count", github_count)diff --git a/mwmbl/main.py b/mwmbl/main.pyindex 659738d..dacc1ea 100644--- a/mwmbl/main.py+++ b/mwmbl/main.py@@ -45,22 +45,19 @@ def run():from django.conf import settingsfrom mwmbl import background- from mwmbl.count_urls import count_urls_continuouslyif settings.STATIC_ROOT:call_command("collectstatic", "--clear", "--noinput")call_command("migrate")- # DEPRECATED: copy_indexes and count_urls are no longer deployed. "server" is the only- # app that runs, and it now also runs the background task queue (see below). They are- # kept here rather than deleted because the code they call is still reachable from the- # management commands and the standalone crawler; treat them as unmaintained.+ # DEPRECATED: copy_indexes is no longer deployed. "server" is the only app that runs,+ # and it now also runs the background task queue (see below). It is kept here rather+ # than deleted because the code it calls is still reachable from the management+ # commands and the standalone crawler; treat it as unmaintained.mwmbl_app = os.environ["MWMBL_APP"]if mwmbl_app == "copy_indexes":background.copy_indexes_continuously()- elif mwmbl_app == "count_urls":- count_urls_continuously()elif mwmbl_app == "process_tasks":# The task queue on its own, for running it in a container of its own rather than# alongside the server. Not currently deployed - RUN_BACKGROUND_TASKS on thediff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.pyindex 3901a9a..639a6e9 100644--- a/mwmbl/settings_common.py+++ b/mwmbl/settings_common.py@@ -359,6 +359,13 @@ BLACKLIST_SNAPSHOT_CHECK_SECONDS = 300 # how often a worker checks Redis for aBLACKLIST_SNAPSHOT_REFRESH_SECONDS = 6 * 60 * 60 # how often the snapshot is rebuilt from the remote listsBLACKLIST_PURGE_INTERVAL_SECONDS = 300 # how often the purge queue is drainedBLACKLIST_PURGE_BATCH_SIZE = 1000 # documents removed from the index per purge run++# Counting the unique URLs in the index means reading all of it, which takes hours. It is+# done a slice at a time so it never holds up the rest of the task queue - see+# mwmbl.count_urls.+INDEX_COUNT_INTERVAL_DAYS = 7 # how often a new scan of the index starts+INDEX_COUNT_RUN_INTERVAL_SECONDS = 300 # how often a slice of the scan runs+INDEX_COUNT_SECONDS_PER_RUN = 120 # how long each slice reads pages for# How far ahead approving a domain submission schedules a snapshot rebuild. Approvers work# through submissions in batches, so the delay collapses a batch into one rebuild rather# than one per approval - see mwmbl.signals.diff --git a/test/test_apps_background_scheduling.py b/test/test_apps_background_scheduling.pyindex 7b38e87..273dc62 100644--- a/test/test_apps_background_scheduling.py+++ b/test/test_apps_background_scheduling.py@@ -21,8 +21,9 @@ SYNC_TASK = "mwmbl.background.sync_search_counts"POLAR_REPORT_TASK = "mwmbl.background.report_usage_to_polar"BLACKLIST_SNAPSHOT_TASK = "mwmbl.background.refresh_blacklist_snapshot"BLACKLIST_PURGE_TASK = "mwmbl.background.purge_blacklisted_from_queue"+INDEX_COUNT_TASK = "mwmbl.background.count_index_urls"-ALL_TASKS = {SYNC_TASK, POLAR_REPORT_TASK, BLACKLIST_SNAPSHOT_TASK, BLACKLIST_PURGE_TASK}+ALL_TASKS = {SYNC_TASK, POLAR_REPORT_TASK, BLACKLIST_SNAPSHOT_TASK, BLACKLIST_PURGE_TASK, INDEX_COUNT_TASK}@pytest.fixture(autouse=True)@@ -98,3 +99,12 @@ def test_a_one_off_snapshot_rebuild_does_not_suppress_the_periodic_one():MwmblConfig._schedule_background_tasks()assert Task.objects.filter(task_name=BLACKLIST_SNAPSHOT_TASK, repeat__gt=0).count() == 1+++def test_index_count_task_repeats_at_the_configured_interval():+ MwmblConfig._schedule_background_tasks()++ index_count = Task.objects.get(task_name=INDEX_COUNT_TASK)++ assert index_count.repeat == settings.INDEX_COUNT_RUN_INTERVAL_SECONDSdiff --git a/test/test_count_urls.py b/test/test_count_urls.pynew file mode 100644index 0000000..6b14088--- /dev/null+++ b/test/test_count_urls.py@@ -0,0 +1,124 @@+"""+Tests for the weekly count of unique URLs in the index.++The scan is spread over many background task runs, each picking up where the last left+off, so what matters is that the slices add up to one correct count however the scan is+cut, and that a new scan only starts once a week.+"""++from datetime import timedelta+from unittest.mock import patch++import fakeredis+import pytest++from mwmbl import count_urls+from mwmbl.count_urls import (+ INDEX_DOMAIN_COUNT_KEY,+ INDEX_RESULT_COUNT_KEY,+ INDEX_SCAN_KEY,+ INDEX_SCAN_LAST_STARTED_KEY,+ INDEX_URL_COUNT_KEY,+ count_urls_step,+)+from mwmbl.tinysearchengine.indexer import PAGE_SIZE, Document, PageError, TinyIndex+from mwmbl.utils import utc_today++NUM_PAGES = 10+++def _document(url, term):+ return Document(title=f"Title of {url}", url=url, extract="An extract", score=1.0, term=term)+++def index_path(tmp_path):+ """An index whose URLs repeat across pages, as a URL indexed under several terms does."""+ path = tmp_path / "count.tinysearch"+ TinyIndex.create(item_factory=Document, index_path=str(path), num_pages=NUM_PAGES, page_size=PAGE_SIZE)+ with TinyIndex(Document, str(path), "w") as index:+ index.store_in_page(0, [_document("https://a.test/1", "one"), _document("https://a.test/2", "one")])+ index.store_in_page(3, [_document("https://a.test/1", "two"), _document("https://b.test/1", "two")])+ index.store_in_page(9, [_document("https://c.test/1", "three")])+ return path+++def redis():+ return fakeredis.FakeRedis(decode_responses=True)+++def _count(redis, key):+ return int(redis.get(key.format(date=utc_today())))+++def test_a_full_scan_counts_unique_urls_domains_and_results(redis, index_path):+ count_urls_step(redis, index_path, time_budget_seconds=60)++ assert _count(redis, INDEX_URL_COUNT_KEY) == 4+ assert _count(redis, INDEX_DOMAIN_COUNT_KEY) == 3+ assert _count(redis, INDEX_RESULT_COUNT_KEY) == 5+ assert not redis.exists(INDEX_SCAN_KEY)+++def test_a_scan_cut_into_slices_gives_the_same_counts(redis, index_path):+ with patch.object(count_urls, "NUM_PAGES_IN_BATCH", 2):+ # A zero budget still reads one batch per run, so this takes five runs.+ for _ in range(4):+ count_urls_step(redis, index_path, time_budget_seconds=0)+ assert redis.get(INDEX_URL_COUNT_KEY.format(date=utc_today())) is None++ count_urls_step(redis, index_path, time_budget_seconds=0)++ assert _count(redis, INDEX_URL_COUNT_KEY) == 4+ assert _count(redis, INDEX_DOMAIN_COUNT_KEY) == 3+ assert _count(redis, INDEX_RESULT_COUNT_KEY) == 5+++def test_no_new_scan_starts_within_the_interval(redis, index_path, settings):+ count_urls_step(redis, index_path, time_budget_seconds=60)+ redis.delete(INDEX_URL_COUNT_KEY.format(date=utc_today()))++ count_urls_step(redis, index_path, time_budget_seconds=60)++ assert redis.get(INDEX_URL_COUNT_KEY.format(date=utc_today())) is None+ assert not redis.exists(INDEX_SCAN_KEY)+++def test_a_new_scan_starts_once_the_interval_has_passed(redis, index_path, settings):+ last_started = utc_today() - timedelta(days=settings.INDEX_COUNT_INTERVAL_DAYS)+ redis.set(INDEX_SCAN_LAST_STARTED_KEY, str(last_started))++ count_urls_step(redis, index_path, time_budget_seconds=60)++ assert _count(redis, INDEX_URL_COUNT_KEY) == 4+ assert redis.get(INDEX_SCAN_LAST_STARTED_KEY) == str(utc_today())+++def test_a_new_scan_does_not_inherit_the_last_ones_urls(redis, index_path, tmp_path):+ count_urls_step(redis, index_path, time_budget_seconds=60)+ redis.delete(INDEX_SCAN_LAST_STARTED_KEY)++ with TinyIndex(Document, str(index_path), "w") as index:+ index.store_in_page(0, [])+ index.store_in_page(3, [])++ count_urls_step(redis, index_path, time_budget_seconds=60)++ assert _count(redis, INDEX_URL_COUNT_KEY) == 1+ assert _count(redis, INDEX_RESULT_COUNT_KEY) == 1+++def test_an_unreadable_page_is_skipped_rather_than_ending_the_scan(redis, index_path):+ get_page = TinyIndex.get_page++ def get_page_failing_on_page_zero(self, i):+ if i == 0:+ raise PageError("torn page")+ return get_page(self, i)++ with patch.object(TinyIndex, "get_page", get_page_failing_on_page_zero):+ count_urls_step(redis, index_path, time_budget_seconds=60)++ assert _count(redis, INDEX_URL_COUNT_KEY) == 3+ assert _count(redis, INDEX_RESULT_COUNT_KEY) == 3