An open source, non-profit web search engine
Make the weekly index count survive errors, races and lost state
Claude2703d8820d7d
diff --git a/mwmbl/background.py b/mwmbl/background.pyindex f0ebf98..851a8d8 100644--- a/mwmbl/background.py+++ b/mwmbl/background.py@@ -158,9 +158,17 @@ def count_index_urls():Each run stops after INDEX_COUNT_SECONDS_PER_RUN, so the hours-long scan is spreadover many runs rather than blocking the hourly tasks queued behind it.++ It never raises. django-background-tasks only repeats a task that succeeds, and after+ MAX_ATTEMPTS failures it deletes the row, so one bad spell - Redis down, the index+ missing - would stop the count until the next deploy rescheduled it. The scan's state+ is in Redis, so the next run just tries again."""index_path = Path(settings.DATA_PATH) / settings.INDEX_NAME- count_urls_step(get_redis(), index_path, settings.INDEX_COUNT_SECONDS_PER_RUN)+ try:+ count_urls_step(get_redis(), index_path, settings.INDEX_COUNT_SECONDS_PER_RUN)+ except Exception:+ logger.exception("Error counting the URLs in the index")# ---------------------------------------------------------------------------diff --git a/mwmbl/count_urls.py b/mwmbl/count_urls.pyindex a11dedf..21704b7 100644--- a/mwmbl/count_urls.py+++ b/mwmbl/count_urls.py@@ -5,11 +5,15 @@ A URL is stored once for every term it is indexed under, spread over many pages,only way to count distinct URLs is to read every page. The URLs and domains go into RedisHyperLogLogs, 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.+Reading the whole index takes many hours, so it 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+finished INDEX_COUNT_INTERVAL_DAYS ago. Short runs matter for two reasons. The task queue+runs tasks one at a time (BACKGROUND_TASK_RUN_ASYNC is left at its default, False), so a+long run would hold up the hourly tasks behind it. And a task that runs past MAX_RUN_TIME+loses its lock and can be picked up again, so INDEX_COUNT_SECONDS_PER_RUN must stay well+under it. Even so, each batch is recorded with a compare-and-set on the scan's cursor, so+two runs that do overlap never count the same pages twice."""import os@@ -19,7 +23,7 @@ from pathlib import Pathfrom time import monotonicfrom django.conf import settings-from redis import Redis+from redis import Redis, WatchErrorfrom mwmbl.tinysearchengine.indexer import Document, PageError, TinyIndexfrom mwmbl.utils import parse_url, utc_today@@ -30,13 +34,23 @@ 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.+# and the two HyperLogLogs being filled. They expire if the scan stops being advanced, so+# an abandoned scan does not leave them behind.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"+INDEX_SCAN_EXPIRE_SECONDS = 60 * 60 * 24 * 2-LONG_EXPIRE_SECONDS = 60 * 60 * 24 * 30+# The date the last scan finished. It is set only once the counts are published, so losing+# the scan state mid-scan means the next run starts again rather than waiting a week.+INDEX_SCAN_LAST_FINISHED_KEY = "index-count-scan-last-finished"++# Published counts are kept long enough that the 30 day window in get_counts always has an+# earlier count to carry forward into its first days.+LONG_EXPIRE_SECONDS = 60 * 60 * 24 * 60++# The position of the URL in a stored document's tuple - see Document.as_tuple.+URL_INDEX = 1# 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.@@ -72,7 +86,11 @@ def count_urls_step(redis: Redis, index_path: Path, time_budget_seconds: float):# 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)+ if not _count_pages(redis, index, next_page, end_page):+ logger.warning(+ f"The index count scan moved on from page {next_page} under this run; leaving it to the other one."+ )+ returnnext_page = end_pageif monotonic() >= deadline:break@@ -84,10 +102,10 @@ def count_urls_step(redis: Redis, index_path: Path, time_budget_seconds: float):def _scan_due(redis: Redis) -> bool:- last_started = redis.get(INDEX_SCAN_LAST_STARTED_KEY)- if last_started is None:+ last_finished = redis.get(INDEX_SCAN_LAST_FINISHED_KEY)+ if last_finished is None:return True- days_since_last_scan = utc_today() - date.fromisoformat(last_started)+ days_since_last_scan = utc_today() - date.fromisoformat(last_finished)return days_since_last_scan >= timedelta(days=settings.INDEX_COUNT_INTERVAL_DAYS)@@ -96,35 +114,55 @@ def _start_scan(redis: Redis):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.expire(INDEX_SCAN_KEY, INDEX_SCAN_EXPIRE_SECONDS)pipeline.execute()-def _count_pages(redis: Redis, index: TinyIndex, start_page: int, end_page: int):+def _count_pages(redis: Redis, index: TinyIndex, start_page: int, end_page: int) -> bool:+ """Add pages start_page to end_page to the scan, if it is still at start_page.++ Returns False, recording nothing, if the scan has moved on or gone in the meantime.+ """urls = set()- domains = set()num_results = 0for i in range(start_page, end_page):try:- page = index.get_page(i)- except PageError:+ # The raw tuples rather than get_page: only the URL is needed, and building+ # a Document for every item is most of the cost of reading a page.+ page = index._get_page_tuples(i)+ except (PageError, OSError):# 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)+ # than abandoning the scan - which, for a device error, would fail on the+ # same page every run.+ logger.warning("Could not read index page %d while counting URLs", i, exc_info=True)continue- urls |= {doc.url for doc in page}- domains |= {parse_url(doc.url).netloc for doc in page}+ urls |= {item[URL_INDEX] for item in page}num_results += len(page)+ # Each URL is on many pages, so its domain is worked out once per batch, not per page.+ domains = {parse_url(url).netloc for url in urls}+# 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()+ # recorded along with the page it got up to, or neither is and it is read again. The+ # watch on the cursor means a second run reading the same batch records nothing.+ with redis.pipeline() as pipeline:+ try:+ pipeline.watch(INDEX_SCAN_KEY)+ next_page = pipeline.hget(INDEX_SCAN_KEY, "next_page")+ if next_page is None or int(next_page) != start_page:+ return False+ pipeline.multi()+ 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)+ for key in (INDEX_SCAN_KEY, INDEX_SCAN_URL_HLL_KEY, INDEX_SCAN_DOMAIN_HLL_KEY):+ pipeline.expire(key, INDEX_SCAN_EXPIRE_SECONDS)+ pipeline.execute()+ except WatchError:+ return False+ return Truedef _finish_scan(redis: Redis):@@ -141,7 +179,10 @@ def _finish_scan(redis: Redis):_set_count(INDEX_DOMAIN_COUNT_KEY, redis, today, domain_count)_set_count(INDEX_RESULT_COUNT_KEY, redis, today, num_results)- redis.delete(INDEX_SCAN_KEY, INDEX_SCAN_URL_HLL_KEY, INDEX_SCAN_DOMAIN_HLL_KEY)+ pipeline = redis.pipeline()+ pipeline.set(INDEX_SCAN_LAST_FINISHED_KEY, str(today))+ pipeline.delete(INDEX_SCAN_KEY, INDEX_SCAN_URL_HLL_KEY, INDEX_SCAN_DOMAIN_HLL_KEY)+ pipeline.execute()def _set_count(key, redis, today, count):@@ -149,25 +190,17 @@ def _set_count(key, redis, today, count):redis.expire(key.format(date=today), LONG_EXPIRE_SECONDS)-def get_counts() -> dict[str, dict[str, int]]:- redis = get_redis()-- today = utc_today()-- urls_in_index_daily = {}- domains_in_index_daily = {}- results_in_index_daily = {}- for i in range(29, -1, -1):- date_i = today - timedelta(days=i)-- _get_count(redis, urls_in_index_daily, INDEX_URL_COUNT_KEY, date_i)- _get_count(redis, domains_in_index_daily, INDEX_DOMAIN_COUNT_KEY, date_i)- _get_count(redis, results_in_index_daily, INDEX_RESULT_COUNT_KEY, date_i)+def get_counts(redis: Redis | None = None) -> dict[str, dict[str, int]]:+ """The index counts for each of the last 30 days.+ A scan only finishes about once a week, so each day gets the latest count published+ on or before it - the size of the index as last measured on that day.+ """+ redis = redis or get_redis()return {- "urls_in_index_daily": urls_in_index_daily,- "domains_in_index_daily": domains_in_index_daily,- "results_in_index_daily": results_in_index_daily,+ "urls_in_index_daily": _get_daily_counts(redis, INDEX_URL_COUNT_KEY),+ "domains_in_index_daily": _get_daily_counts(redis, INDEX_DOMAIN_COUNT_KEY),+ "results_in_index_daily": _get_daily_counts(redis, INDEX_RESULT_COUNT_KEY),}@@ -179,10 +212,18 @@ def get_domain_result_count(domain: str) -> int:return 0 if count is None else int(count)-def _get_count(redis, count_dict, key, date_i):- """- Get the count for a given date and set it in the count_dict.- """- count = redis.get(key.format(date=date_i))- if count is not None:- count_dict[str(date_i)] = int(count)+def _get_daily_counts(redis: Redis, key: str, num_days: int = 30) -> dict[str, int]:+ today = utc_today()+ # Look back far enough before the window to find a count to carry into its first days.+ first_day = today - timedelta(days=num_days - 1 + 2 * settings.INDEX_COUNT_INTERVAL_DAYS)+ days = [first_day + timedelta(days=i) for i in range((today - first_day).days + 1)]+ counts = redis.mget([key.format(date=day) for day in days])++ daily_counts = {}+ latest = None+ for day, count in zip(days, counts):+ if count is not None:+ latest = int(count)+ if latest is not None and day > today - timedelta(days=num_days):+ daily_counts[str(day)] = latest+ return daily_countsdiff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.pyindex 639a6e9..e26b24b 100644--- a/mwmbl/settings_common.py+++ b/mwmbl/settings_common.py@@ -365,7 +365,7 @@ BLACKLIST_PURGE_BATCH_SIZE = 1000 # documents removed from the index per purge# mwmbl.count_urls.INDEX_COUNT_INTERVAL_DAYS = 7 # how often a new scan of the index startsINDEX_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+INDEX_COUNT_SECONDS_PER_RUN = 120 # how long each slice reads pages for; keep well under MAX_RUN_TIME# 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_count_urls.py b/test/test_count_urls.pyindex 6b14088..31eec26 100644--- a/test/test_count_urls.py+++ b/test/test_count_urls.py@@ -17,9 +17,11 @@ from mwmbl.count_urls import (INDEX_DOMAIN_COUNT_KEY,INDEX_RESULT_COUNT_KEY,INDEX_SCAN_KEY,- INDEX_SCAN_LAST_STARTED_KEY,+ INDEX_SCAN_LAST_FINISHED_KEY,+ INDEX_SCAN_URL_HLL_KEY,INDEX_URL_COUNT_KEY,count_urls_step,+ get_counts,)from mwmbl.tinysearchengine.indexer import PAGE_SIZE, Document, PageError, TinyIndexfrom mwmbl.utils import utc_today@@ -86,18 +88,18 @@ def test_no_new_scan_starts_within_the_interval(redis, index_path, settings):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))+ last_finished = utc_today() - timedelta(days=settings.INDEX_COUNT_INTERVAL_DAYS)+ redis.set(INDEX_SCAN_LAST_FINISHED_KEY, str(last_finished))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())+ assert redis.get(INDEX_SCAN_LAST_FINISHED_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)+ redis.delete(INDEX_SCAN_LAST_FINISHED_KEY)with TinyIndex(Document, str(index_path), "w") as index:index.store_in_page(0, [])@@ -109,16 +111,78 @@ def test_a_new_scan_does_not_inherit_the_last_ones_urls(redis, index_path, tmp_passert _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[email protected]("error", [PageError("torn page"), OSError(5, "Input/output error")])+def test_an_unreadable_page_is_skipped_rather_than_ending_the_scan(redis, index_path, error):+ get_page_tuples = TinyIndex._get_page_tuples- def get_page_failing_on_page_zero(self, i):+ def get_page_tuples_failing_on_page_zero(self, i, term=None):if i == 0:- raise PageError("torn page")- return get_page(self, i)+ raise error+ return get_page_tuples(self, i, term)- with patch.object(TinyIndex, "get_page", get_page_failing_on_page_zero):+ with patch.object(TinyIndex, "_get_page_tuples", get_page_tuples_failing_on_page_zero):count_urls_step(redis, index_path, time_budget_seconds=60)assert _count(redis, INDEX_URL_COUNT_KEY) == 3assert _count(redis, INDEX_RESULT_COUNT_KEY) == 3+++def test_a_scan_whose_state_is_lost_starts_again(redis, index_path):+ with patch.object(count_urls, "NUM_PAGES_IN_BATCH", 2):+ count_urls_step(redis, index_path, time_budget_seconds=0)+ redis.delete(INDEX_SCAN_KEY)++ count_urls_step(redis, index_path, time_budget_seconds=0)++ assert redis.hget(INDEX_SCAN_KEY, "next_page") == "2"+++def test_the_scan_state_expires_if_it_stops_being_advanced(redis, index_path):+ with patch.object(count_urls, "NUM_PAGES_IN_BATCH", 2):+ count_urls_step(redis, index_path, time_budget_seconds=0)++ assert redis.ttl(INDEX_SCAN_KEY) > 0+ assert redis.ttl(INDEX_SCAN_URL_HLL_KEY) > 0+++def test_a_batch_another_run_has_already_counted_is_not_counted_again(redis, index_path):+ count_pages = count_urls._count_pages++ def count_pages_raced_by_another_run(redis, index, start_page, end_page):+ # The other run reads and records the same batch first.+ assert count_pages(redis, index, start_page, end_page)+ return count_pages(redis, index, start_page, end_page)++ with patch.object(count_urls, "_count_pages", count_pages_raced_by_another_run):+ count_urls_step(redis, index_path, time_budget_seconds=60)++ assert not redis.exists(INDEX_URL_COUNT_KEY.format(date=utc_today()))++ count_urls_step(redis, index_path, time_budget_seconds=60)++ assert _count(redis, INDEX_RESULT_COUNT_KEY) == 5+++def test_each_day_reports_the_latest_count_published_on_or_before_it(redis):+ today = utc_today()+ redis.set(INDEX_URL_COUNT_KEY.format(date=today - timedelta(days=33)), 100)+ redis.set(INDEX_URL_COUNT_KEY.format(date=today - timedelta(days=10)), 200)++ urls_daily = get_counts(redis)["urls_in_index_daily"]++ assert len(urls_daily) == 30+ assert urls_daily[str(today - timedelta(days=29))] == 100+ assert urls_daily[str(today - timedelta(days=11))] == 100+ assert urls_daily[str(today - timedelta(days=10))] == 200+ assert urls_daily[str(today)] == 200+++def test_no_counts_are_reported_before_the_first_scan(redis):+ assert get_counts(redis)["urls_in_index_daily"] == {}+++def test_the_background_task_does_not_raise_so_it_keeps_repeating():+ from mwmbl import background++ with patch.object(background, "count_urls_step", side_effect=ConnectionError("Redis is down")):+ background.count_index_urls.now()