An open source, non-profit web search engine
Remove the dead batch-indexing pipeline
Daoud Clarkebf05637b730d
diff --git a/mwmbl/apps.py b/mwmbl/apps.pyindex b230425..cf944b4 100644--- a/mwmbl/apps.py+++ b/mwmbl/apps.py@@ -3,9 +3,6 @@ from pathlib import Pathfrom django.apps import AppConfigfrom django.conf import settings-from mwmbl.database import Database-from mwmbl.indexer.indexdb import IndexDatabase-def create_index(index_name, num_pages, rebuild_on_mismatch=False):"""Create the index file if it is missing, and check an existing one is the right shape.@@ -81,12 +78,6 @@ def _replace_index_file(index_path, num_pages):temp_path.replace(index_path)-def create_index_db():- with Database() as db:- index_db = IndexDatabase(db.connection)- index_db.create_tables()--class MwmblConfig(AppConfig):name = "mwmbl"verbose_name = "Mwmbl Application"@@ -99,7 +90,6 @@ class MwmblConfig(AppConfig):# grace in app.json has to cover.create_index(settings.EXTERNAL_CACHE_INDEX_NAME, settings.EXTERNAL_CACHE_NUM_PAGES, rebuild_on_mismatch=True)if settings.HAS_DATABASE:- create_index_db()import mwmbl.signals # noqa: F401 - connects the post_save receiversself._schedule_background_tasks()diff --git a/mwmbl/background.py b/mwmbl/background.pyindex e8dc6ab..99cf5cd 100644--- a/mwmbl/background.py+++ b/mwmbl/background.py@@ -1,7 +1,7 @@"""-Script that updates data in a background process.+Background work that runs outside the request path.-Also contains Django Background Tasks for periodic maintenance:+Django Background Tasks for periodic maintenance:- sync_search_counts: syncs Redis monthly counters → DB once per hour- report_usage_to_polar: reports billable usage overage to Polar once per hour- refresh_blacklist_snapshot: rebuilds the blacklist the search path filters against@@ -24,8 +24,6 @@ from redis import Redisfrom mwmbl import pricingfrom mwmbl.crawler.stats import StatsManager-from mwmbl.indexer import historical, index_batches-from mwmbl.indexer.batch_cache import BatchCachefrom mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklist, refresh_snapshotfrom mwmbl.indexer.purge_blacklisted import purge_documentsfrom mwmbl.indexer.purge_queue import drain_purge_queue, queue_size@@ -46,25 +44,6 @@ 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")-- historical.run()- index_path = Path(data_path) / settings.INDEX_NAME- batch_cache = BatchCache(Path(data_path) / settings.BATCH_DIR_NAME)-- while True:- try:- batch_cache.retrieve_batches(num_batches=10000)- except Exception:- logger.exception("Error retrieving batches")- try:- index_batches.run(batch_cache, index_path)- except Exception:- logger.exception("Error indexing batches")- sleep(10)--def copy_all_indexes(new_index_path):old_indexes = OldIndex.objects.all()logger.info(f"Found {len(old_indexes)} old indexes")diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.pyindex 538bcca..43be995 100644--- a/mwmbl/crawler/app.py+++ b/mwmbl/crawler/app.py@@ -40,7 +40,6 @@ from mwmbl.settings import (VERSION,)from mwmbl.tinysearchengine.indexer import Document-from mwmbl.utils import utc_todaystats_manager = StatsManager(Redis.from_url(os.environ.get("REDIS_URL", "redis://127.0.0.1:6379"), decode_responses=True)@@ -384,26 +383,3 @@ def get_subfolders(prefix):items = client.list_objects(Bucket=BUCKET_NAME, Prefix=prefix, Delimiter="/")item_keys = [item["Prefix"][len(prefix) :].strip("/") for item in items["CommonPrefixes"]]return item_keys---def get_batches_for_date(date_str):- check_date_str(date_str)- prefix = f"1/{VERSION}/{date_str}/1/"- cache_filename = prefix + "batches.json.gz"- cache_url = PUBLIC_URL_PREFIX + cache_filename- try:- cached_batches = json.loads(gzip.decompress(requests.get(cache_url).content))- print(f"Got cached batches for {date_str}")- return cached_batches- except gzip.BadGzipFile:- pass-- batches = get_batches_for_prefix(prefix)- result = {"batch_urls": [f"{PUBLIC_URL_PREFIX}{batch}" for batch in sorted(batches)]}- if date_str != str(utc_today()):- # Don't cache data from today since it may change- data = gzip.compress(json.dumps(result).encode("utf8"))- upload(data, cache_filename)- print(f"Cached batches for {date_str} in {PUBLIC_URL_PREFIX}{cache_filename}")- print(f"Returning {len(result['batch_urls'])} batches for {date_str}")- return resultdiff --git a/mwmbl/indexer/batch_cache.py b/mwmbl/indexer/batch_cache.pydeleted file mode 100644index 3d460f4..0000000--- a/mwmbl/indexer/batch_cache.py+++ /dev/null@@ -1,90 +0,0 @@-"""-Store for local batches.--We store them in a directory on the local machine.-"""--import gzip-import json-import os-from logging import getLogger-from multiprocessing.pool import ThreadPool-from pathlib import Path-from urllib.parse import urlparse--from pydantic import ValidationError--from mwmbl.crawler.batch import HashedBatch-from mwmbl.database import Database-from mwmbl.indexer.indexdb import BatchStatus, IndexDatabase-from mwmbl.retry import retry_requests--logger = getLogger(__name__)---class BatchCache:- num_threads = 20-- def __init__(self, repo_path):- os.makedirs(repo_path, exist_ok=True)- self.path = repo_path-- def get_cached(self, batch_urls: list[str]) -> dict[str, HashedBatch]:- batches = {}- for url in batch_urls:- path = self.get_path_from_url(url)- try:- data = gzip.GzipFile(path).read()- except FileNotFoundError:- logger.exception(f"Missing batch file: {path}")- continue- try:- batch = HashedBatch.parse_raw(data)- except ValidationError:- logger.exception(f"Unable to parse batch, skipping: '{data}'")- continue- batches[url] = batch- return batches-- def retrieve_batches(self, num_batches):- with Database() as db:- index_db = IndexDatabase(db.connection)- index_db.create_tables()-- with Database() as db:- index_db = IndexDatabase(db.connection)- batches = index_db.get_batches_by_status(BatchStatus.REMOTE, num_batches)- logger.info(f"Found {len(batches)} remote batches")- if len(batches) == 0:- return- urls = [batch.url for batch in batches]- pool = ThreadPool(self.num_threads)- results = pool.imap_unordered(self.retrieve_batch, urls)- total_processed = 0- for result in results:- total_processed += result- logger.info(f"Processed batches with {total_processed} items")- index_db.update_batch_status(urls, BatchStatus.LOCAL)-- def retrieve_batch(self, url):- data = json.loads(gzip.decompress(retry_requests.get(url).content))- try:- batch = HashedBatch.parse_obj(data)- except ValidationError:- logger.info(f"Failed to validate batch {data}")- return 0- if len(batch.items) > 0:- self.store(batch, url)- return len(batch.items)-- def store(self, batch, url):- path = self.get_path_from_url(url)- logger.debug(f"Storing local batch at {path}")- os.makedirs(path.parent, exist_ok=True)- with open(path, "wb") as output_file:- data = gzip.compress(batch.json().encode("utf8"))- output_file.write(data)-- def get_path_from_url(self, url) -> Path:- url_path = urlparse(url).path- return Path(self.path) / url_path.lstrip("/")diff --git a/mwmbl/indexer/historical.py b/mwmbl/indexer/historical.pydeleted file mode 100644index e58d972..0000000--- a/mwmbl/indexer/historical.py+++ /dev/null@@ -1,29 +0,0 @@-from datetime import timedelta--from mwmbl.crawler.app import get_batches_for_date-from mwmbl.database import Database-from mwmbl.indexer.indexdb import BatchInfo, BatchStatus, IndexDatabase-from mwmbl.utils import utc_today--DAYS = 20---def run():- for day in range(DAYS):- date_str = str(utc_today() - timedelta(days=day))- with Database() as db:- index_db = IndexDatabase(db.connection)- index_db.create_tables()- batches = get_batches_for_date(date_str)- batch_urls = batches["batch_urls"]- print("Historical batches for date", date_str, len(batch_urls))- infos = [BatchInfo(url, get_user_id_hash_from_url(url), BatchStatus.REMOTE) for url in batch_urls]- index_db.record_batches(infos)---def get_user_id_hash_from_url(url):- return url.split("/")[9]---if __name__ == "__main__":- run()diff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.pyindex cc1d1a2..6dab3c2 100644--- a/mwmbl/indexer/index_batches.py+++ b/mwmbl/indexer/index_batches.py@@ -1,5 +1,5 @@"""-Index batches that are stored locally.+Write crawled documents into the index."""from collections import Counter, defaultdict@@ -10,11 +10,8 @@ from urllib.parse import unquotefrom mwmbl.crawler.batch import HashedBatch, Itemfrom mwmbl.crawler.urls import URLStatus-from mwmbl.indexer import process_batch-from mwmbl.indexer.batch_cache import BatchCachefrom mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklistfrom mwmbl.indexer.index import prepare_url_for_tokenizing, tokenize_document-from mwmbl.indexer.indexdb import BatchStatusfrom mwmbl.tinysearchengine.indexer import (CURATED_STATES,Document,@@ -53,15 +50,6 @@ def get_documents_from_batches(batches: Collection[HashedBatch]) -> Iterable[Doc)-def run(batch_cache: BatchCache, index_path: str):-- def process(batches: Collection[HashedBatch]):- index_batches(batches, index_path)- logger.info("Indexed pages")-- process_batch.run(batch_cache, BatchStatus.URLS_UPDATED, BatchStatus.INDEXED, process, 10000)--def get_url_score(url):# TODO: compute a proper score for each documentreturn 1 / len(url)@@ -76,12 +64,11 @@ def index_batches(batch_data: Collection[HashedBatch], index_path: str) -> Countdef index_documents(documents, index_path):- """The common choke point every indexing path (offline batch processing, the- trusted-crawler POST /results endpoint, the standalone crawl tool) goes through, so+ """The common choke point every indexing path (the trusted-crawler POST /results+ endpoint, the standalone crawl tool) goes through, sothis is where the blacklist is enforced. Crawling/link-discovery also check theblacklist (RedisURLQueue, update_urls.process_link) but only to stop *new* crawling -- a submitted batch or a direct /results submission can contain a blacklisted domain's- pages regardless of whether that domain was ever handed out to be crawled (e.g. a+ a /results submission can contain a blacklisted domain's pages 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 checkrather than relying on those upstream gates.@@ -137,8 +124,8 @@ def index_pages(index_path: str, page_documents: dict[int, list[Document]], markexcept PageError:# One page we cannot safely write costs the documents bound for it, not the# rest of the batch. Letting it propagate would abort every remaining page,- # and this runs inside POST /crawler/results and the batch indexer, where- # that means a 500 or a batch that is never marked done and retries forever.+ # and this runs inside POST /crawler/results and the standalone crawler's+ # indexing loop, where that means a 500 or a batch lost wholesale.logger.exception("Skipping index page %d", page_index)continuediff --git a/mwmbl/indexer/indexdb.py b/mwmbl/indexer/indexdb.pydeleted file mode 100644index 81f1b10..0000000--- a/mwmbl/indexer/indexdb.py+++ /dev/null@@ -1,75 +0,0 @@-"""-Database interface for batches of crawled data.-"""--from dataclasses import dataclass-from enum import Enum-from typing import Optional--from psycopg2.extras import execute_values---class BatchStatus(Enum):- REMOTE = 0 # The batch only exists in long term storage- LOCAL = 10 # We have a copy of the batch locally in Postgresql- URLS_UPDATED = 20 # We've updated URLs from the batch- INDEXED = 30 # The batch has been indexed---@dataclass-class BatchInfo:- url: str- user_id_hash: str- status: BatchStatus- device_name: Optional[str] = None---class IndexDatabase:- def __init__(self, connection):- self.connection = connection-- def create_tables(self):- batches_sql = """- CREATE TABLE IF NOT EXISTS batches (- url VARCHAR PRIMARY KEY,- user_id_hash VARCHAR NOT NULL,- status INT NOT NULL,- device_name VARCHAR- )- """-- with self.connection.cursor() as cursor:- cursor.execute(batches_sql)-- def record_batches(self, batch_infos: list[BatchInfo]):- sql = """- INSERT INTO batches (url, user_id_hash, status, device_name) values %s- ON CONFLICT (url) DO NOTHING- """-- data = [(info.url, info.user_id_hash, info.status.value, info.device_name) for info in batch_infos]-- with self.connection.cursor() as cursor:- execute_values(cursor, sql, data)-- def get_batches_by_status(self, status: BatchStatus, num_batches=1000) -> list[BatchInfo]:- sql = """- SELECT * FROM batches WHERE status = %(status)s LIMIT %(num_batches)s- """-- with self.connection.cursor() as cursor:- cursor.execute(sql, {"status": status.value, "num_batches": num_batches})- results = cursor.fetchall()- return [BatchInfo(url, user_id_hash, status) for url, user_id_hash, status in results]-- def update_batch_status(self, batch_urls: list[str], status: BatchStatus):- if not batch_urls:- return-- sql = """- UPDATE batches SET status = %(status)s- WHERE url IN %(urls)s- """-- with self.connection.cursor() as cursor:- cursor.execute(sql, {"status": status.value, "urls": tuple(batch_urls)})diff --git a/mwmbl/indexer/process_batch.py b/mwmbl/indexer/process_batch.pydeleted file mode 100644index c0f88de..0000000--- a/mwmbl/indexer/process_batch.py+++ /dev/null@@ -1,39 +0,0 @@-from logging import getLogger-from typing import Callable, Collection--from mwmbl.crawler.batch import HashedBatch-from mwmbl.database import Database-from mwmbl.indexer.batch_cache import BatchCache-from mwmbl.indexer.indexdb import BatchStatus, IndexDatabase--logger = getLogger(__name__)---def run(- batch_cache: BatchCache,- start_status: BatchStatus,- end_status: BatchStatus,- process: Callable[[Collection[HashedBatch], ...], None],- num_batches,- *args,-):-- with Database() as db:- index_db = IndexDatabase(db.connection)-- logger.info(f"Getting batches with status {start_status}")- batches = index_db.get_batches_by_status(start_status, num_batches)- logger.info(f"Got {len(batches)} batch urls")- if len(batches) == 0:- return-- batch_data = batch_cache.get_cached([batch.url for batch in batches])- logger.info(f"Got {len(batch_data)} cached batches")-- missing_batches = {batch.url for batch in batches} - batch_data.keys()- logger.info(f"Got {len(missing_batches)} missing batches")- index_db.update_batch_status(list(missing_batches), BatchStatus.REMOTE)-- process(batch_data.values(), *args)-- index_db.update_batch_status(list(batch_data.keys()), end_status)diff --git a/mwmbl/indexer/update_urls.py b/mwmbl/indexer/update_urls.pyindex d62a86d..30f9420 100644--- a/mwmbl/indexer/update_urls.py+++ b/mwmbl/indexer/update_urls.py@@ -1,45 +1,21 @@-import loggingfrom collections import defaultdictfrom datetime import datetime, timedelta, timezonefrom logging import getLogger-from pathlib import Path-from time import sleepfrom typing import Collectionimport requests-from django.conf import settings-from redis import Redisfrom mwmbl.crawler.batch import HashedBatch, Linkfrom mwmbl.crawler.domains import DomainLinkDatabasefrom mwmbl.crawler.urls import FoundURL, URLDatabase, URLStatus-from mwmbl.indexer import process_batch-from mwmbl.indexer.batch_cache import BatchCachefrom mwmbl.indexer.blacklist import get_default_blacklist_providerfrom mwmbl.indexer.index_batches import get_url_error_status-from mwmbl.indexer.indexdb import BatchStatusfrom mwmbl.redis_url_queue import RedisURLQueue, get_domain_max_urlsfrom mwmbl.utils import get_domain, parse_urllogger = getLogger(__name__)-def update_urls_continuously(data_path: str, new_item_queue: RedisURLQueue):- batch_cache = BatchCache(Path(data_path) / settings.BATCH_DIR_NAME)- while True:- try:- run(batch_cache, new_item_queue)- except Exception:- logger.exception("Error updating URLs")- sleep(10)---def run(batch_cache: BatchCache, new_item_queue: RedisURLQueue, num_batches: int = 1000):- process_batch.run(- batch_cache, BatchStatus.LOCAL, BatchStatus.URLS_UPDATED, record_urls_in_database, num_batches, new_item_queue- )--def record_urls_in_database(batches: Collection[HashedBatch], new_item_queue: RedisURLQueue):start = datetime.now(timezone.utc)# Take the approved domains from the queue rather than the database: the standalone@@ -159,14 +135,3 @@ def process_link(def get_datetime_from_timestamp(timestamp: float) -> datetime:batch_datetime = datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)return batch_datetime---if __name__ == "__main__":- logging.basicConfig(level=logging.INFO)- redis: Redis = Redis.from_url("redis://127.0.0.1:6379", decode_responses=True)- batch_cache = BatchCache(Path(settings.DATA_PATH) / settings.BATCH_DIR_NAME)- url_queue = RedisURLQueue(redis, lambda: set())- start_time = datetime.now(timezone.utc)- run(batch_cache, url_queue, num_batches=500)- end_time = datetime.now(timezone.utc)- logger.info(f"Finished updating URLs in {end_time - start_time}")diff --git a/mwmbl/main.py b/mwmbl/main.pyindex 47cda9e..659738d 100644--- a/mwmbl/main.py+++ b/mwmbl/main.py@@ -6,7 +6,6 @@ from time import sleepimport djangofrom django.core.management import call_commandfrom gunicorn.app.base import BaseApplication-from redis import Redislogger = logging.getLogger(__name__)@@ -47,28 +46,18 @@ def run():from mwmbl import backgroundfrom mwmbl.count_urls import count_urls_continuously- from mwmbl.curated_domains import get_curated_domains- from mwmbl.indexer.update_urls import update_urls_continuously- from mwmbl.redis_url_queue import RedisURLQueueif settings.STATIC_ROOT:call_command("collectstatic", "--clear", "--noinput")call_command("migrate")- # DEPRECATED: update_urls, update_batches, 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 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.mwmbl_app = os.environ["MWMBL_APP"]- if mwmbl_app == "update_urls":- redis: Redis = Redis.from_url(os.environ.get("REDIS_URL", "redis://127.0.0.1:6379"), decode_responses=True)- url_queue = RedisURLQueue(redis, get_curated_domains)- update_urls_continuously(settings.DATA_PATH, url_queue)- elif mwmbl_app == "update_batches":- background.run(settings.DATA_PATH)- elif mwmbl_app == "copy_indexes":+ if mwmbl_app == "copy_indexes":background.copy_indexes_continuously()elif mwmbl_app == "count_urls":count_urls_continuously()diff --git a/mwmbl/migrations/0039_batches_device_name.py b/mwmbl/migrations/0039_batches_device_name.pydeleted file mode 100644index ae32c2d..0000000--- a/mwmbl/migrations/0039_batches_device_name.py+++ /dev/null@@ -1,25 +0,0 @@-# Generated by Django 5.2.13 on 2026-09-17--from django.db import migrations---class Migration(migrations.Migration):- dependencies = [- ("mwmbl", "0038_apikey_last_used_device"),- ]-- operations = [- migrations.RunSQL(- """- CREATE TABLE IF NOT EXISTS batches (- url VARCHAR PRIMARY KEY,- user_id_hash VARCHAR NOT NULL,- status INT NOT NULL,- device_name VARCHAR- );- """,- """- ALTER TABLE batches DROP COLUMN device_name;- """,- ),- ]diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.pyindex 352e21f..b511bdd 100644--- a/mwmbl/settings_common.py+++ b/mwmbl/settings_common.py@@ -188,7 +188,6 @@ FOOTER_LINKS = [},]-BATCH_DIR_NAME = "batches"DATA_UPLOAD_MAX_NUMBER_FIELDS = Nonediff --git a/test/conftest.py b/test/conftest.pyindex c25ce9b..3fab119 100644--- a/test/conftest.py+++ b/test/conftest.py@@ -31,11 +31,3 @@ def async_debug_loop(event_loop):event_loop.set_debug(True)event_loop.slow_callback_duration = 0.1yield event_loop---def index_db():- """Create the index database tables (batches, etc.) for tests that need them."""- from mwmbl.apps import create_index_db-- create_index_db()diff --git a/test/test_export_judgments.py b/test/test_export_judgments.pyindex 00e2bce..d7fc3fe 100644--- a/test/test_export_judgments.py+++ b/test/test_export_judgments.py@@ -11,14 +11,6 @@ from mwmbl.models import Curation, DomainSubmission, FlagCuration, SearchResultVUser = get_user_model()[email protected](autouse=True)-def index_db():- """Create the index database tables for tests that need them."""- from mwmbl.apps import create_index_db-- create_index_db()--def doc(url, title="title", extract="extract", score=1.0, state=None, user_ids=None):return {"url": url,diff --git a/test/test_large_url_list.py b/test/test_large_url_list.pyindex 107c335..56c3a98 100644--- a/test/test_large_url_list.py+++ b/test/test_large_url_list.py@@ -10,14 +10,6 @@ from mwmbl.models import SearchResultVoteUser = get_user_model()[email protected](autouse=True)-def index_db():- """Create the index database tables for tests that need them."""- from mwmbl.apps import create_index_db-- create_index_db()--@pytest.fixturedef verified_user():"""Create a user with verified email"""diff --git a/test/test_marketing_consent.py b/test/test_marketing_consent.pyindex 8d857b2..c44bff9 100644--- a/test/test_marketing_consent.py+++ b/test/test_marketing_consent.py@@ -15,14 +15,6 @@ CONSENT_URL = "/api/v1/platform/marketing-consent"UNSUBSCRIBE_URL = "/api/v1/platform/marketing/unsubscribe"[email protected](autouse=True)-def index_db():- """Create the index database tables for tests that need them."""- from mwmbl.apps import create_index_db-- create_index_db()--@pytest.fixturedef verified_user(db):user = User.objects.create_user(