Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Add opt-in seed crawls to Combined Search

Claudee76c43f4f15c
diff --git a/mwmbl/background.py b/mwmbl/background.py
index 70f313f..6d93193 100644
--- a/mwmbl/background.py
+++ b/mwmbl/background.py
@@ -6,6 +6,7 @@ Django Background Tasks for periodic maintenance:
- report_usage_to_polar: reports billable usage overage to Polar once per hour
- refresh_blacklist_snapshot: rebuilds the blacklist the search path filters against
- purge_blacklisted_from_queue: removes retrieval-filtered documents from the index
+ - seed_crawl: crawls outwards from a Combined Search's Staan results, on request
"""
import logging
@@ -27,6 +28,7 @@ from mwmbl.crawler.stats import StatsManager
from mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklist, refresh_snapshot
from mwmbl.indexer.purge_blacklisted import purge_documents
from mwmbl.indexer.purge_queue import drain_purge_queue, queue_size
+from mwmbl.indexer.seed_crawl import run_seed_crawl
from mwmbl.models import DomainEvidence, DomainSubmission, OldIndex, UsageBucket
from mwmbl.moderation.evidence import crawl_domain, store_evidence, store_failure
from mwmbl.moderation.model import reset_model_cache
@@ -251,6 +253,16 @@ def report_usage_to_polar():
# ---------------------------------------------------------------------------
+@background(schedule=0)
+def seed_crawl(user_id: int, query: str, seed_urls: list[str], domains: list[str]):
+ """Crawl the pages a Combined Search found that the index lacked - see mwmbl.indexer.seed_crawl.
+
+ Takes minutes, which is why the queue runs tasks concurrently (BACKGROUND_TASK_RUN_ASYNC).
+ """
+ index_path = Path(settings.DATA_PATH) / settings.INDEX_NAME
+ run_seed_crawl(user_id, query, seed_urls, domains, str(index_path))
+
+
@background(schedule=0)
def enrich_domain_submission(domain: str):
"""Crawl a submitted domain and store the suggestion the moderation queue will read.
diff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.py
index 6dab3c2..245c3e9 100644
--- a/mwmbl/indexer/index_batches.py
+++ b/mwmbl/indexer/index_batches.py
@@ -76,16 +76,43 @@ def index_documents(documents, index_path):
POST /crawler/results calls this from a gunicorn worker, and the providers download
tens of megabytes and hold ~156 MB of domain strings for the process's life - see
blacklist_snapshot."""
+ page_documents = _page_documents(documents, index_path)
+ new_page_doc_counts = index_pages(index_path, page_documents)
+ end_time = datetime.now(timezone.utc)
+ return end_time, new_page_doc_counts
+
+
+def index_new_documents(documents, index_path) -> set[str]:
+ """index_documents, returning the URLs of the documents the index did not hold before.
+
+ A URL counts as new when none of the pages it is written to held it beforehand. Those
+ are the pages its tokens hash to, so an earlier copy of the same page lives there too.
+ Like index_results_against_query's count, this is a slight upper bound: a new document
+ the store then trims from a full page is still counted.
+ """
+ page_documents = _page_documents(documents, index_path)
+ seen_urls = set()
+ with TinyIndex(Document, index_path, "r") as indexer:
+ for page_index in page_documents:
+ try:
+ seen_urls |= {document.url for document in indexer.get_page(page_index)}
+ except PageError:
+ # An unlocked read, as in index_results_against_query: it only decides
+ # what counts as new, and the write below reads the page properly.
+ logger.warning("Could not read index page %d while finding new URLs", page_index)
+ new_urls = {document.url for documents in page_documents.values() for document in documents} - seen_urls
+ index_pages(index_path, page_documents)
+ return new_urls
+
+
+def _page_documents(documents, index_path) -> dict[int, list[Document]]:
documents = filter_blacklisted_documents(documents)
# Cleaned here rather than at each of the paths above, for the same reason the
# blacklist is: every one of them takes its text from somewhere outside, and a title or
# an extract holding a character that cannot be stored costs the whole page it would be
# written to - a page that is shared with documents from everywhere else.
cleaned_documents = [cleaned_document(document) for document in documents]
- page_documents = preprocess_documents(cleaned_documents, index_path)
- new_page_doc_counts = index_pages(index_path, page_documents)
- end_time = datetime.now(timezone.utc)
- return end_time, new_page_doc_counts
+ return preprocess_documents(cleaned_documents, index_path)
def filter_blacklisted_documents(documents: list[Document]) -> list[Document]:
diff --git a/mwmbl/indexer/seed_crawl.py b/mwmbl/indexer/seed_crawl.py
new file mode 100644
index 0000000..3a5d1dd
--- /dev/null
+++ b/mwmbl/indexer/seed_crawl.py
@@ -0,0 +1,188 @@
+"""Seed crawls: crawling outwards from the pages Staan found that the index lacked.
+
+Combined Search with crawl=true hands the Staan results the index did not already hold to
+a background task (mwmbl.background.seed_crawl), which crawls them and follows their links,
+breadth first, until it has fetched SEED_CRAWL_MAX_PAGES pages. Links are only followed to
+the domains Staan returned for the query, so a crawl stays on the sites the query was about.
+
+The crawl goes a round at a time, one URL per domain per round and at least
+SEED_CRAWL_DOMAIN_DELAY_SECONDS apart, so no site is fetched from faster than that however
+much of the frontier it holds. Each round is indexed as it finishes, so what a crawl has
+added is visible while it is still running.
+
+What it added is recorded in Redis against the user and the query, where
+GET /api/v2/combined-search/new-pages reads it, and counted on the user for their stats.
+"""
+
+import hashlib
+import json
+import time
+from collections import deque
+from datetime import datetime, timezone
+from logging import getLogger
+
+from django.conf import settings
+from django.db.models import F
+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.tinysearchengine.indexer import Document
+from mwmbl.tinysearchengine.rank import find_blacklisted_urls
+from mwmbl.utils import bare_host
+
+logger = getLogger(__name__)
+
+STATUS_CRAWLING = "crawling"
+STATUS_DONE = "done"
+
+
+def _record_key(user_id: int, query: str) -> str:
+ # Hashed so that a user's private query is not spelled out in the key space.
+ query_hash = hashlib.sha256(query.encode()).hexdigest()
+ return f"seed-crawl:{user_id}:{query_hash}"
+
+
+def _pages_key(user_id: int, query: str) -> str:
+ return f"{_record_key(user_id, query)}:pages"
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def start_seed_crawl(user_id: int, query: str, index_pages: list[Document], staan_results: list[Document]):
+ """Record a seed crawl as started, returning the seed URLs and domains to crawl it with.
+
+ None when there is nothing to crawl - every Staan result is already in the index - or
+ when this user's crawl for this query is still running, which a repeated search must
+ not start again.
+ """
+ blacklisted_urls = find_blacklisted_urls(staan_results)
+ allowed = [document for document in staan_results if document.url not in blacklisted_urls]
+ indexed_urls = {document.url for document in index_pages}
+ seed_urls = [document.url for document in allowed if document.url not in indexed_urls]
+ if not seed_urls:
+ return None
+
+ redis = get_redis_connection("default")
+ record_key = _record_key(user_id, query)
+ if redis.hget(record_key, "status") == STATUS_CRAWLING.encode():
+ return None
+
+ ttl = settings.SEED_CRAWL_RECORD_TTL_SECONDS
+ pipeline = redis.pipeline()
+ pipeline.delete(record_key, _pages_key(user_id, query))
+ pipeline.hset(
+ record_key,
+ mapping={"status": STATUS_CRAWLING, "query": query, "started_at": _now(), "pages_crawled": 0},
+ )
+ pipeline.expire(record_key, ttl)
+ pipeline.execute()
+
+ domains = sorted({bare_host(document.url) for document in allowed})
+ return seed_urls, domains
+
+
+def run_seed_crawl(user_id: int, query: str, seed_urls: list[str], domains: list[str], index_path: str) -> None:
+ redis = get_redis_connection("default")
+ record_key = _record_key(user_id, query)
+ pages_key = _pages_key(user_id, query)
+ ttl = settings.SEED_CRAWL_RECORD_TTL_SECONDS
+
+ for num_crawled, documents in crawl_within_domains(seed_urls, set(domains), redis):
+ # The seeds were missing from the index when the user searched, but Combined Search
+ # has since written Staan's snippets of them, so the index alone no longer says so.
+ new_urls = index_new_documents(documents, index_path) | set(seed_urls)
+ new_documents = [document for document in documents if document.url in new_urls]
+ logger.info("Seed crawl for user %d added %d new pages", user_id, len(new_documents))
+
+ pipeline = redis.pipeline()
+ pipeline.hincrby(record_key, "pages_crawled", num_crawled)
+ 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.execute()
+
+ if new_documents:
+ MwmblUser.objects.filter(id=user_id).update(
+ seed_search_pages_indexed=F("seed_search_pages_indexed") + len(new_documents)
+ )
+
+ pipeline = redis.pipeline()
+ pipeline.hset(record_key, mapping={"status": STATUS_DONE, "finished_at": _now()})
+ pipeline.expire(record_key, ttl)
+ pipeline.execute()
+
+
+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.
+ """
+ frontiers: dict[str, deque[str]] = {}
+ seen_urls = set()
+
+ def enqueue(url: str) -> None:
+ domain = bare_host(url)
+ if url in seen_urls or domain not in domains:
+ return
+ seen_urls.add(url)
+ frontiers.setdefault(domain, deque()).append(url)
+
+ for url in seed_urls:
+ enqueue(url)
+
+ max_pages = settings.SEED_CRAWL_MAX_PAGES
+ num_crawled = 0
+ last_round_started = None
+ while num_crawled < max_pages:
+ batch = [frontier.popleft() for frontier in frontiers.values() if frontier][: max_pages - num_crawled]
+ if not batch:
+ return
+
+ if last_round_started is not None:
+ elapsed = time.monotonic() - last_round_started
+ time.sleep(max(0.0, settings.SEED_CRAWL_DOMAIN_DELAY_SECONDS - elapsed))
+ last_round_started = time.monotonic()
+
+ results = crawl_batch(batch, settings.SEED_CRAWL_THREADS, 0, redis)
+ num_crawled += len(batch)
+
+ documents = []
+ for result in results:
+ content = result["content"]
+ if content is None:
+ continue
+ if content["title"]:
+ documents.append(
+ Document(
+ content["title"],
+ result["url"],
+ content["extract"],
+ last_crawled=result["timestamp"] // 1000,
+ )
+ )
+ for link in content["links"] + content["extra_links"]:
+ enqueue(link)
+ yield len(batch), documents
+
+
+def get_seed_crawl(user_id: int, query: str) -> dict | None:
+ """The record of this user's seed crawl for this query, or None if there is none."""
+ redis = get_redis_connection("default")
+ record = redis.hgetall(_record_key(user_id, query))
+ if not record:
+ return None
+ fields = {key.decode(): value.decode() for key, value in record.items()}
+ pages = [json.loads(page) for page in redis.lrange(_pages_key(user_id, query), 0, -1)]
+ return {
+ "query": fields["query"],
+ "status": fields["status"],
+ "started_at": fields["started_at"],
+ "finished_at": fields.get("finished_at"),
+ "pages_crawled": int(fields["pages_crawled"]),
+ "pages": pages,
+ }
diff --git a/mwmbl/migrations/0042_mwmbluser_seed_search_pages_indexed.py b/mwmbl/migrations/0042_mwmbluser_seed_search_pages_indexed.py
new file mode 100644
index 0000000..d5d9846
--- /dev/null
+++ b/mwmbl/migrations/0042_mwmbluser_seed_search_pages_indexed.py
@@ -0,0 +1,17 @@
+# Generated by Django 5.2.13 on 2026-10-06 12:36
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("mwmbl", "0041_usagebucket_combined_search"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="mwmbluser",
+ name="seed_search_pages_indexed",
+ field=models.IntegerField(default=0),
+ ),
+ ]
diff --git a/mwmbl/models.py b/mwmbl/models.py
index 233c986..20fccee 100644
--- a/mwmbl/models.py
+++ b/mwmbl/models.py
@@ -11,7 +11,10 @@ from mwmbl.utils import bare_host
class MwmblUser(AbstractUser):
- pass
+ # Pages the user's seed crawls (Combined Search with crawl=true) have added to the index,
+ # all time. A total on the user rather than a UserStats column, because a UserStats row
+ # created for it would enter the crawl leaderboards with no crawl results behind it.
+ seed_search_pages_indexed = models.IntegerField(default=0)
class UserCuration(models.Model):
diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.py
index 67a4d2c..07c186d 100644
--- a/mwmbl/platform/api.py
+++ b/mwmbl/platform/api.py
@@ -1210,13 +1210,15 @@ def get_current_user(request):
summary="Get current user's contribution stats",
description=(
"Returns the authenticated user's contribution stats: how many results they "
- "have indexed, broken down per day for the last 30 days."
+ "have indexed, broken down per day for the last 30 days, and how many pages their "
+ "seed crawls (Combined Search with `crawl=true`) have added to the index in all."
),
tags=["Users"],
)
def get_current_user_stats(request):
user = request.user
- return stats_manager.get_user_stats(user.username)
+ stats = stats_manager.get_user_stats(user.username)
+ return {**stats, "seed_search_pages_indexed": user.seed_search_pages_indexed}
# ---------------------------------------------------------------------------
diff --git a/mwmbl/platform/schemas.py b/mwmbl/platform/schemas.py
index 30e9e42..42a6406 100644
--- a/mwmbl/platform/schemas.py
+++ b/mwmbl/platform/schemas.py
@@ -22,6 +22,7 @@ class UserStatsResponse(Schema):
username: str
results_indexed_today: int
results_indexed_daily: dict[str, int]
+ seed_search_pages_indexed: int
class SubscriptionResponse(Schema):
diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.py
index 3901a9a..c6dc908 100644
--- a/mwmbl/settings_common.py
+++ b/mwmbl/settings_common.py
@@ -206,6 +206,12 @@ HAS_DATABASE = True
# `dokku config:set <app> RUN_BACKGROUND_TASKS=true`.
RUN_BACKGROUND_TASKS = os.environ.get("RUN_BACKGROUND_TASKS", "false").lower() == "true"
+# Run tasks on a thread pool rather than one at a time. A seed crawl (below) takes minutes,
+# and in series it would hold up the hourly usage sync and the Polar report behind it.
+# Each task row is locked while it runs, so no task ever overlaps with itself.
+BACKGROUND_TASK_RUN_ASYNC = True
+BACKGROUND_TASK_ASYNC_THREADS = 4
+
SENTRY_DSN = os.environ.get("SENTRY_DSN")
@@ -305,6 +311,15 @@ STAAN_SEARCH_URL = os.environ.get("STAAN_SEARCH_URL", "https://api.staan.ai/v2/s
STAAN_MARKET = os.environ.get("STAAN_MARKET", "en-gb")
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 = 1000
+SEED_CRAWL_THREADS = 8
+# The least time between two fetches from one domain.
+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
+
# 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
# order instead.
diff --git a/mwmbl/tinysearchengine/combined_search.py b/mwmbl/tinysearchengine/combined_search.py
index 9736517..717e20d 100644
--- a/mwmbl/tinysearchengine/combined_search.py
+++ b/mwmbl/tinysearchengine/combined_search.py
@@ -4,8 +4,9 @@ Pools both sources, ranks the union with a model of its own, and answers with th
SearXNG-shaped JSON as /api/v2/search/. Authentication is required and a flat monthly quota
applies, exactly as for Super Search, which this endpoint is meant to replace.
-There is deliberately no streaming and no crawling here. Super Search streams because it
-crawls promoted pages and follows their outbound links, which takes seconds; Staan is the
+There is deliberately no streaming and no crawling on the request path. Super Search streams
+because it crawls promoted pages and follows their outbound links, which takes seconds; the
+seed crawl below runs in the background instead, so the response never waits on it. Staan is the
only network call here, and it is cached, so there is nothing to stream and a plain response
is what a client actually wants.
@@ -22,19 +23,28 @@ Staan's results are written back to the search index, against the query's unigra
bigrams, exactly as Super Search indexes what it finds: a page Staan found for one person's
query then becomes a candidate for every search, plain /search/ included. The write runs
alongside ranking, and the response reports how many new pages it added.
+
+With crawl=true the search also starts a seed crawl: the Staan results the index lacked are
+crawled in the background, following links within Staan's domains, and what that adds is
+read back from /new-pages - see mwmbl.indexer.seed_crawl. JWT only for now: it is free, and
+API customers are billed per request.
"""
import asyncio
from logging import getLogger
from asgiref.sync import sync_to_async
-from ninja import Router
+from django.conf import settings
+from ninja import Router, Schema
from ninja.errors import HttpError
+from ninja_jwt.authentication import JWTAuth
from pydantic import Field
from mwmbl import pricing
+from mwmbl.background import seed_crawl
from mwmbl.format import format_result_v2
from mwmbl.indexer.index_batches import index_results_against_query
+from mwmbl.indexer.seed_crawl import get_seed_crawl, start_seed_crawl
from mwmbl.membership import combined_search_monthly_limit
from mwmbl.models import Membership, UserBilling
from mwmbl.quota import (
@@ -63,6 +73,26 @@ class CombinedSearchResponse(SearchResponse):
"so a repeated query usually adds none.",
examples=[3],
)
+ crawl_scheduled: bool = Field(
+ description="Whether this search started a seed crawl (`crawl=true`). False when every "
+ "EUSP result is already in the index, or when a crawl for this query is still running.",
+ examples=[True],
+ )
+
+
+class NewPage(Schema):
+ url: str
+ title: str
+ extract: str
+
+
+class SeedCrawlResponse(Schema):
+ query: str
+ status: str = Field(description="`crawling` while the crawl runs, then `done`.", examples=["crawling"])
+ started_at: str
+ finished_at: str | None
+ pages_crawled: int = Field(description="Pages fetched so far, including ones that added nothing.")
+ pages: list[NewPage] = Field(description="Pages the crawl has added to the Mwmbl index so far.")
DESCRIPTION = (
@@ -87,6 +117,10 @@ DESCRIPTION = (
"every response.\n\n"
"EUSP's results are added to the Mwmbl index; `pages_indexed` reports how many new "
"pages that added.\n\n"
+ "With `crawl=true` (JWT only), the search also starts a background crawl of the EUSP results "
+ "that were not already in the Mwmbl index, following their links within the domains EUSP "
+ f"returned, up to {settings.SEED_CRAWL_MAX_PAGES:,} pages. "
+ "`GET /api/v2/combined-search/new-pages?q=...` lists what it has added.\n\n"
"If EUSP is down or unconfigured, the request loses its extra recall, not its "
"results: the index's results are ranked and returned as usual.\n\n"
"**Query parameter:** `q` - the search query string (required)."
@@ -99,7 +133,13 @@ OPENAPI_EXTRA = {
"in": "query",
"required": True,
"schema": {"type": "string", "example": "rust async runtimes"},
- }
+ },
+ {
+ "name": "crawl",
+ "in": "query",
+ "required": False,
+ "schema": {"type": "boolean", "default": False},
+ },
]
}
@@ -152,9 +192,13 @@ def init_router(ranker) -> None:
description=DESCRIPTION,
openapi_extra=OPENAPI_EXTRA,
)
- async def combined_search(request, q: str):
+ async def combined_search(request, q: str, crawl: bool = False):
user = await authenticate_user(request)
+ # Checked before the quota, so a refused request is not counted.
+ if crawl and request.headers.get("X-API-Key"):
+ raise HttpError(403, "crawl=true is not yet available with an API key.")
+
if not await sync_to_async(check_rate_limit)(user.id):
raise HttpError(429, "Rate limit exceeded: maximum 5 requests per second.")
@@ -196,6 +240,13 @@ def init_router(ranker) -> None:
asyncio.to_thread(index_staan_results, q, staan_results),
)
+ crawl_scheduled = False
+ if crawl:
+ crawl_args = await sync_to_async(start_seed_crawl)(user.id, q, retrieval.pages, staan_results)
+ if crawl_args is not None:
+ await sync_to_async(seed_crawl)(user.id, q, *crawl_args)
+ crawl_scheduled = True
+
formatted = [format_result_v2(result, i + 1, q) for i, result in enumerate(results)]
return CombinedSearchResponse(
query=q,
@@ -204,4 +255,20 @@ def init_router(ranker) -> None:
monthly_usage=monthly_usage,
monthly_limit=monthly_limit,
pages_indexed=pages_indexed,
+ crawl_scheduled=crawl_scheduled,
)
+
+ @router.get(
+ "new-pages",
+ response=SeedCrawlResponse,
+ auth=JWTAuth(),
+ summary="Pages added by a seed crawl",
+ description="What the seed crawl started by `crawl=true` for this query has added to the "
+ "Mwmbl index, so far or in all. 404 when there is no crawl for this query; records are "
+ "kept for a week.",
+ )
+ def new_pages(request, q: str):
+ record = get_seed_crawl(request.user.id, q)
+ if record is None:
+ raise HttpError(404, "No seed crawl for this query.")
+ return record
diff --git a/test/test_combined_search.py b/test/test_combined_search.py
index 63a1115..730823c 100644
--- a/test/test_combined_search.py
+++ b/test/test_combined_search.py
@@ -14,6 +14,7 @@ from urllib.parse import urlparse
import pytest
from allauth.account.models import EmailAddress
+from background_task.models import Task
from django.contrib.auth import get_user_model
from django.core.cache import cache
from django.test import Client, override_settings
@@ -21,6 +22,7 @@ from ninja_jwt.tokens import RefreshToken
import mwmbl.tinysearchengine.combined_search as combined_search
from mwmbl import pricing
+from mwmbl.indexer import seed_crawl
from mwmbl.membership import MembershipTier
from mwmbl.models import ApiKey, Membership, UserBilling, generate_api_key
from mwmbl.quota import (
@@ -55,6 +57,14 @@ WIKI_INDEX_RESULT = Document(
# ---------------------------------------------------------------------------
+class _Retrieval(list):
+ """What the stub ranker retrieves: a list of index pages that a seed crawl can also read."""
+
+ @property
+ def pages(self):
+ return list(self)
+
+
@pytest.fixture
def user(db):
u = User.objects.create_user(username="csuser", email="[email protected]", password="x")
@@ -105,7 +115,7 @@ def stub_sources(monkeypatch):
def fake_retrieve(query):
calls["retrieve_query"] = query
- return list(index)
+ return _Retrieval(index)
def fake_search_retrieved(retrieval, additional_results):
calls["additional_results"] = additional_results
@@ -491,3 +501,101 @@ def test_index_staan_results_writes_new_pages_once(tmp_path, monkeypatch):
with TinyIndex(Document, str(index_path), "r") as index:
assert [document.url for document in index.retrieve("tokio")] == [STAAN_RESULT.url]
+
+
+# ---------------------------------------------------------------------------
+# Seed crawls (the crawl itself is tested in test_seed_crawl.py)
+# ---------------------------------------------------------------------------
+
+NEW_PAGES_URL = f"{URL}new-pages"
+
+
+def crawl_sources(stub_sources, monkeypatch):
+ monkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: set())
+ return stub_sources
+
+
+def _crawl(client, access_token, query="tokio"):
+ return client.get(f"{URL}?q={query}&crawl=true", HTTP_AUTHORIZATION=f"Bearer {access_token}")
+
+
+def test_crawl_schedules_a_seed_crawl_of_what_the_index_lacked(
+ client, user, access_token, fresh_quota, redis_cache, crawl_sources
+):
+ crawl_sources()
+
+ body = _crawl(client, access_token).json()
+
+ assert body["crawl_scheduled"] is True
+ task = Task.objects.get(task_name="mwmbl.background.seed_crawl")
+ assert task.params() == ([user.id, "tokio", [STAAN_RESULT.url], ["tokio.rs"]], {})
+ assert seed_crawl.get_seed_crawl(user.id, "tokio")["status"] == "crawling"
+
+
+def test_no_crawl_without_the_flag(client, access_token, fresh_quota, redis_cache, crawl_sources):
+ crawl_sources()
+
+ assert _get(client, access_token).json()["crawl_scheduled"] is False
+ assert not Task.objects.filter(task_name="mwmbl.background.seed_crawl").exists()
+
+
+def test_no_crawl_when_the_index_already_has_every_staan_result(
+ client, access_token, fresh_quota, redis_cache, crawl_sources
+):
+ crawl_sources(index=(INDEX_RESULT, STAAN_RESULT))
+
+ assert _crawl(client, access_token).json()["crawl_scheduled"] is False
+ assert not Task.objects.filter(task_name="mwmbl.background.seed_crawl").exists()
+
+
+def test_crawl_is_refused_with_an_api_key_and_not_counted(
+ client, user, api_key, fresh_quota, redis_cache, crawl_sources
+):
+ crawl_sources()
+ UserBilling.objects.create(user=user, max_monthly_spend_cents=1_000)
+
+ response = client.get(f"{URL}?q=tokio&crawl=true", HTTP_X_API_KEY=api_key.raw_key)
+
+ assert response.status_code == 403
+ assert get_monthly_combined_search_api_count(user.id) == 0
+
+
+def test_new_pages_reports_the_crawl_for_the_query(client, access_token, fresh_quota, redis_cache, crawl_sources):
+ crawl_sources()
+ _crawl(client, access_token)
+
+ response = client.get(f"{NEW_PAGES_URL}?q=tokio", HTTP_AUTHORIZATION=f"Bearer {access_token}")
+
+ assert response.status_code == 200
+ assert response.json()["status"] == "crawling"
+ assert response.json()["pages"] == []
+
+
+def test_new_pages_is_404_without_a_crawl(client, access_token, redis_cache):
+ response = client.get(f"{NEW_PAGES_URL}?q=tokio", HTTP_AUTHORIZATION=f"Bearer {access_token}")
+
+ assert response.status_code == 404
+
+
+def test_new_pages_only_shows_the_users_own_crawls(client, access_token, fresh_quota, redis_cache, crawl_sources):
+ crawl_sources()
+ _crawl(client, access_token)
+ other = User.objects.create_user(username="other", email="[email protected]", password="x")
+ other_token = str(RefreshToken.for_user(other).access_token)
+
+ response = client.get(f"{NEW_PAGES_URL}?q=tokio", HTTP_AUTHORIZATION=f"Bearer {other_token}")
+
+ assert response.status_code == 404
+
+
+def test_new_pages_requires_a_jwt(client, api_key):
+ assert client.get(f"{NEW_PAGES_URL}?q=tokio", HTTP_X_API_KEY=api_key.raw_key).status_code == 401
diff --git a/test/test_seed_crawl.py b/test/test_seed_crawl.py
new file mode 100644
index 0000000..6920730
--- /dev/null
+++ b/test/test_seed_crawl.py
@@ -0,0 +1,229 @@
+"""Tests for seed crawls (mwmbl.indexer.seed_crawl): what gets crawled, what counts as new,
+and what is recorded for the user. The endpoint that starts a crawl is tested with the
+rest of Combined Search, in test_combined_search.py.
+"""
+
+from pathlib import Path
+
+import pytest
+from django.contrib.auth import get_user_model
+from django.test import Client
+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.tinysearchengine.indexer import Document, DocumentSource, TinyIndex
+
+User = get_user_model()
+
+SEED = "https://www.tokio.rs/"
+STAAN_RESULTS = [
+ Document("Tokio", SEED, "An async runtime.", source=DocumentSource.STAAN),
+ Document("Async book", "https://rust-lang.github.io/async-book/", "Async Rust.", source=DocumentSource.STAAN),
+]
+
+
+def _page(title, links=()):
+ return {"title": title, "extract": f"About {title}.", "links": list(links), "extra_links": []}
+
+
+# The web the fake crawler sees: url -> content, or None for a fetch that failed.
+WEB = {
+ SEED: _page("Tokio runtime", ["https://tokio.rs/tutorial", "https://elsewhere.example.com/"]),
+ "https://tokio.rs/tutorial": _page("Tokio tutorial", ["https://tokio.rs/tutorial/spawning", SEED]),
+ "https://tokio.rs/tutorial/spawning": _page("Spawning tasks"),
+ "https://elsewhere.example.com/": _page("Elsewhere"),
+}
+
+
+def fake_web(monkeypatch, settings):
+ """Serve WEB in place of the network, recording each round's batch."""
+ settings.SEED_CRAWL_DOMAIN_DELAY_SECONDS = 0
+ rounds = []
+
+ def fake_crawl_batch(urls, num_threads, delay_seconds, redis):
+ rounds.append(urls)
+ return [{"url": url, "timestamp": 1_700_000_000_000, "content": WEB.get(url)} for url in urls]
+
+ monkeypatch.setattr(seed_crawl, "crawl_batch", fake_crawl_batch)
+ monkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: set())
+ monkeypatch.setattr(index_batches, "filter_blacklisted_documents", lambda documents: documents)
+ return rounds
+
+
+def index_path(tmp_path):
+ path = Path(tmp_path) / "index.tinysearch"
+ with TinyIndex.create(Document, str(path), num_pages=64, page_size=4096):
+ pass
+ return str(path)
+
+
+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)]
+
+
+# ---------------------------------------------------------------------------
+# Crawling
+# ---------------------------------------------------------------------------
+
+
+def test_links_are_followed_within_the_domains_and_no_further(fake_web):
+ rounds = _crawl([SEED], ["tokio.rs"])
+
+ crawled = [document.url for _, documents in rounds for document in documents]
+ assert crawled == [SEED, "https://tokio.rs/tutorial", "https://tokio.rs/tutorial/spawning"]
+
+
+def test_a_page_is_crawled_once_however_often_it_is_linked(fake_web):
+ _crawl([SEED], ["tokio.rs"])
+
+ fetched = [url for batch in fake_web for url in batch]
+ assert len(fetched) == len(set(fetched))
+
+
+def test_each_round_fetches_at_most_one_url_per_domain(fake_web):
+ _crawl(
+ [SEED, "https://tokio.rs/tutorial", "https://rust-lang.github.io/async-book/"],
+ ["tokio.rs", "rust-lang.github.io"],
+ )
+
+ assert fake_web[0] == [SEED, "https://rust-lang.github.io/async-book/"]
+ assert all(len({url.split("/")[2].removeprefix("www.") for url in batch}) == len(batch) for batch in fake_web)
+
+
+def test_the_crawl_stops_at_the_page_limit(fake_web, settings):
+ settings.SEED_CRAWL_MAX_PAGES = 2
+
+ rounds = _crawl([SEED], ["tokio.rs"])
+
+ assert sum(num_crawled for num_crawled, _ in rounds) == 2
+
+
+def test_a_failed_fetch_adds_no_document(fake_web):
+ rounds = _crawl(["https://tokio.rs/missing"], ["tokio.rs"])
+
+ assert rounds == [(1, [])]
+
+
+# ---------------------------------------------------------------------------
+# Starting a crawl
+# ---------------------------------------------------------------------------
+
+
+def test_only_staan_results_missing_from_the_index_are_seeds(redis_cache, monkeypatch):
+ monkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: set())
+ index_pages = [Document("Async book", "https://rust-lang.github.io/async-book/", "")]
+
+ seed_urls, domains = seed_crawl.start_seed_crawl(1, "tokio", index_pages, STAAN_RESULTS)
+
+ assert seed_urls == [SEED]
+ # Every Staan domain is crawlable, including those of results the index already had.
+ assert domains == ["rust-lang.github.io", "tokio.rs"]
+
+
+def test_blacklisted_staan_results_are_neither_seeds_nor_domains(redis_cache, monkeypatch):
+ monkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: {SEED})
+
+ seed_urls, domains = seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS)
+
+ assert SEED not in seed_urls
+ assert domains == ["rust-lang.github.io"]
+
+
+def test_nothing_to_crawl_starts_nothing(redis_cache, monkeypatch):
+ monkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: set())
+
+ assert seed_crawl.start_seed_crawl(1, "tokio", STAAN_RESULTS, STAAN_RESULTS) is None
+ assert seed_crawl.get_seed_crawl(1, "tokio") is None
+
+
+def test_a_running_crawl_is_not_started_again(redis_cache, monkeypatch):
+ monkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: set())
+
+ assert seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS) is not None
+ assert seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS) is None
+ assert seed_crawl.start_seed_crawl(2, "tokio", [], STAAN_RESULTS) is not None
+
+
+# ---------------------------------------------------------------------------
+# Running a crawl
+# ---------------------------------------------------------------------------
+
+
+def _run(user, index_path, seed_urls=(SEED,)):
+ seed_crawl.start_seed_crawl(user.id, "tokio", [], STAAN_RESULTS)
+ seed_crawl.run_seed_crawl(user.id, "tokio", list(seed_urls), ["tokio.rs"], index_path)
+ return seed_crawl.get_seed_crawl(user.id, "tokio")
+
+
+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)
+
+ assert record["status"] == "done"
+ assert record["finished_at"] is not None
+ assert record["pages_crawled"] == 3
+ assert [page["url"] for page in record["pages"]] == [
+ SEED,
+ "https://tokio.rs/tutorial",
+ "https://tokio.rs/tutorial/spawning",
+ ]
+ assert record["pages"][1] == {
+ "url": "https://tokio.rs/tutorial",
+ "title": "Tokio tutorial",
+ "extract": "About Tokio tutorial.",
+ }
+
+
+def test_the_crawled_pages_are_in_the_index(fake_web, redis_cache, user, index_path):
+ _run(user, index_path)
+
+ with TinyIndex(Document, index_path, "r") as index:
+ assert "https://tokio.rs/tutorial/spawning" in {document.url for document in index.retrieve("spawning")}
+
+
+def test_pages_already_in_the_index_are_not_counted_as_new(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, seed_urls=["https://tokio.rs/tutorial"])
+
+ assert record["pages_crawled"] == 3
+ assert [page["url"] for page in record["pages"]] == ["https://tokio.rs/tutorial"]
+
+
+def test_new_pages_are_added_to_the_users_total(fake_web, redis_cache, user, index_path):
+ _run(user, index_path)
+ user.refresh_from_db()
+
+ assert user.seed_search_pages_indexed == 3
+
+
+def test_the_users_stats_report_their_seed_search_total(user):
+ User.objects.filter(id=user.id).update(seed_search_pages_indexed=12)
+ token = str(RefreshToken.for_user(user).access_token)
+
+ response = Client().get("/api/v1/platform/user/stats", HTTP_AUTHORIZATION=f"Bearer {token}")
+
+ assert response.status_code == 200
+ assert response.json()["seed_search_pages_indexed"] == 12
+
+
+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.")
+ second = Document("Spawning tasks", "https://tokio.rs/spawning", "Spawning with tokio.")
+
+ assert index_new_documents([first], index_path) == {first.url}
+ assert index_new_documents([first, second], index_path) == {second.url}