Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Stop crawl workers picking the same batches, and measure domain overlap

Daoud Clarke6b00dad78e5f
diff --git a/mwmbl/crawler/README.md b/mwmbl/crawler/README.md
index a7b4f52..6391018 100644
--- a/mwmbl/crawler/README.md
+++ b/mwmbl/crawler/README.md
@@ -16,6 +16,8 @@ The crawler can be configured using the following environment variables:
**Process Architecture**: The crawler spawns `CRAWLER_WORKERS` processes for crawling work, each using `CRAWL_THREADS` threads for concurrent URL fetching. Additionally, one separate process handles indexing work. For example, with default settings you get 2 crawler processes × 20 threads = 40 total crawling threads, plus 1 indexing process. The queue gives each batch at most one URL per domain, so the threads of one batch never fetch pages from the same site at once.
+Batches crawled by different workers at the same time can share domains, since each worker samples its domains independently. The core domains (Wikipedia, GitHub and so on) are in every batch, so they are the usual overlap. With the default 2 workers, about 0.7% of fetches start while another fetch to the same domain is in flight. Overlap grows with `CRAWLER_WORKERS`. The crawler records it in Redis, and `redis-cli HGETALL crawl-domain-overlap` gives the totals: `fetches`, `overlapped` (fetches that started while another fetch to their domain was in flight) and `duplicate_domains` (should stay 0).
+
### Rate Limiting Configuration
- `CRAWL_DELAY_SECONDS` (default: 0.0) - Delay in seconds each crawl thread waits between the URLs it crawls. Includes 10% random fuzz (±10%) to avoid synchronized requests across workers. Set to 0 to disable delays.
diff --git a/mwmbl/crawler/retrieve.py b/mwmbl/crawler/retrieve.py
index 23dbfd9..a86f623 100644
--- a/mwmbl/crawler/retrieve.py
+++ b/mwmbl/crawler/retrieve.py
@@ -60,6 +60,14 @@ USER_AGENT = f"mwmbl/{CRAWLER_VERSION} (https://github.com/mwmbl/mwmbl/ contact
ROBOTS_CACHE_TTL_SECONDS = 60 * 60 * 24
ROBOTS_CACHE_ERROR_TTL_SECONDS = 60 * 60
+# Diagnostic: how often a fetch starts while another fetch to the same domain is in flight,
+# across every worker sharing this Redis. Read the totals with HGETALL crawl-domain-overlap.
+DOMAIN_IN_FLIGHT_KEY = "crawl-in-flight-{domain}"
+DOMAIN_OVERLAP_KEY = "crawl-domain-overlap"
+# Only matters if a worker dies mid-crawl and never decrements: the stale count then
+# lingers until the domain goes this long without a fetch starting.
+DOMAIN_IN_FLIGHT_EXPIRY_SECONDS = 120
+
logger = getLogger(__name__)
# One verifying context for every fetch. Left to itself, requests builds a fresh context for
@@ -500,11 +508,47 @@ def crawl_batch(urls: list[str], num_threads: int, delay_seconds: float, redis:
Each thread waits delay_seconds, with 10% random fuzz, between the URLs it crawls.
"""
+ overlaps = []
+
def crawl_after_delay(url: str) -> dict:
if delay_seconds and getattr(_thread_local, "has_crawled", False):
time.sleep(delay_seconds * (0.9 + 0.2 * random.random()))
_thread_local.has_crawled = True
- return crawl_url(url, redis)
+ result, overlap = crawl_counting_overlap(url, redis)
+ overlaps.append(overlap)
+ return result
with ThreadPool(num_threads) as pool:
- return pool.map(crawl_after_delay, urls)
+ results = pool.map(crawl_after_delay, urls)
+
+ record_overlap(urls, overlaps, redis)
+ return results
+
+
+def crawl_counting_overlap(url: str, redis: Redis) -> tuple[dict, int]:
+ """Crawl url, also returning how many other crawls of its domain were in flight as it started."""
+ key = DOMAIN_IN_FLIGHT_KEY.format(domain=urlparse(url).netloc)
+ in_flight, _ = redis.pipeline().incr(key).expire(key, DOMAIN_IN_FLIGHT_EXPIRY_SECONDS).execute()
+ try:
+ return crawl_url(url, redis), in_flight - 1
+ finally:
+ redis.decr(key)
+
+
+def record_overlap(urls: list[str], overlaps: list[int], redis: Redis):
+ """Add a batch to the overlap totals.
+
+ duplicate_domains counts URLs whose domain already appeared earlier in the same batch, so
+ overlapped minus duplicate_domains is a lower bound on the overlap between batches.
+ """
+ num_domains = len({urlparse(url).netloc for url in urls})
+ duplicate_domains = len(urls) - num_domains
+ overlapped = sum(1 for overlap in overlaps if overlap > 0)
+ max_overlap = max(overlaps, default=0)
+ logger.info(
+ f"Domain overlap: {overlapped} of {len(urls)} fetches started while another fetch to the same "
+ f"domain was in flight (max {max_overlap} others); {duplicate_domains} duplicate domains in batch"
+ )
+ redis.pipeline().hincrby(DOMAIN_OVERLAP_KEY, "fetches", len(urls)).hincrby(
+ DOMAIN_OVERLAP_KEY, "overlapped", overlapped
+ ).hincrby(DOMAIN_OVERLAP_KEY, "duplicate_domains", duplicate_domains).execute()
diff --git a/mwmbl/redis_url_queue.py b/mwmbl/redis_url_queue.py
index e5b9122..8392c82 100644
--- a/mwmbl/redis_url_queue.py
+++ b/mwmbl/redis_url_queue.py
@@ -1,9 +1,9 @@
import json
import math
+import random
from collections import defaultdict
from datetime import datetime, timedelta, timezone
from logging import getLogger
-from random import Random
from typing import Callable
from redis import Redis
@@ -18,7 +18,6 @@ from mwmbl.utils import parse_url
MAX_TIME_DELTA = timedelta(days=100000)
-random = Random(1)
logger = getLogger(__name__)
@@ -119,6 +118,9 @@ class RedisURLQueue:
top_scoring_domains = set(self.redis.zrange(DOMAIN_SCORE_KEY, 0, 2000, desc=True))
top_other_domains = top_scoring_domains - DOMAINS.keys()
+ # The stdlib's shared random instance, which Python reseeds in every forked child. A
+ # Random of our own, seeded or not, would be copied into each crawl worker, and every
+ # worker would then pick the same domains and seed URL in lockstep.
domains = list(CORE_DOMAINS)
top_curated_domains = (DOMAINS.keys() & top_scoring_domains) | curated_domains
if len(top_curated_domains) > NUM_TOP_DOMAIN_URLS_TO_INCLUDE:
@@ -133,15 +135,21 @@ class RedisURLQueue:
seed_domains = list(DOMAINS.keys() | curated_domains)
- domains = [domain for domain in domains if not self.blacklist_provider.is_domain_blacklisted(domain)]
- logger.info(f"Getting batch from domains {domains}")
-
# Add a random url as the root domain of one of DOMAINS. The seed needs the same
# blacklist filter as the rest: it is a URL we are about to fetch.
seed_domains = [domain for domain in seed_domains if not self.blacklist_provider.is_domain_blacklisted(domain)]
random_domain = random.choice(seed_domains)
urls = [f"https://{random_domain}/"]
+ # At most one URL per domain, since the batch is crawled concurrently: the samples
+ # above can pick a core domain again, and the seed can repeat any of them.
+ domains = [
+ domain
+ for domain in dict.fromkeys(domains)
+ if domain != random_domain and not self.blacklist_provider.is_domain_blacklisted(domain)
+ ]
+ logger.info(f"Getting batch from domains {domains}")
+
# Pop the highest scoring URL from each domain
for domain in domains:
domain_urls_scores = self.redis.zpopmax(DOMAIN_URLS_KEY.format(domain=domain))
diff --git a/test/test_retrieve_concurrency.py b/test/test_retrieve_concurrency.py
index 90888d0..b9923c7 100644
--- a/test/test_retrieve_concurrency.py
+++ b/test/test_retrieve_concurrency.py
@@ -89,3 +89,24 @@ def test_crawl_batch_without_delay_never_sleeps(monkeypatch):
)
assert sleeps == []
+
+
+def test_crawl_batch_counts_fetches_overlapping_on_a_domain(monkeypatch):
+ # Both crawls of a.test wait for each other, so the second always starts while the
+ # first is in flight; b.test never overlaps.
+ both_a_in_flight = threading.Barrier(2, timeout=5)
+
+ def fake_crawl_url(url, redis):
+ if "a.test" in url:
+ both_a_in_flight.wait()
+ return {"url": url}
+
+ monkeypatch.setattr(retrieve, "crawl_url", fake_crawl_url)
+ redis = fakeredis.FakeStrictRedis()
+ urls = ["https://a.test/1", "https://a.test/2", "https://b.test/"]
+
+ crawl_batch(urls, num_threads=3, delay_seconds=0.0, redis=redis)
+
+ totals = redis.hgetall(retrieve.DOMAIN_OVERLAP_KEY)
+ assert totals == {b"fetches": b"3", b"overlapped": b"1", b"duplicate_domains": b"1"}
+ assert int(redis.get(retrieve.DOMAIN_IN_FLIGHT_KEY.format(domain="a.test"))) == 0