Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Score seed domains and report seed crawl progress

Claudec2c4856a7c6a
diff --git a/mwmbl/indexer/seed_crawl.py b/mwmbl/indexer/seed_crawl.py
index 550dd82..290bd0f 100644
--- a/mwmbl/indexer/seed_crawl.py
+++ b/mwmbl/indexer/seed_crawl.py
@@ -19,6 +19,8 @@ running, and at most SEED_CRAWL_MAX_QUEUED wait, so nobody can fill the queue.
What it added is recorded in Redis against the user and the query, where
GET /api/v2/combined-search/new-pages (and /new-pages/count) reads it, and counted on the user for their stats.
+That record also says how far along the crawl is, and what it found on each of Staan's
+domains, which are scored for crawlers as seed domains - see mwmbl.indexer.seed_domains.
"""
import hashlib
@@ -39,7 +41,8 @@ from django_redis import get_redis_connection
from mwmbl.crawler.retrieve import crawl_batch
from mwmbl.indexer.index_batches import index_new_documents
-from mwmbl.models import MwmblUser
+from mwmbl.indexer.seed_domains import new_page_score, record_seed_domain_crawls, register_seed_domains
+from mwmbl.models import MwmblUser, SeedDomain
from mwmbl.tinysearchengine.indexer import Document
from mwmbl.tinysearchengine.rank import find_blacklisted_urls
from mwmbl.utils import bare_host
@@ -81,6 +84,10 @@ def _counted_urls_key(user_id: int, query: str) -> str:
return f"{_record_key(user_id, query)}:urls"
+def _domain_pages_key(user_id: int, query: str) -> str:
+ return f"{_record_key(user_id, query)}:domain-pages"
+
+
def _active_key(user_id: int) -> str:
return f"seed-crawl:{user_id}:active"
@@ -124,7 +131,8 @@ def start_seed_crawl(
return CrawlOutcome.ALREADY_RUNNING
record_key = _record_key(user_id, query)
- domains = sorted({bare_host(document.url) for document in allowed})
+ # Each domain with the number of Staan results it had, which the seed domains count.
+ domains = dict(sorted(Counter(bare_host(document.url) for document in allowed).items()))
new_seed_urls = [url for url in seed_urls if url in new_staan_urls]
job = {
"user_id": user_id,
@@ -134,11 +142,19 @@ def start_seed_crawl(
"domains": domains,
}
# An earlier crawl's pages are kept: the new one adds to them, and the user's total
- # already includes them.
+ # already includes them. Its progress and domains are this crawl's alone.
+ record = {
+ "status": STATUS_QUEUED,
+ "query": query,
+ "started_at": _now(),
+ "rounds": 0,
+ "domains": json.dumps(domains),
+ }
pipeline = redis.pipeline()
- pipeline.hset(record_key, mapping={"status": STATUS_QUEUED, "query": query, "started_at": _now()})
+ pipeline.hset(record_key, mapping=record)
pipeline.hsetnx(record_key, "pages_crawled", 0)
- pipeline.hdel(record_key, "finished_at")
+ pipeline.hdel(record_key, "finished_at", "crawl_started_at", "discovered")
+ pipeline.delete(_domain_pages_key(user_id, query))
pipeline.expire(record_key, settings.SEED_CRAWL_RECORD_TTL_SECONDS)
pipeline.lpush(QUEUE_KEY, json.dumps(job))
pipeline.execute()
@@ -173,13 +189,19 @@ def run_next_seed_crawl(index_path: str) -> bool:
def run_seed_crawl(
- user_id: int, query: str, seed_urls: list[str], new_seed_urls: list[str], domains: list[str], index_path: str
+ user_id: int, query: str, seed_urls: list[str], new_seed_urls: list[str], domains: dict[str, int], index_path: str
) -> None:
redis = get_redis_connection("default")
record_key = _record_key(user_id, query)
- redis.hset(record_key, "status", STATUS_CRAWLING)
+ redis.hset(record_key, mapping={"status": STATUS_CRAWLING, "crawl_started_at": _now()})
try:
- _crawl_and_record(user_id, query, seed_urls, set(new_seed_urls), domains, index_path, redis)
+ discovered = register_seed_domains(user_id, domains)
+ redis.hset(record_key, "discovered", json.dumps(sorted(discovered)))
+ domain_pages = _crawl_and_record(
+ user_id, query, seed_urls, set(new_seed_urls), list(domains), index_path, redis
+ )
+ # Only a finished crawl is recorded: a failed one's counts would understate its domains.
+ record_seed_domain_crawls({domain: domain_pages[domain] for domain in domains})
status = STATUS_DONE
except Exception:
# Recorded rather than retried: a retry would start again from the seeds, fetching
@@ -197,11 +219,14 @@ def run_seed_crawl(
def _crawl_and_record(
user_id: int, query: str, seed_urls: list[str], new_seed_urls: set[str], domains: list[str], index_path: str, redis
-):
+) -> Counter:
+ """Crawl, index and record what is new, returning how many new pages each domain gave."""
record_key = _record_key(user_id, query)
pages_key = _pages_key(user_id, query)
counted_urls_key = _counted_urls_key(user_id, query)
+ domain_pages_key = _domain_pages_key(user_id, query)
ttl = settings.SEED_CRAWL_RECORD_TTL_SECONDS
+ domain_pages = Counter()
for num_crawled, documents in crawl_within_domains(seed_urls, set(domains), redis):
indexed = index_new_documents(documents, index_path)
@@ -217,20 +242,27 @@ def _crawl_and_record(
first_counted = pipeline.execute()
new_documents = [document for document, added in zip(candidates, first_counted) if added]
logger.info("Seed crawl for user %d added %d new pages", user_id, len(new_documents))
+ round_domain_pages = Counter(bare_host(document.url) for document in new_documents)
+ domain_pages.update(round_domain_pages)
pipeline = redis.pipeline()
pipeline.hincrby(record_key, "pages_crawled", num_crawled)
+ pipeline.hincrby(record_key, "rounds", 1)
if new_documents:
pages = [{"url": doc.url, "title": doc.title, "extract": doc.extract} for doc in new_documents]
pipeline.rpush(pages_key, *[json.dumps(page) for page in pages])
pipeline.expire(pages_key, ttl)
pipeline.expire(counted_urls_key, ttl)
+ for domain, count in round_domain_pages.items():
+ pipeline.hincrby(domain_pages_key, domain, count)
+ pipeline.expire(domain_pages_key, ttl)
pipeline.execute()
if new_documents:
MwmblUser.objects.filter(id=user_id).update(
seed_search_pages_indexed=F("seed_search_pages_indexed") + len(new_documents)
)
+ return domain_pages
def crawl_within_domains(seed_urls: list[str], domains: set[str], redis):
@@ -307,6 +339,11 @@ def get_seed_crawl_summary(user_id: int, query: str) -> dict | None:
if not record:
return None
fields = {key.decode(): value.decode() for key, value in record.items()}
+ domain_pages = {key.decode(): int(value) for key, value in redis.hgetall(_domain_pages_key(user_id, query)).items()}
+ # Records written before seed domains existed have no domains; they expire within a week.
+ domains = list(json.loads(fields.get("domains", "{}")))
+ # Absent until the worker has started the crawl and registered its domains.
+ discovered = json.loads(fields.get("discovered", "[]"))
return {
"query": fields["query"],
"status": fields["status"],
@@ -314,9 +351,49 @@ def get_seed_crawl_summary(user_id: int, query: str) -> dict | None:
"finished_at": fields.get("finished_at"),
"pages_crawled": int(fields["pages_crawled"]),
"pages_indexed": redis.llen(_pages_key(user_id, query)),
+ "progress": _progress(fields),
+ "domains": _domain_results(domains, discovered, domain_pages),
}
+def _progress(fields: dict[str, str]) -> float:
+ """How far through its crawl a record is, from 0 to 1.
+
+ A crawl ends at whichever comes first of its last round - at most one per page of a
+ domain's budget - and its time limit, so its progress is the further along of the two.
+ It jumps to 1 when the frontier runs dry before either.
+ """
+ if fields["status"] == STATUS_QUEUED:
+ return 0.0
+ if fields["status"] != STATUS_CRAWLING:
+ return 1.0
+ rounds_progress = int(fields["rounds"]) / settings.SEED_CRAWL_MAX_PAGES_PER_DOMAIN
+ elapsed = datetime.now(timezone.utc) - datetime.fromisoformat(fields["crawl_started_at"])
+ time_progress = elapsed.total_seconds() / settings.SEED_CRAWL_MAX_SECONDS
+ return min(1.0, max(rounds_progress, time_progress))
+
+
+def _domain_results(domains: list[str], discovered: list[str], domain_pages: dict[str, int]) -> list[dict]:
+ """What this crawl found on each of its domains, with their seed domain scores, best first.
+
+ A domain only has scores once the worker has started the crawl and registered it.
+ """
+ seed_domains = SeedDomain.objects.filter(domain__in=domains).order_by("domain")
+ results = [
+ {
+ "domain": seed_domain.domain,
+ "newly_discovered": seed_domain.domain in discovered,
+ "pages_indexed": domain_pages.get(seed_domain.domain, 0),
+ "new_page_score": new_page_score(domain_pages.get(seed_domain.domain, 0)),
+ "recent_new_page_score": seed_domain.new_page_score,
+ "staan_results": seed_domain.staan_results,
+ "score": seed_domain.score,
+ }
+ for seed_domain in seed_domains
+ ]
+ return sorted(results, key=lambda result: result["pages_indexed"], reverse=True)
+
+
def get_seed_crawl(user_id: int, query: str) -> dict | None:
"""This user's seed crawl for this query with the pages it added, or None if there is none."""
summary = get_seed_crawl_summary(user_id, query)
diff --git a/mwmbl/indexer/seed_domains.py b/mwmbl/indexer/seed_domains.py
new file mode 100644
index 0000000..3ab6d66
--- /dev/null
+++ b/mwmbl/indexer/seed_domains.py
@@ -0,0 +1,69 @@
+"""Seed domains: the domains Staan returns for seed crawls, scored for crawlers.
+
+Two things make a domain worth crawling. It should still have pages the index lacks: its
+new-page score is the share of a crawl's per-domain budget (SEED_CRAWL_MAX_PAGES_PER_DOMAIN)
+that turned out to be new pages, averaged over its last SEED_DOMAIN_RECENT_CRAWLS crawls, so
+it falls as crawls saturate the domain. And it should be likely to answer searches: Staan
+returning it often, across everyone's seed queries, is the evidence for that. A domain's
+score is the product of the two, and GET /api/v2/combined-search/seed-domains lists the
+domains by it.
+
+The user whose crawl first met a domain is kept against it, so that discovering a domain
+that turns out well can be rewarded later. Nothing shows it yet.
+"""
+
+from django.conf import settings
+from django.db import transaction
+from django.db.models import F
+
+from mwmbl.models import SeedDomain, SeedDomainCrawl
+
+
+def new_page_score(pages_indexed: int) -> float:
+ """The share of a crawl's per-domain budget that pages_indexed new pages make."""
+ return pages_indexed / settings.SEED_CRAWL_MAX_PAGES_PER_DOMAIN
+
+
+def register_seed_domains(user_id: int, staan_results: dict[str, int]) -> set[str]:
+ """Count a seed crawl's Staan results against their domains, returning the domains it discovered.
+
+ staan_results maps each domain to how many of the query's Staan results it had.
+ """
+ known = set(SeedDomain.objects.filter(domain__in=staan_results).values_list("domain", flat=True))
+ discovered = set(staan_results) - known
+ with transaction.atomic():
+ # ignore_conflicts because a domain may have been discovered since the read above.
+ SeedDomain.objects.bulk_create(
+ [SeedDomain(domain=domain, discovered_by_id=user_id) for domain in sorted(discovered)],
+ ignore_conflicts=True,
+ )
+ for domain, count in staan_results.items():
+ SeedDomain.objects.filter(domain=domain).update(
+ staan_results=F("staan_results") + count,
+ score=F("new_page_score") * (F("staan_results") + count),
+ )
+ return discovered
+
+
+def record_seed_domain_crawls(pages_indexed: dict[str, int]) -> None:
+ """Record a finished crawl's new pages per domain and rescore those domains.
+
+ pages_indexed holds every domain the crawl covered, including those that gave nothing:
+ a crawl that finds a domain exhausted is what lowers its score.
+ """
+ with transaction.atomic():
+ seed_domains = SeedDomain.objects.select_for_update().filter(domain__in=pages_indexed)
+ for seed_domain in seed_domains:
+ SeedDomainCrawl.objects.create(seed_domain=seed_domain, pages_indexed=pages_indexed[seed_domain.domain])
+ recent_pages = list(
+ seed_domain.crawls.order_by("-crawled_at", "-id").values_list("pages_indexed", flat=True)[
+ : settings.SEED_DOMAIN_RECENT_CRAWLS
+ ]
+ )
+ seed_domain.new_page_score = new_page_score(sum(recent_pages)) / len(recent_pages)
+ seed_domain.score = seed_domain.new_page_score * seed_domain.staan_results
+ seed_domain.save(update_fields=["new_page_score", "score"])
+
+
+def top_seed_domains(limit: int) -> list[SeedDomain]:
+ return list(SeedDomain.objects.order_by("-score", "domain")[:limit])
diff --git a/mwmbl/migrations/0043_seed_domains.py b/mwmbl/migrations/0043_seed_domains.py
new file mode 100644
index 0000000..8ab31d7
--- /dev/null
+++ b/mwmbl/migrations/0043_seed_domains.py
@@ -0,0 +1,83 @@
+# Generated by Django 5.2.13 on 2026-10-10 08:33
+
+import django.db.models.deletion
+import django.utils.timezone
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("mwmbl", "0042_mwmbluser_seed_search_pages_indexed"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="SeedDomain",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("domain", models.CharField(max_length=300, unique=True)),
+ (
+ "discovered_at",
+ models.DateTimeField(default=django.utils.timezone.now),
+ ),
+ ("staan_results", models.IntegerField(default=0)),
+ ("new_page_score", models.FloatField(default=0.0)),
+ ("score", models.FloatField(default=0.0)),
+ ],
+ ),
+ migrations.CreateModel(
+ name="SeedDomainCrawl",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("crawled_at", models.DateTimeField(default=django.utils.timezone.now)),
+ ("pages_indexed", models.IntegerField()),
+ ],
+ ),
+ migrations.AddField(
+ model_name="seeddomain",
+ name="discovered_by",
+ field=models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.SET_NULL,
+ related_name="discovered_seed_domains",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ migrations.AddField(
+ model_name="seeddomaincrawl",
+ name="seed_domain",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="crawls",
+ to="mwmbl.seeddomain",
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="seeddomain",
+ index=models.Index(fields=["-score"], name="mwmbl_seedd_score_503db3_idx"),
+ ),
+ migrations.AddIndex(
+ model_name="seeddomaincrawl",
+ index=models.Index(
+ fields=["seed_domain", "-crawled_at"],
+ name="mwmbl_seedd_seed_do_33878e_idx",
+ ),
+ ),
+ ]
diff --git a/mwmbl/models.py b/mwmbl/models.py
index 20fccee..bfd12b1 100644
--- a/mwmbl/models.py
+++ b/mwmbl/models.py
@@ -490,3 +490,48 @@ class ModerationModelArtifact(models.Model):
def __str__(self):
return f"{self.version} ({self.created_on:%Y-%m-%d})"
+
+
+class SeedDomain(models.Model):
+ """A domain Staan returned for a seed crawl (Combined Search with crawl=true).
+
+ Scored for how much a crawl of it is still likely to add to the index, and for how often
+ Staan returns it - its likely benefit to searches - so crawlers can go where both are
+ high. See mwmbl.indexer.seed_domains.
+ """
+
+ domain = models.CharField(max_length=300, unique=True)
+ # Kept so discovering a high-impact domain can be rewarded later; private for now.
+ discovered_by = models.ForeignKey(
+ MwmblUser, on_delete=models.SET_NULL, null=True, related_name="discovered_seed_domains"
+ )
+ discovered_at = models.DateTimeField(default=timezone.now)
+ # Staan results for this domain across every seed crawl.
+ staan_results = models.IntegerField(default=0)
+ # Denormalised from the recent SeedDomainCrawls, so the domains can be ordered by score.
+ new_page_score = models.FloatField(default=0.0)
+ score = models.FloatField(default=0.0)
+
+ class Meta:
+ indexes = [
+ models.Index(fields=["-score"]),
+ ]
+
+ def __str__(self):
+ return self.domain
+
+
+class SeedDomainCrawl(models.Model):
+ """How many new pages one finished seed crawl added from one domain.
+
+ Holds neither the user nor the query: queries are private.
+ """
+
+ seed_domain = models.ForeignKey(SeedDomain, on_delete=models.CASCADE, related_name="crawls")
+ crawled_at = models.DateTimeField(default=timezone.now)
+ pages_indexed = models.IntegerField()
+
+ class Meta:
+ indexes = [
+ models.Index(fields=["seed_domain", "-crawled_at"]),
+ ]
diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.py
index 16a9a06..35c3caf 100644
--- a/mwmbl/settings_common.py
+++ b/mwmbl/settings_common.py
@@ -317,6 +317,9 @@ SEED_CRAWL_THREADS = 8
SEED_CRAWL_DOMAIN_DELAY_SECONDS = 1.0
# Queries are private, so a user's record of what their crawl added is not kept for long.
SEED_CRAWL_RECORD_TTL_SECONDS = 7 * 24 * 60 * 60
+# A seed domain's new-page score averages only its most recent crawls, so a domain the
+# crawls have saturated drops down the list rather than living off its first crawl.
+SEED_DOMAIN_RECENT_CRAWLS = 5
# Jev (TypeSafe), which orders Combined Search's results - see mwmbl.tinysearchengine.jev_rank.
# Without a key, or when a request fails or times out, Combined Search serves the LTR's
diff --git a/mwmbl/tinysearchengine/combined_search.py b/mwmbl/tinysearchengine/combined_search.py
index b9fd25d..62b983e 100644
--- a/mwmbl/tinysearchengine/combined_search.py
+++ b/mwmbl/tinysearchengine/combined_search.py
@@ -35,7 +35,7 @@ from logging import getLogger
from asgiref.sync import sync_to_async
from django.conf import settings
-from ninja import Router, Schema
+from ninja import Query, Router, Schema
from ninja.errors import HttpError
from ninja_jwt.authentication import JWTAuth
from pydantic import Field
@@ -50,6 +50,7 @@ from mwmbl.indexer.seed_crawl import (
get_seed_crawl_summary,
start_seed_crawl,
)
+from mwmbl.indexer.seed_domains import top_seed_domains
from mwmbl.membership import combined_search_monthly_limit
from mwmbl.models import Membership, UserBilling
from mwmbl.quota import (
@@ -103,6 +104,36 @@ class NewPage(Schema):
extract: str
+class SeedCrawlDomain(Schema):
+ domain: str
+ newly_discovered: bool = Field(description="Whether this crawl was the first to meet the domain.")
+ pages_indexed: int = Field(description="New pages this crawl has added from the domain so far.", examples=[50])
+ new_page_score: float = Field(
+ description="`pages_indexed` as a share of the most a crawl takes from one domain "
+ f"({settings.SEED_CRAWL_MAX_PAGES_PER_DOMAIN:,} pages), from 0 to 1.",
+ examples=[0.5],
+ )
+ recent_new_page_score: float = Field(
+ description="The average `new_page_score` of the domain's last "
+ f"{settings.SEED_DOMAIN_RECENT_CRAWLS} finished crawls, by anyone. It falls as the crawls "
+ "exhaust the domain.",
+ examples=[0.3],
+ )
+ staan_results: int = Field(description="EUSP results for the domain across everyone's seed crawls.")
+ score: float = Field(description="`recent_new_page_score` times `staan_results`: how worth crawling the domain is.")
+
+
+class SeedDomainResponse(Schema):
+ domain: str
+ new_page_score: float = Field(
+ description=f"The average share of a crawl's per-domain budget that the domain's last "
+ f"{settings.SEED_DOMAIN_RECENT_CRAWLS} seed crawls found to be new pages, from 0 to 1.",
+ examples=[0.3],
+ )
+ staan_results: int = Field(description="EUSP results for the domain across all seed crawls.")
+ score: float = Field(description="`new_page_score` times `staan_results`.", examples=[1.2])
+
+
class SeedCrawlSummaryResponse(Schema):
query: str
status: str = Field(
@@ -115,6 +146,14 @@ class SeedCrawlSummaryResponse(Schema):
description="Pages fetched so far, by every crawl of this query, including ones that added nothing."
)
pages_indexed: int = Field(description="Pages the crawl has added to the Mwmbl index so far.", examples=[42])
+ progress: float = Field(
+ description="How far through the latest crawl of this query, from 0 (queued) to 1 (done or failed).",
+ examples=[0.25],
+ )
+ domains: list[SeedCrawlDomain] = Field(
+ description="The domains EUSP returned, which the latest crawl stays within, with what it has "
+ "found on each, most new pages first. Empty until the crawl starts."
+ )
class SeedCrawlResponse(SeedCrawlSummaryResponse):
@@ -319,3 +358,15 @@ def init_router(ranker) -> None:
if summary is None:
raise HttpError(404, "No seed crawl for this query.")
return summary
+
+ @router.get(
+ "seed-domains",
+ response=list[SeedDomainResponse],
+ auth=None,
+ summary="Seed domains, best first",
+ description="The domains EUSP has returned for seed crawls, ordered by `score`: how likely "
+ "a crawl of the domain is to add new pages to the index, times how often EUSP returns it. "
+ "For crawlers deciding where to go next.",
+ )
+ def seed_domains(request, limit: int = Query(100, ge=1, le=1000)):
+ return top_seed_domains(limit)
diff --git a/test/test_combined_search.py b/test/test_combined_search.py
index 4dc2196..de127f9 100644
--- a/test/test_combined_search.py
+++ b/test/test_combined_search.py
@@ -536,7 +536,7 @@ def test_crawl_schedules_a_seed_crawl_of_what_the_index_lacked(
"query": "tokio",
"seed_urls": [STAAN_RESULT.url],
"new_seed_urls": [STAAN_RESULT.url],
- "domains": ["tokio.rs"],
+ "domains": {"tokio.rs": 1},
}
assert seed_crawl.get_seed_crawl(user.id, "tokio")["status"] == "queued"
diff --git a/test/test_seed_crawl.py b/test/test_seed_crawl.py
index cee587e..bce4ebc 100644
--- a/test/test_seed_crawl.py
+++ b/test/test_seed_crawl.py
@@ -13,6 +13,7 @@ from ninja_jwt.tokens import RefreshToken
from mwmbl.indexer import index_batches, seed_crawl
from mwmbl.indexer.index_batches import index_new_documents
+from mwmbl.models import SeedDomain, SeedDomainCrawl
from mwmbl.tinysearchengine.indexer import Document, DocumentSource, TinyIndex
User = get_user_model()
@@ -166,7 +167,7 @@ def test_only_staan_results_missing_from_the_index_are_seeds(redis_cache, monkey
# Not retrieved, but Combined Search's write found the index already held it.
assert job["new_seed_urls"] == []
# Every Staan domain is crawlable, including those of results the index already had.
- assert job["domains"] == ["rust-lang.github.io", "tokio.rs"]
+ assert job["domains"] == {"rust-lang.github.io": 1, "tokio.rs": 1}
def test_blacklisted_staan_results_are_neither_seeds_nor_domains(redis_cache, monkeypatch):
@@ -176,7 +177,7 @@ def test_blacklisted_staan_results_are_neither_seeds_nor_domains(redis_cache, mo
[job] = _queued_jobs(redis_cache)
assert SEED not in job["seed_urls"]
- assert job["domains"] == ["rust-lang.github.io"]
+ assert job["domains"] == {"rust-lang.github.io": 1}
def test_nothing_to_crawl_starts_nothing(redis_cache, monkeypatch):
@@ -227,7 +228,7 @@ def _run(user, index_path, seed_urls=(SEED,), new_seed_urls=()):
seed_crawl.start_seed_crawl(user.id, "tokio", [], STAAN_RESULTS, set())
# Crawl only the seeds and domain given, whatever start_seed_crawl made of STAAN_RESULTS.
seed_crawl.get_redis_connection("default").delete(seed_crawl.QUEUE_KEY)
- seed_crawl.run_seed_crawl(user.id, "tokio", list(seed_urls), list(new_seed_urls), ["tokio.rs"], index_path)
+ seed_crawl.run_seed_crawl(user.id, "tokio", list(seed_urls), list(new_seed_urls), {"tokio.rs": 1}, index_path)
return seed_crawl.get_seed_crawl(user.id, "tokio")
@@ -374,6 +375,105 @@ def test_the_users_stats_report_their_seed_search_total(user):
assert response.json()["seed_search_pages_indexed"] == 12
+# ---------------------------------------------------------------------------
+# Progress and seed domains
+# ---------------------------------------------------------------------------
+
+
+def test_a_queued_crawl_has_no_progress_and_no_domains_yet(redis_cache, monkeypatch, db):
+ monkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: set())
+ seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS, set())
+
+ summary = seed_crawl.get_seed_crawl_summary(1, "tokio")
+
+ assert summary["progress"] == 0.0
+ assert summary["domains"] == []
+
+
+def test_progress_counts_rounds_against_a_domains_page_limit(redis_cache, user, settings):
+ settings.SEED_CRAWL_MAX_PAGES_PER_DOMAIN = 4
+ seed_crawl.start_seed_crawl(user.id, "tokio", [], STAAN_RESULTS, set())
+ record_key = seed_crawl._record_key(user.id, "tokio")
+ redis_cache.hset(record_key, mapping={"status": "crawling", "crawl_started_at": seed_crawl._now(), "rounds": 1})
+
+ assert seed_crawl.get_seed_crawl_summary(user.id, "tokio")["progress"] == pytest.approx(0.25, abs=0.01)
+
+
+def test_a_finished_crawl_reports_its_domains_with_their_scores(fake_web, redis_cache, user, index_path):
+ record = _run(user, index_path)
+
+ assert record["progress"] == 1.0
+ assert record["domains"] == [
+ {
+ "domain": "tokio.rs",
+ "newly_discovered": True,
+ "pages_indexed": 3,
+ "new_page_score": 0.03,
+ "recent_new_page_score": 0.03,
+ "staan_results": 1,
+ "score": 0.03,
+ }
+ ]
+
+
+def test_the_user_who_first_crawls_a_domain_is_its_discoverer(fake_web, redis_cache, user, index_path):
+ _run(user, index_path)
+ other = User.objects.create_user(username="other", email="[email protected]", password="x")
+
+ record = _run(other, index_path)
+
+ [domain] = record["domains"]
+ assert domain["newly_discovered"] is False
+ assert domain["staan_results"] == 2
+ assert SeedDomain.objects.get(domain="tokio.rs").discovered_by == user
+
+
+def test_a_domain_the_crawls_have_exhausted_loses_its_score(fake_web, redis_cache, user, index_path, settings):
+ settings.SEED_DOMAIN_RECENT_CRAWLS = 2
+ _run(user, index_path)
+ assert SeedDomain.objects.get(domain="tokio.rs").new_page_score == 0.03
+
+ # The pages are no longer new, so these crawls add none.
+ _run(user, index_path)
+ assert SeedDomain.objects.get(domain="tokio.rs").new_page_score == 0.015
+ _run(user, index_path)
+ seed_domain = SeedDomain.objects.get(domain="tokio.rs")
+ assert seed_domain.new_page_score == 0.0
+ assert seed_domain.score == 0.0
+
+
+def test_a_failed_crawl_does_not_score_its_domains(fake_web, redis_cache, user, index_path, monkeypatch):
+ def failing_crawl_batch(urls, num_threads, delay_seconds, redis):
+ raise ConnectionError("Redis went away")
+
+ monkeypatch.setattr(seed_crawl, "crawl_batch", failing_crawl_batch)
+
+ _run(user, index_path)
+
+ assert SeedDomain.objects.get(domain="tokio.rs").staan_results == 1
+ assert not SeedDomainCrawl.objects.exists()
+
+
+def test_the_seed_domains_endpoint_lists_the_best_first_without_their_discoverers(user):
+ SeedDomain.objects.create(
+ domain="low.example.com", discovered_by=user, new_page_score=0.1, staan_results=1, score=0.1
+ )
+ SeedDomain.objects.create(
+ domain="high.example.com", discovered_by=user, new_page_score=0.5, staan_results=4, score=2
+ )
+
+ response = Client().get("/api/v2/combined-search/seed-domains?limit=1")
+
+ assert response.status_code == 200
+ assert response.json() == [{"domain": "high.example.com", "new_page_score": 0.5, "staan_results": 4, "score": 2.0}]
+
+
def test_index_new_documents_returns_only_urls_the_index_lacked(index_path, monkeypatch):
monkeypatch.setattr(index_batches, "filter_blacklisted_documents", lambda documents: documents)
first = Document("Tokio tutorial", "https://tokio.rs/tutorial", "Learn tokio.")