Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Stop seed crawls repeating a query and running on when nothing is left

Claude29085a6b8ff8
diff --git a/mwmbl/indexer/seed_crawl.py b/mwmbl/indexer/seed_crawl.py
index 6e91664..f2073a8 100644
--- a/mwmbl/indexer/seed_crawl.py
+++ b/mwmbl/indexer/seed_crawl.py
@@ -62,6 +62,7 @@ class CrawlOutcome(StrEnum):
NO_RESULTS = "no_results"
ALREADY_INDEXED = "already_indexed"
ALREADY_RUNNING = "already_running"
+ ALREADY_CRAWLED = "already_crawled"
QUEUE_FULL = "queue_full"
@@ -106,8 +107,8 @@ def start_seed_crawl(
the index - count as pages the crawl added; the rest the index already held.
Nothing is queued when Staan returned nothing crawlable, when every Staan result is
- already in the index, when this user already has a crawl queued or running, or when the
- queue is full.
+ already in the index, when this user has already crawled the query, when they already
+ have a crawl queued or running, or when the queue is full.
"""
blacklisted_urls = find_blacklisted_urls(staan_results)
allowed = [document for document in staan_results if document.url not in blacklisted_urls]
@@ -119,6 +120,14 @@ def start_seed_crawl(
return CrawlOutcome.ALREADY_INDEXED
redis = get_redis_connection("default")
+ record_key = _record_key(user_id, query)
+ # Pages a crawl adds need not rank for the query, so its seeds would mostly be the same
+ # again: a query is crawled once while its record lasts, unless that crawl failed.
+ status = redis.hget(record_key, "status")
+ if status in (STATUS_QUEUED.encode(), STATUS_CRAWLING.encode()):
+ return CrawlOutcome.ALREADY_RUNNING
+ if status == STATUS_DONE.encode():
+ return CrawlOutcome.ALREADY_CRAWLED
# A slight overshoot from racing requests is harmless; the cap is there to stop one
# user, or many, queueing hours of crawling.
if redis.llen(QUEUE_KEY) >= settings.SEED_CRAWL_MAX_QUEUED:
@@ -130,7 +139,6 @@ def start_seed_crawl(
if not redis.set(_active_key(user_id), query, nx=True, ex=lock_seconds):
return CrawlOutcome.ALREADY_RUNNING
- record_key = _record_key(user_id, query)
# Each domain with the number of Staan results it had, which the seed domains count.
staan_results_per_domain = Counter(bare_host(document.url) for document in allowed)
domains = dict(sorted(staan_results_per_domain.items()))
@@ -142,7 +150,7 @@ def start_seed_crawl(
"new_seed_urls": new_seed_urls,
"domains": domains,
}
- # An earlier crawl's pages are kept: the new one adds to them, and the user's total
+ # A failed earlier crawl's pages are kept: the new one adds to them, and the user's total
# already includes them. Its progress and domains are this crawl's alone.
record = {
"status": STATUS_QUEUED,
@@ -235,7 +243,14 @@ def _crawl_and_record(
ttl = settings.SEED_CRAWL_RECORD_TTL_SECONDS
domain_pages = Counter()
- for num_crawled, documents in crawl_within_domains(seed_urls, set(domains), redis):
+ rounds = crawl_within_domains(seed_urls, set(domains), redis)
+ # Each round is told which of its pages were new, so it can tell when a domain has run dry.
+ counted_urls = None
+ while True:
+ try:
+ num_crawled, documents = rounds.send(counted_urls)
+ except StopIteration:
+ return domain_pages
indexed = index_new_documents(documents, index_path)
# Combined Search has since written Staan's snippets of the new seeds, so the index
# alone no longer says they were new. Only those this write stored count.
@@ -269,17 +284,22 @@ def _crawl_and_record(
MwmblUser.objects.filter(id=user_id).update(
seed_search_pages_indexed=F("seed_search_pages_indexed") + len(new_documents)
)
- return domain_pages
+ counted_urls = {document.url for document in new_documents}
def crawl_within_domains(seed_urls: list[str], domains: set[str], redis):
"""Crawl breadth first from the seeds, staying within the domains given.
- Yields, for each round, how many URLs it fetched and the documents it got from them.
+ Yields, for each round, how many URLs it fetched and the documents it got from them, and
+ is sent back the URLs of those documents that were new. A domain is dropped once
+ SEED_CRAWL_MAX_STALE_PAGES_PER_DOMAIN fetches in a row from it have added nothing new, so
+ the crawl ends when there is nothing left for it to find rather than when it has fetched
+ every domain's budget.
"""
frontiers: dict[str, deque[str]] = {}
seen_urls = set()
enqueued_per_domain = Counter()
+ stale_fetches_per_domain = Counter()
max_pages_per_domain = settings.SEED_CRAWL_MAX_PAGES_PER_DOMAIN
def enqueue(url: str) -> None:
@@ -332,7 +352,16 @@ def crawl_within_domains(seed_urls: list[str], domains: set[str], redis):
)
for link in content["links"] + content["extra_links"]:
follow(link)
- yield len(batch), documents
+ new_urls = yield len(batch), documents
+
+ for url, result in zip(batch, results):
+ domain = bare_host(url)
+ if result["url"] in new_urls:
+ stale_fetches_per_domain[domain] = 0
+ continue
+ stale_fetches_per_domain[domain] += 1
+ if stale_fetches_per_domain[domain] >= settings.SEED_CRAWL_MAX_STALE_PAGES_PER_DOMAIN:
+ frontiers[domain].clear()
def get_seed_crawl_summary(user_id: int, query: str) -> dict | None:
diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.py
index 36126c7..ebf0faa 100644
--- a/mwmbl/settings_common.py
+++ b/mwmbl/settings_common.py
@@ -316,6 +316,8 @@ STAAN_TIMEOUT_SECONDS = 5
# Seed crawls: Combined Search with crawl=true crawls the Staan results the index lacked,
# following links within Staan's domains - see mwmbl.indexer.seed_crawl.
SEED_CRAWL_MAX_PAGES_PER_DOMAIN = 100
+# A domain is dropped from a crawl after this many fetches in a row that added no new page.
+SEED_CRAWL_MAX_STALE_PAGES_PER_DOMAIN = 10
# A backstop on a crawl's length; the per-domain cap ends almost all of them well before it.
SEED_CRAWL_MAX_SECONDS = 15 * 60
# Crawls waiting for the worker, across all users, beyond which crawl=true queues nothing.
diff --git a/mwmbl/tinysearchengine/combined_search.py b/mwmbl/tinysearchengine/combined_search.py
index 2fdd395..abae13f 100644
--- a/mwmbl/tinysearchengine/combined_search.py
+++ b/mwmbl/tinysearchengine/combined_search.py
@@ -87,7 +87,7 @@ class CombinedSearchResponse(SearchResponse):
default=None,
description="What `crawl=true` did: `scheduled` a crawl, or none because EUSP returned "
"nothing to crawl (`no_results`), every EUSP result is already in the index "
- "(`already_indexed`), one of your crawls is still queued or running (`already_running`), "
+ "(`already_indexed`), you have already crawled this query (`already_crawled`), one of your crawls is still queued or running (`already_running`), "
"or the crawl queue is full (`queue_full`). Null without `crawl=true`.",
examples=["scheduled"],
)
diff --git a/test/test_seed_crawl.py b/test/test_seed_crawl.py
index 6ceb86c..253ddbd 100644
--- a/test/test_seed_crawl.py
+++ b/test/test_seed_crawl.py
@@ -85,8 +85,18 @@ def user(db):
return User.objects.create_user(username="seeder", email="[email protected]", password="x")
-def _crawl(seed_urls, domains):
- return [round_ for round_ in seed_crawl.crawl_within_domains(seed_urls, set(domains), redis=None)]
+def _crawl(seed_urls, domains, is_new=lambda url: True):
+ """Run a crawl to its end, telling it that the pages is_new picks were new."""
+ rounds = seed_crawl.crawl_within_domains(seed_urls, set(domains), redis=None)
+ crawled = []
+ new_urls = None
+ while True:
+ try:
+ num_crawled, documents = rounds.send(new_urls)
+ except StopIteration:
+ return crawled
+ crawled.append((num_crawled, documents))
+ new_urls = {document.url for document in documents if is_new(document.url)}
# ---------------------------------------------------------------------------
@@ -128,6 +138,31 @@ def test_each_domain_stops_at_its_page_limit(fake_web, settings):
assert sum(num_crawled for num_crawled, _ in rounds) == 3
+def test_a_domain_is_dropped_once_its_fetches_stop_finding_new_pages(fake_web, monkeypatch, settings):
+ settings.SEED_CRAWL_MAX_STALE_PAGES_PER_DOMAIN = 2
+ # An endless site: every page links to the next.
+ monkeypatch.setitem(WEB, SEED, _page("Page 0", ["https://tokio.rs/1"]))
+ for n in range(1, 20):
+ monkeypatch.setitem(WEB, f"https://tokio.rs/{n}", _page(f"Page {n}", [f"https://tokio.rs/{n + 1}"]))
+
+ _crawl([SEED], ["tokio.rs"], is_new=lambda url: False)
+
+ fetched = [url for batch in fake_web for url in batch]
+ assert fetched == [SEED, "https://tokio.rs/1"]
+
+
+def test_a_new_page_resets_a_domains_run_of_stale_fetches(fake_web, monkeypatch, settings):
+ settings.SEED_CRAWL_MAX_STALE_PAGES_PER_DOMAIN = 2
+ monkeypatch.setitem(WEB, SEED, _page("Page 0", ["https://tokio.rs/1"]))
+ for n in range(1, 20):
+ monkeypatch.setitem(WEB, f"https://tokio.rs/{n}", _page(f"Page {n}", [f"https://tokio.rs/{n + 1}"]))
+
+ _crawl([SEED], ["tokio.rs"], is_new=lambda url: url == "https://tokio.rs/1")
+
+ fetched = [url for batch in fake_web for url in batch]
+ assert fetched == [SEED, "https://tokio.rs/1", "https://tokio.rs/2", "https://tokio.rs/3"]
+
+
def test_a_failed_fetch_adds_no_document(fake_web):
rounds = _crawl(["https://tokio.rs/missing"], ["tokio.rs"])
@@ -211,6 +246,18 @@ def test_a_user_has_one_crawl_at_a_time(redis_cache, monkeypatch):
assert len(_queued_jobs(redis_cache)) == 2
+def test_a_query_already_crawled_is_not_crawled_again(fake_web, redis_cache, user, index_path, worker):
+ seed_crawl.start_seed_crawl(user.id, "tokio", [], STAAN_RESULTS, set())
+ worker(index_path)
+
+ outcome = seed_crawl.start_seed_crawl(user.id, "tokio", [], STAAN_RESULTS, set())
+
+ assert outcome == seed_crawl.CrawlOutcome.ALREADY_CRAWLED
+ assert _queued_jobs(redis_cache) == []
+ assert seed_crawl.start_seed_crawl(user.id, "rust", [], STAAN_RESULTS, set()) == seed_crawl.CrawlOutcome.SCHEDULED
+
+
def test_nothing_is_queued_once_the_queue_is_full(redis_cache, monkeypatch, settings):
monkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: set())
settings.SEED_CRAWL_MAX_QUEUED = 1
@@ -233,6 +280,11 @@ def _run(user, index_path, seed_urls=(SEED,), new_seed_urls=()):
return seed_crawl.get_seed_crawl(user.id, "tokio")
+def _mark_failed(user, query="tokio"):
+ """Mark the user's crawl of the query failed, the one case in which it is crawled again."""
+ seed_crawl.get_redis_connection("default").hset(seed_crawl._record_key(user.id, query), "status", "failed")
+
+
@pytest.mark.django_db
def test_the_record_lists_the_new_pages_once_the_crawl_is_done(fake_web, redis_cache, user, index_path):
record = _run(user, index_path)
@@ -284,6 +336,7 @@ def test_a_failed_crawl_is_recorded_and_not_retried(fake_web, redis_cache, user,
@pytest.mark.django_db
def test_crawling_a_query_again_keeps_its_pages_and_counts_none_twice(fake_web, redis_cache, user, index_path):
_run(user, index_path)
+ _mark_failed(user)
record = _run(user, index_path)
user.refresh_from_db()
@@ -484,6 +537,7 @@ def test_domains_are_not_reported_until_the_crawl_has_registered_them(fake_web,
@pytest.mark.django_db
def test_crawling_a_query_again_reports_only_the_new_crawls_domains(fake_web, redis_cache, user, index_path):
_run(user, index_path)
+ _mark_failed(user)
record = _run(user, index_path)
@@ -501,6 +555,7 @@ def test_a_querys_staan_results_count_once_per_user(fake_web, redis_cache, user,
seed_crawl.start_seed_crawl(user.id, "tokio", [], tokio_results, set())
job = json.loads(seed_crawl.get_redis_connection("default").rpop(seed_crawl.QUEUE_KEY))
seed_crawl.run_seed_crawl(user.id, "tokio", [SEED], [], job["domains"], index_path)
+ _mark_failed(user)
assert SeedDomain.objects.get(domain="tokio.rs").staan_results == 2
assert SeedDomain.objects.get(domain="rust-lang.github.io").staan_results == 1