Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Count seed crawl pages from the index write, and skip error pages

Claude4f3881964133
diff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.py
index 245c3e9..e02c475 100644
--- a/mwmbl/indexer/index_batches.py
+++ b/mwmbl/indexer/index_batches.py
@@ -5,7 +5,7 @@ Write crawled documents into the index.
from collections import Counter, defaultdict
from datetime import datetime, timezone
from logging import getLogger
-from typing import Collection, Iterable, Optional
+from typing import Collection, Iterable, NamedTuple, Optional
from urllib.parse import unquote
from mwmbl.crawler.batch import HashedBatch, Item
@@ -82,27 +82,30 @@ def index_documents(documents, index_path):
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.
+class IndexedURLs(NamedTuple):
+ stored: set[str]
+ """URLs of the documents written, now on at least one of their pages."""
+ new: set[str]
+ """Of those, the URLs none of their pages held beforehand."""
+
+
+def index_new_documents(documents, index_path) -> IndexedURLs:
+ """index_documents, returning which URLs it stored and which of those the index lacked.
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.
+ Both are read under the page locks the write takes, so a document the store trimmed, or
+ one the blacklist dropped, is in neither.
"""
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
+ stored_urls = set()
+ held_urls = set()
+ for stored_documents, existing_documents in _store_pages(index_path, page_documents):
+ stored_urls |= {document.url for document in stored_documents}
+ held_urls |= {document.url for document in existing_documents}
+ incoming_urls = {document.url for documents in page_documents.values() for document in documents}
+ written_urls = stored_urls & incoming_urls
+ return IndexedURLs(stored=written_urls, new=written_urls - held_urls)
def _page_documents(documents, index_path) -> dict[int, list[Document]]:
@@ -137,16 +140,27 @@ def filter_blacklisted_documents(documents: list[Document]) -> list[Document]:
def index_pages(index_path: str, page_documents: dict[int, list[Document]], mark_synced: bool = False) -> Counter:
term_new_doc_counts = Counter()
+ for stored_documents, _ in _store_pages(index_path, page_documents, mark_synced):
+ term_new_doc_counts.update(
+ document.term for document in stored_documents if document.state != DocumentState.SYNCED_WITH_MAIN_INDEX
+ )
+ return term_new_doc_counts
+
+
+def _store_pages(index_path: str, page_documents: dict[int, list[Document]], mark_synced: bool = False):
+ """Merge the documents into their pages, yielding for each page written what it now
+ stores and what it held before."""
with TinyIndex(Document, index_path, "w") as indexer:
ranker = HeuristicRanker(indexer, None, score_threshold=float("-inf"))
for page_index, documents in page_documents.items():
try:
with indexer.page(page_index) as page:
- combined_documents = combine_documents(page.documents, documents, mark_synced, ranker)
+ existing_documents = page.documents
+ combined_documents = combine_documents(existing_documents, documents, mark_synced, ranker)
num_stored = page.store(combined_documents)
logger.info(
f"Storing {num_stored} of {len(combined_documents)} documents for "
- f"page {page_index}, originally {len(page.documents)}"
+ f"page {page_index}, originally {len(existing_documents)}"
)
except PageError:
# One page we cannot safely write costs the documents bound for it, not the
@@ -156,12 +170,7 @@ def index_pages(index_path: str, page_documents: dict[int, list[Document]], mark
logger.exception("Skipping index page %d", page_index)
continue
- term_new_doc_counts.update(
- document.term
- for document in combined_documents[:num_stored]
- if document.state != DocumentState.SYNCED_WITH_MAIN_INDEX
- )
- return term_new_doc_counts
+ yield combined_documents[:num_stored], existing_documents
def _document_token_set(doc: Document) -> set[str]:
@@ -171,13 +180,18 @@ def _document_token_set(doc: Document) -> set[str]:
def index_results_against_query(documents: list[Document], query: str, index_path: str) -> int:
+ """index_new_results_against_query, returning how many URLs it added."""
+ return len(index_new_results_against_query(documents, query, index_path))
+
+
+def index_new_results_against_query(documents: list[Document], query: str, index_path: str) -> set[str]:
"""Index each document against the query unigrams/bigrams it matches.
A query term matches a document when all of the term's words are present in
the document's token set (unigram: the token; bigram: both words, in any
order). Matching docs are stored against that term via index_pages(), which
- applies the normal combine/prioritise path. Returns the number of distinct
- URLs newly added to the index.
+ applies the normal combine/prioritise path. Returns the distinct URLs newly
+ added to the index.
The count is computed in the read pass, before combine/store, so a candidate
later dropped by URL/title dedup or by the full-page trim is still counted;
@@ -185,7 +199,7 @@ def index_results_against_query(documents: list[Document], query: str, index_pat
"""
tokens = tokenize(query)
if not tokens or not documents:
- return 0
+ return set()
# term string -> the set of words that must all be present to match.
query_terms: dict[str, frozenset[str]] = {t: frozenset((t,)) for t in tokens}
@@ -230,7 +244,7 @@ def index_results_against_query(documents: list[Document], query: str, index_pat
if page_documents:
index_pages(index_path, page_documents) # reuse the existing write path
- return len(new_urls)
+ return new_urls
def combine_documents(existing_documents, documents, mark_synced, ranker):
diff --git a/mwmbl/indexer/seed_crawl.py b/mwmbl/indexer/seed_crawl.py
index f0ec2e7..c665254 100644
--- a/mwmbl/indexer/seed_crawl.py
+++ b/mwmbl/indexer/seed_crawl.py
@@ -26,8 +26,10 @@ import json
import time
from collections import Counter, deque
from datetime import datetime, timezone
+from http import HTTPStatus
from logging import getLogger
from pathlib import Path
+from urllib.parse import urlsplit
from django.conf import settings
from django.db import close_old_connections
@@ -75,9 +77,15 @@ 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]) -> bool:
+def start_seed_crawl(
+ user_id: int, query: str, index_pages: list[Document], staan_results: list[Document], new_staan_urls: set[str]
+) -> bool:
"""Queue a seed crawl of the Staan results the index lacked, returning whether it did.
+ The seeds are the results the query did not retrieve. Of those, only the ones in
+ new_staan_urls - which Combined Search's own write of Staan's results found missing from
+ the index - count as pages the crawl added; the rest the index already held.
+
Nothing is queued 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.
"""
@@ -102,7 +110,14 @@ def start_seed_crawl(user_id: int, query: str, index_pages: list[Document], staa
record_key = _record_key(user_id, query)
domains = sorted({bare_host(document.url) for document in allowed})
- job = {"user_id": user_id, "query": query, "seed_urls": seed_urls, "domains": domains}
+ new_seed_urls = [url for url in seed_urls if url in new_staan_urls]
+ job = {
+ "user_id": user_id,
+ "query": query,
+ "seed_urls": seed_urls,
+ "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
# already includes them.
pipeline = redis.pipeline()
@@ -132,16 +147,18 @@ def run_next_seed_crawl(index_path: str) -> bool:
# Postgres has long since closed.
close_old_connections()
job = json.loads(popped[1])
- run_seed_crawl(job["user_id"], job["query"], job["seed_urls"], job["domains"], index_path)
+ run_seed_crawl(job["user_id"], job["query"], job["seed_urls"], job["new_seed_urls"], job["domains"], index_path)
return True
-def run_seed_crawl(user_id: int, query: str, seed_urls: list[str], domains: list[str], index_path: str) -> None:
+def run_seed_crawl(
+ user_id: int, query: str, seed_urls: list[str], new_seed_urls: list[str], domains: list[str], index_path: str
+) -> None:
redis = get_redis_connection("default")
record_key = _record_key(user_id, query)
redis.hset(record_key, "status", STATUS_CRAWLING)
try:
- _crawl_and_record(user_id, query, seed_urls, domains, index_path, redis)
+ _crawl_and_record(user_id, query, seed_urls, set(new_seed_urls), domains, index_path, redis)
status = STATUS_DONE
except Exception:
# Recorded rather than retried: a retry would start again from the seeds, fetching
@@ -157,16 +174,19 @@ def run_seed_crawl(user_id: int, query: str, seed_urls: list[str], domains: list
pipeline.execute()
-def _crawl_and_record(user_id: int, query: str, seed_urls: list[str], domains: list[str], index_path: str, redis):
+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
+):
record_key = _record_key(user_id, query)
pages_key = _pages_key(user_id, query)
counted_urls_key = _counted_urls_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)
+ 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.
+ new_urls = indexed.new | (indexed.stored & new_seed_urls)
candidates = [document for document in documents if document.url in new_urls]
# A page is counted once per query, however many crawls of it find it new.
@@ -213,6 +233,13 @@ def crawl_within_domains(seed_urls: list[str], domains: set[str], redis):
for url in seed_urls:
enqueue(url)
+ def follow(link: str) -> None:
+ # Query strings are where faceted search, sorting and calendars multiply one page
+ # into thousands, which would spend a domain's budget on near-duplicates.
+ if urlsplit(link).query:
+ return
+ enqueue(link)
+
# The per-domain cap already bounds the rounds; this bounds a round's slow fetches.
deadline = time.monotonic() + settings.SEED_CRAWL_MAX_SECONDS
last_round_started = None
@@ -231,7 +258,8 @@ def crawl_within_domains(seed_urls: list[str], domains: set[str], redis):
documents = []
for result in results:
content = result["content"]
- if content is None:
+ # An error page is not content, and its links are no lead to any.
+ if content is None or result["status"] != HTTPStatus.OK:
continue
if content["title"]:
documents.append(
@@ -243,7 +271,7 @@ def crawl_within_domains(seed_urls: list[str], domains: set[str], redis):
)
)
for link in content["links"] + content["extra_links"]:
- enqueue(link)
+ follow(link)
yield len(batch), documents
diff --git a/mwmbl/tinysearchengine/combined_search.py b/mwmbl/tinysearchengine/combined_search.py
index b5772ec..ed4e620 100644
--- a/mwmbl/tinysearchengine/combined_search.py
+++ b/mwmbl/tinysearchengine/combined_search.py
@@ -42,7 +42,7 @@ from pydantic import Field
from mwmbl import pricing
from mwmbl.format import format_result_v2
-from mwmbl.indexer.index_batches import index_results_against_query
+from mwmbl.indexer.index_batches import index_new_results_against_query
from mwmbl.indexer.seed_crawl import get_seed_crawl, get_seed_crawl_summary, start_seed_crawl
from mwmbl.membership import combined_search_monthly_limit
from mwmbl.models import Membership, UserBilling
@@ -155,10 +155,10 @@ OPENAPI_EXTRA = {
}
-def index_staan_results(query: str, staan_results: list[Document]) -> int:
- """Index Staan's results against the query, returning the number of new pages added.
+def index_staan_results(query: str, staan_results: list[Document]) -> set[str]:
+ """Index Staan's results against the query, returning the URLs of the new pages added.
- Blacklisted domains are dropped first: index_results_against_query bypasses the
+ Blacklisted domains are dropped first: index_new_results_against_query bypasses the
blacklist check in index_documents, and the ranker's read-path filter only stops these
pages being shown, not being written.
@@ -168,12 +168,12 @@ def index_staan_results(query: str, staan_results: list[Document]) -> int:
blacklisted_urls = find_blacklisted_urls(staan_results)
allowed = [document for document in staan_results if document.url not in blacklisted_urls]
if not allowed:
- return 0
+ return set()
try:
- return index_results_against_query(allowed, query, str(index_path))
+ return index_new_results_against_query(allowed, query, str(index_path))
except Exception:
logger.exception("combined-search failed to index Staan results")
- return 0
+ return set()
def _keyed_monthly_limit(user) -> int:
@@ -246,12 +246,14 @@ def init_router(ranker) -> None:
asyncio.to_thread(get_staan_results, q),
)
# Ranking only reads what was already retrieved, so the index write can overlap it.
- results, pages_indexed = await asyncio.gather(
+ results, new_staan_urls = await asyncio.gather(
asyncio.to_thread(ranker.search_retrieved, retrieval, staan_results),
asyncio.to_thread(index_staan_results, q, staan_results),
)
- crawl_scheduled = crawl and await sync_to_async(start_seed_crawl)(user.id, q, retrieval.pages, staan_results)
+ crawl_scheduled = crawl and await sync_to_async(start_seed_crawl)(
+ user.id, q, retrieval.pages, staan_results, new_staan_urls
+ )
formatted = [format_result_v2(result, i + 1, q) for i, result in enumerate(results)]
return CombinedSearchResponse(
@@ -260,7 +262,7 @@ def init_router(ranker) -> None:
results=formatted,
monthly_usage=monthly_usage,
monthly_limit=monthly_limit,
- pages_indexed=pages_indexed,
+ pages_indexed=len(new_staan_urls),
crawl_scheduled=crawl_scheduled,
)
diff --git a/test/test_combined_search.py b/test/test_combined_search.py
index acb6ab0..9d985e7 100644
--- a/test/test_combined_search.py
+++ b/test/test_combined_search.py
@@ -106,7 +106,7 @@ def stub_sources(monkeypatch):
"""
calls = {}
- def configure(staan=(STAAN_RESULT,), index=(INDEX_RESULT,), pages_indexed=1):
+ def configure(staan=(STAAN_RESULT,), index=(INDEX_RESULT,), new_urls=(STAAN_RESULT.url,)):
def fake_staan(query, *args, **kwargs):
calls["staan_query"] = query
if isinstance(staan, Exception):
@@ -124,12 +124,12 @@ def stub_sources(monkeypatch):
def fake_index(documents, query, path):
calls["indexed"] = [document.url for document in documents]
calls["indexed_query"] = query
- if isinstance(pages_indexed, Exception):
- raise pages_indexed
- return pages_indexed
+ if isinstance(new_urls, Exception):
+ raise new_urls
+ return set(new_urls)
monkeypatch.setattr(combined_search, "get_staan_results", fake_staan)
- monkeypatch.setattr(combined_search, "index_results_against_query", fake_index)
+ monkeypatch.setattr(combined_search, "index_new_results_against_query", fake_index)
monkeypatch.setattr(combined_search, "find_blacklisted_urls", lambda documents: set())
# The router closed over the ranker at registration time, so the ranker instance
# itself is what has to be patched, not the name in search_setup.
@@ -444,7 +444,7 @@ def test_an_empty_pool_is_an_empty_response_not_an_error(client, access_token, f
@pytest.mark.django_db
def test_staan_results_are_indexed_against_the_query(client, access_token, fresh_quota, stub_sources):
- calls = stub_sources(pages_indexed=3)
+ calls = stub_sources(new_urls=("https://a.example/", "https://b.example/", "https://c.example/"))
body = _get(client, access_token, query="rust").json()
@@ -455,7 +455,7 @@ def test_staan_results_are_indexed_against_the_query(client, access_token, fresh
@pytest.mark.django_db
def test_blacklisted_staan_results_are_not_indexed(client, access_token, fresh_quota, stub_sources, monkeypatch):
- """index_results_against_query bypasses index_documents' blacklist check."""
+ """index_new_results_against_query bypasses index_documents' blacklist check."""
bad = Document("Bad", "https://badsite.test/x", "bad", 5.0, source=DocumentSource.STAAN)
calls = stub_sources(staan=(bad, STAAN_RESULT))
monkeypatch.setattr(
@@ -481,7 +481,7 @@ def test_nothing_from_staan_indexes_nothing(client, access_token, fresh_quota, s
@pytest.mark.django_db
def test_a_failed_index_write_still_serves_the_results(client, access_token, fresh_quota, stub_sources):
- stub_sources(pages_indexed=OSError("disk full"))
+ stub_sources(new_urls=OSError("disk full"))
body = _get(client, access_token).json()
@@ -496,8 +496,8 @@ def test_index_staan_results_writes_new_pages_once(tmp_path, monkeypatch):
monkeypatch.setattr(combined_search, "index_path", index_path)
monkeypatch.setattr(combined_search, "find_blacklisted_urls", lambda documents: set())
- assert combined_search.index_staan_results("tokio", [STAAN_RESULT]) == 1
- assert combined_search.index_staan_results("tokio", [STAAN_RESULT]) == 0
+ assert combined_search.index_staan_results("tokio", [STAAN_RESULT]) == {STAAN_RESULT.url}
+ assert combined_search.index_staan_results("tokio", [STAAN_RESULT]) == set()
with TinyIndex(Document, str(index_path), "r") as index:
assert [document.url for document in index.retrieve("tokio")] == [STAAN_RESULT.url]
@@ -530,7 +530,13 @@ def test_crawl_schedules_a_seed_crawl_of_what_the_index_lacked(
assert body["crawl_scheduled"] is True
job = json.loads(redis_cache.rpop(seed_crawl.QUEUE_KEY))
- assert job == {"user_id": user.id, "query": "tokio", "seed_urls": [STAAN_RESULT.url], "domains": ["tokio.rs"]}
+ assert job == {
+ "user_id": user.id,
+ "query": "tokio",
+ "seed_urls": [STAAN_RESULT.url],
+ "new_seed_urls": [STAAN_RESULT.url],
+ "domains": ["tokio.rs"],
+ }
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 c662318..ec34aa4 100644
--- a/test/test_seed_crawl.py
+++ b/test/test_seed_crawl.py
@@ -30,11 +30,18 @@ def _page(title, 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/"]),
+ SEED: _page(
+ "Tokio runtime",
+ ["https://tokio.rs/tutorial", "https://elsewhere.example.com/", "https://tokio.rs/search?q=spawn"],
+ ),
"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"),
+ "https://tokio.rs/search?q=spawn": _page("Search results"),
+ "https://tokio.rs/gone": _page("404 Not Found", ["https://tokio.rs/tutorial"]),
}
+# Pages that answer with an error status rather than 200.
+STATUSES = {"https://tokio.rs/gone": 404}
@pytest.fixture
@@ -45,7 +52,10 @@ def fake_web(monkeypatch, settings):
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]
+ return [
+ {"url": url, "status": STATUSES.get(url, 200), "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())
@@ -122,6 +132,18 @@ def test_a_failed_fetch_adds_no_document(fake_web):
assert rounds == [(1, [])]
+def test_an_error_page_is_neither_indexed_nor_followed(fake_web):
+ rounds = _crawl(["https://tokio.rs/gone"], ["tokio.rs"])
+
+ assert rounds == [(1, [])]
+
+
+def test_links_with_a_query_string_are_not_followed(fake_web):
+ _crawl([SEED], ["tokio.rs"])
+
+ assert "https://tokio.rs/search?q=spawn" not in [url for batch in fake_web for url in batch]
+
+
# ---------------------------------------------------------------------------
# Starting a crawl
# ---------------------------------------------------------------------------
@@ -135,10 +157,12 @@ def test_only_staan_results_missing_from_the_index_are_seeds(redis_cache, monkey
monkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: set())
index_pages = [Document("Async book", "https://rust-lang.github.io/async-book/", "")]
- assert seed_crawl.start_seed_crawl(1, "tokio", index_pages, STAAN_RESULTS) is True
+ assert seed_crawl.start_seed_crawl(1, "tokio", index_pages, STAAN_RESULTS, set()) is True
[job] = _queued_jobs(redis_cache)
assert job["seed_urls"] == [SEED]
+ # 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"]
@@ -146,7 +170,7 @@ def test_only_staan_results_missing_from_the_index_are_seeds(redis_cache, monkey
def test_blacklisted_staan_results_are_neither_seeds_nor_domains(redis_cache, monkeypatch):
monkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: {SEED})
- seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS)
+ seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS, set())
[job] = _queued_jobs(redis_cache)
assert SEED not in job["seed_urls"]
@@ -156,7 +180,7 @@ def test_blacklisted_staan_results_are_neither_seeds_nor_domains(redis_cache, mo
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 False
+ assert seed_crawl.start_seed_crawl(1, "tokio", STAAN_RESULTS, STAAN_RESULTS, set()) is False
assert seed_crawl.get_seed_crawl(1, "tokio") is None
assert _queued_jobs(redis_cache) == []
@@ -164,10 +188,10 @@ def test_nothing_to_crawl_starts_nothing(redis_cache, monkeypatch):
def test_a_user_has_one_crawl_at_a_time(redis_cache, monkeypatch):
monkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: set())
- assert seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS) is True
- assert seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS) is False
- assert seed_crawl.start_seed_crawl(1, "rust", [], STAAN_RESULTS) is False
- assert seed_crawl.start_seed_crawl(2, "tokio", [], STAAN_RESULTS) is True
+ assert seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS, set()) is True
+ assert seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS, set()) is False
+ assert seed_crawl.start_seed_crawl(1, "rust", [], STAAN_RESULTS, set()) is False
+ assert seed_crawl.start_seed_crawl(2, "tokio", [], STAAN_RESULTS, set()) is True
assert len(_queued_jobs(redis_cache)) == 2
@@ -175,8 +199,8 @@ def test_nothing_is_queued_once_the_queue_is_full(redis_cache, monkeypatch, sett
monkeypatch.setattr(seed_crawl, "find_blacklisted_urls", lambda documents: set())
settings.SEED_CRAWL_MAX_QUEUED = 1
- assert seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS) is True
- assert seed_crawl.start_seed_crawl(2, "tokio", [], STAAN_RESULTS) is False
+ assert seed_crawl.start_seed_crawl(1, "tokio", [], STAAN_RESULTS, set()) is True
+ assert seed_crawl.start_seed_crawl(2, "tokio", [], STAAN_RESULTS, set()) is False
assert seed_crawl.get_seed_crawl(2, "tokio") is None
@@ -185,11 +209,11 @@ def test_nothing_is_queued_once_the_queue_is_full(redis_cache, monkeypatch, sett
# ---------------------------------------------------------------------------
-def _run(user, index_path, seed_urls=(SEED,)):
- seed_crawl.start_seed_crawl(user.id, "tokio", [], STAAN_RESULTS)
+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), ["tokio.rs"], index_path)
+ seed_crawl.run_seed_crawl(user.id, "tokio", list(seed_urls), list(new_seed_urls), ["tokio.rs"], index_path)
return seed_crawl.get_seed_crawl(user.id, "tokio")
@@ -215,13 +239,13 @@ def test_the_record_lists_the_new_pages_once_the_crawl_is_done(fake_web, redis_c
@pytest.mark.django_db
def test_the_worker_runs_a_queued_crawl(fake_web, redis_cache, user, index_path, worker):
- seed_crawl.start_seed_crawl(user.id, "tokio", [], STAAN_RESULTS)
+ seed_crawl.start_seed_crawl(user.id, "tokio", [], STAAN_RESULTS, set())
assert worker(index_path) is True
assert seed_crawl.get_seed_crawl(user.id, "tokio")["status"] == "done"
# The user can start another crawl once theirs has finished.
- assert seed_crawl.start_seed_crawl(user.id, "rust", [], STAAN_RESULTS) is True
+ assert seed_crawl.start_seed_crawl(user.id, "rust", [], STAAN_RESULTS, set()) is True
@pytest.mark.django_db
@@ -230,7 +254,7 @@ def test_a_failed_crawl_is_recorded_and_not_retried(fake_web, redis_cache, user,
raise ConnectionError("Redis went away")
monkeypatch.setattr(seed_crawl, "crawl_batch", failing_crawl_batch)
- seed_crawl.start_seed_crawl(user.id, "tokio", [], STAAN_RESULTS)
+ seed_crawl.start_seed_crawl(user.id, "tokio", [], STAAN_RESULTS, set())
worker(index_path)
@@ -238,7 +262,7 @@ def test_a_failed_crawl_is_recorded_and_not_retried(fake_web, redis_cache, user,
assert record["status"] == "failed"
assert record["finished_at"] is not None
assert _queued_jobs(redis_cache) == []
- assert seed_crawl.start_seed_crawl(user.id, "tokio", [], STAAN_RESULTS) is True
+ assert seed_crawl.start_seed_crawl(user.id, "tokio", [], STAAN_RESULTS, set()) is True
@pytest.mark.django_db
@@ -270,7 +294,41 @@ def test_pages_already_in_the_index_are_not_counted_as_new(fake_web, redis_cache
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"]
+ assert record["pages"] == []
+
+
+def _index_staan_snippet_of_the_seed(index_path):
+ """What Combined Search writes before the crawl starts."""
+ index_batches.index_documents([Document("Tokio", SEED, "An async runtime.")], index_path)
+
+
+def test_a_seed_combined_search_found_new_is_counted_once_crawled(fake_web, redis_cache, user, index_path):
+ _index_staan_snippet_of_the_seed(index_path)
+
+ record = _run(user, index_path, new_seed_urls=[SEED])
+
+ assert SEED in [page["url"] for page in record["pages"]]
+
+
+def test_a_seed_the_index_already_held_is_not_counted(fake_web, redis_cache, user, index_path):
+ _index_staan_snippet_of_the_seed(index_path)
+
+ record = _run(user, index_path, new_seed_urls=[])
+
+ assert SEED not in [page["url"] for page in record["pages"]]
+
+
+def test_a_seed_the_blacklist_drops_is_not_counted(fake_web, redis_cache, user, index_path, monkeypatch):
+ monkeypatch.setattr(
+ index_batches, "filter_blacklisted_documents", lambda documents: [d for d in documents if d.url != SEED]
+ )
+
+ record = _run(user, index_path, new_seed_urls=[SEED])
+
+ assert SEED not in [page["url"] for page in record["pages"]]
@pytest.mark.django_db
@@ -307,5 +365,15 @@ def test_index_new_documents_returns_only_urls_the_index_lacked(index_path, monk
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}
+ assert index_new_documents([first], index_path).new == {first.url}
+ indexed = index_new_documents([first, second], index_path)
+ assert indexed.stored == {first.url, second.url}
+ assert indexed.new == {second.url}
+
+
+def test_index_new_documents_counts_nothing_the_blacklist_drops(index_path, monkeypatch):
+ monkeypatch.setattr(index_batches, "filter_blacklisted_documents", lambda documents: [])
+
+ indexed = index_new_documents([Document("Tokio", SEED, "Tokio.")], index_path)
+
+ assert indexed == (set(), set())