Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Vote on the stored copy, then compare once per URL

Claudea98bd95aa447
diff --git a/mwmbl/crawler/agreement.py b/mwmbl/crawler/agreement.py
index 2ddb871..e880725 100644
--- a/mwmbl/crawler/agreement.py
+++ b/mwmbl/crawler/agreement.py
@@ -10,7 +10,7 @@ from mwmbl.models import CrawlerAgreement, MwmblUser
AGREEMENT_RETENTION = timedelta(days=90)
-def record_agreements(agreements: set[Agreement], user: MwmblUser, crawler_version: str | None):
+def record_agreements(agreements: list[Agreement], user: MwmblUser, crawler_version: str | None):
CrawlerAgreement.objects.bulk_create(
CrawlerAgreement(
url=agreement.url,
diff --git a/mwmbl/indexer/agreement.py b/mwmbl/indexer/agreement.py
index f8d9794..7c01a6c 100644
--- a/mwmbl/indexer/agreement.py
+++ b/mwmbl/indexer/agreement.py
@@ -7,16 +7,27 @@ and a crawler whose copies disagree with many different crawlers is one whose su
are worth a closer look.
"""
+from collections import defaultdict
from typing import Iterable, NamedTuple, Optional
from mwmbl.tinysearchengine.indexer import CURATED_STATES, Document
+class StoredCopy(NamedTuple):
+ """Another crawler's copy of a URL, as a page holds it: what pages are counted on to find
+ the copy most of a URL's pages hold. Its crawl time is left out, since that is the latest
+ of the copies merged on each page and so can differ between pages holding the same copy."""
+
+ url: str
+ author_id: int
+ """The last of its user_ids, which combine_documents keeps for the kept copy's author."""
+ title: str
+ extract: str
+
+
class Agreement(NamedTuple):
url: str
existing_user_id: int
- """The crawler whose text the stored copy holds: the last of its user_ids, which
- combine_documents keeps for the kept copy's author."""
title_similarity: float
extract_similarity: float
last_crawled_delta: Optional[int]
@@ -25,36 +36,39 @@ class Agreement(NamedTuple):
latest of the copies merged into it, not necessarily that of its text."""
-def find_agreements(incoming: Iterable[Document], existing: Iterable[Document]) -> set[Agreement]:
- """Compare each incoming document against another crawler's stored copy of its URL."""
- # A page keeps one document per URL, so there is at most one stored copy to compare. A
- # curated copy or a copy of Staan's has no author of its own, yet takes on the user_ids
- # of the copies it beats, so its last id names one of them.
- authors_by_url = {
- document.url: (document, document.user_ids[-1])
- for document in existing
- if document.user_ids and document.state not in CURATED_STATES and document.source is None
- }
- agreements = set()
+def find_stored_copies(
+ incoming: Iterable[Document], existing: Iterable[Document]
+) -> list[tuple[StoredCopy, Optional[int]]]:
+ """Other crawlers' stored copies of the incoming documents' URLs, with their crawl times."""
+ submitters_by_url = defaultdict(set)
for document in incoming:
- if document.url not in authors_by_url or document.user_ids is None:
+ submitters_by_url[document.url] |= set(document.user_ids or ())
+ stored_copies = []
+ # A page keeps one document per URL, so there is at most one stored copy of each.
+ for document in existing:
+ # A curated copy or a copy of Staan's has no author of its own, yet takes on the
+ # user_ids of the copies it beats, so its last id names one of them.
+ attributed = document.user_ids and document.state not in CURATED_STATES and document.source is None
+ if not attributed or not submitters_by_url[document.url]:
continue
- stored, existing_user_id = authors_by_url[document.url]
+ author_id = document.user_ids[-1]
# The stored text may be this crawler's own, from an earlier submission.
- if existing_user_id in document.user_ids:
+ if author_id in submitters_by_url[document.url]:
continue
- both_crawled = document.last_crawled is not None and stored.last_crawled is not None
- last_crawled_delta = document.last_crawled - stored.last_crawled if both_crawled else None
- agreements.add(
- Agreement(
- url=document.url,
- existing_user_id=existing_user_id,
- title_similarity=trigram_similarity(document.title, stored.title),
- extract_similarity=trigram_similarity(document.extract, stored.extract),
- last_crawled_delta=last_crawled_delta,
- )
- )
- return agreements
+ stored_copy = StoredCopy(document.url, author_id, document.title, document.extract)
+ stored_copies.append((stored_copy, document.last_crawled))
+ return stored_copies
+
+
+def compare(document: Document, stored_copy: StoredCopy, stored_last_crawled: Optional[int]) -> Agreement:
+ both_crawled = document.last_crawled is not None and stored_last_crawled is not None
+ return Agreement(
+ url=document.url,
+ existing_user_id=stored_copy.author_id,
+ title_similarity=trigram_similarity(document.title, stored_copy.title),
+ extract_similarity=trigram_similarity(document.extract, stored_copy.extract),
+ last_crawled_delta=document.last_crawled - stored_last_crawled if both_crawled else None,
+ )
def trigram_similarity(first: str, second: str) -> float:
diff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.py
index 02414a0..ed3666a 100644
--- a/mwmbl/indexer/index_batches.py
+++ b/mwmbl/indexer/index_batches.py
@@ -10,7 +10,7 @@ from urllib.parse import unquote
from mwmbl.crawler.batch import HashedBatch, Item
from mwmbl.crawler.urls import URLStatus
-from mwmbl.indexer.agreement import Agreement, find_agreements
+from mwmbl.indexer.agreement import Agreement, StoredCopy, compare, find_stored_copies
from mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklist
from mwmbl.indexer.index import prepare_url_for_tokenizing, tokenize_document
from mwmbl.tinysearchengine.indexer import (
@@ -74,8 +74,8 @@ def index_batches(batch_data: Collection[HashedBatch], index_path: str) -> Count
class IndexedDocuments(NamedTuple):
end_time: datetime
new_page_doc_counts: Counter
- agreements: set[Agreement]
- """Where an incoming document met another crawler's stored copy of its URL."""
+ agreements: list[Agreement]
+ """One for each submitted URL another crawler's stored copy of was met."""
def index_documents(documents, index_path) -> IndexedDocuments:
@@ -93,32 +93,37 @@ def index_documents(documents, index_path) -> IndexedDocuments:
blacklist_snapshot."""
page_documents = _page_documents(documents, index_path)
new_page_doc_counts = Counter()
- page_agreements = Counter()
+ copy_pages = Counter()
+ copy_last_crawled = {}
for page in _store_pages(index_path, page_documents):
new_page_doc_counts.update(_new_terms(page.stored))
- page_agreements.update(page.agreements)
+ for stored_copy, last_crawled in page.stored_copies:
+ copy_pages[stored_copy] += 1
+ copy_last_crawled[stored_copy] = _latest(copy_last_crawled.get(stored_copy), last_crawled)
+ # A submission can repeat a URL; its last copy is the one compared.
+ submitted_by_url = {document.url: cleaned_document(document) for document in documents}
+ agreements = [
+ compare(submitted_by_url[stored_copy.url], stored_copy, copy_last_crawled[stored_copy])
+ for stored_copy in _most_held_copies(copy_pages)
+ ]
end_time = datetime.now(timezone.utc)
- return IndexedDocuments(end_time, new_page_doc_counts, _one_agreement_per_url(page_agreements))
+ return IndexedDocuments(end_time, new_page_doc_counts, agreements)
-def _one_agreement_per_url(page_agreements: Counter) -> set[Agreement]:
- """The URL is on the page of each of its terms, and the pages need not all hold the same
- stored copy: two crawlers' versions have different terms, and which one a shared term's
- page keeps depends on rank. Keeping the copy most of its pages hold gives one agreement
- per submitted URL, so a URL with divergent copies is not counted several times over.
+def _most_held_copies(copy_pages: Counter) -> list[StoredCopy]:
+ """For each URL, the stored copy most of its pages hold. The URL is on the page of each
+ of its terms, and the pages need not all hold the same copy: two crawlers' versions have
+ different terms, and which one a shared term's page keeps depends on rank. Taking one
+ copy gives one agreement per submitted URL, so a URL with divergent copies is not
+ counted several times over."""
+ copies_by_url = {}
+ for stored_copy, _ in copy_pages.most_common():
+ copies_by_url.setdefault(stored_copy.url, stored_copy)
+ return list(copies_by_url.values())
- The vote leaves out the crawl time gap: a page's stored crawl time is the latest of the
- copies merged on it, so one stored copy can carry different gaps on different pages."""
- copy_votes = Counter()
- agreement_by_copy = {}
- for agreement, count in page_agreements.items():
- copy = agreement._replace(last_crawled_delta=None)
- copy_votes[copy] += count
- agreement_by_copy.setdefault(copy, agreement)
- agreements_by_url = {}
- for copy, _ in copy_votes.most_common():
- agreements_by_url.setdefault(copy.url, agreement_by_copy[copy])
- return set(agreements_by_url.values())
+
+def _latest(first: Optional[int], second: Optional[int]) -> Optional[int]:
+ return max((time for time in (first, second) if time is not None), default=None)
class IndexedURLs(NamedTuple):
@@ -193,8 +198,8 @@ class StoredPage(NamedTuple):
"""What the page now stores."""
existing: list[Document]
"""What it held before."""
- agreements: set[Agreement]
- """Where an incoming document met another crawler's copy of its URL on the page."""
+ stored_copies: list[tuple[StoredCopy, Optional[int]]]
+ """Other crawlers' copies of the incoming documents' URLs it held, with their crawl times."""
def _store_pages(index_path: str, page_documents: dict[int, list[Document]], mark_synced: bool = False):
@@ -207,7 +212,7 @@ def _store_pages(index_path: str, page_documents: dict[int, list[Document]], mar
existing_documents = page.documents
# Before combining, which merges the user_ids and crawl times of the copies
# of a URL into whichever one it keeps, in place.
- agreements = find_agreements(documents, existing_documents)
+ stored_copies = find_stored_copies(documents, existing_documents)
combined_documents = combine_documents(existing_documents, documents, mark_synced, ranker)
num_stored = page.store(combined_documents)
logger.info(
@@ -222,7 +227,7 @@ def _store_pages(index_path: str, page_documents: dict[int, list[Document]], mar
logger.exception("Skipping index page %d", page_index)
continue
- yield StoredPage(combined_documents[:num_stored], existing_documents, agreements)
+ yield StoredPage(combined_documents[:num_stored], existing_documents, stored_copies)
def _document_token_set(doc: Document) -> set[str]:
diff --git a/test/test_crawler_agreement.py b/test/test_crawler_agreement.py
index da2cf17..e090a21 100644
--- a/test/test_crawler_agreement.py
+++ b/test/test_crawler_agreement.py
@@ -9,10 +9,10 @@ from django.test import Client
from django.utils import timezone
from mwmbl.crawler.agreement import AGREEMENT_RETENTION, prune_agreements, record_agreements
-from mwmbl.indexer.agreement import Agreement, find_agreements, trigram_similarity
+from mwmbl.indexer.agreement import Agreement, StoredCopy, compare, find_stored_copies, trigram_similarity
from mwmbl.indexer.blacklist_providers import StaticBlacklistProvider
from mwmbl.indexer.blacklist_snapshot import SnapshotBlacklist
-from mwmbl.indexer.index_batches import _one_agreement_per_url, index_documents
+from mwmbl.indexer.index_batches import _most_held_copies, index_documents
from mwmbl.models import ApiKey, CrawlerAgreement, generate_api_key
from mwmbl.tinysearchengine.indexer import PAGE_SIZE, Document, DocumentSource, DocumentState, TinyIndex
@@ -37,76 +37,78 @@ def test_trigram_similarity_of_an_edit_is_between():
assert 0.5 < similarity < 1.0
-def test_find_agreements_compares_against_another_crawlers_copy():
+def test_find_stored_copies_finds_another_crawlers_copy():
existing = [Document("Title", URL, "An extract", term="t", user_ids=[1, 2], last_crawled=1000)]
- incoming = [Document("Title", URL, "Buy cheap pills", term="t", user_ids=[3], last_crawled=1600)]
+ incoming = [Document("Title", URL, "Buy cheap pills", term="t", user_ids=[3])]
- (agreement,) = find_agreements(incoming, existing)
+ assert find_stored_copies(incoming, existing) == [(StoredCopy(URL, 2, "Title", "An extract"), 1000)]
- assert agreement.url == URL
- assert agreement.existing_user_id == 2
- assert agreement.title_similarity == 1.0
- assert agreement.extract_similarity == 0.0
- assert agreement.last_crawled_delta == 600
-
-def test_find_agreements_skips_the_crawlers_own_copy():
+def test_find_stored_copies_skips_the_crawlers_own_copy():
existing = [Document("Title", URL, "Old extract", term="t", user_ids=[1, 3])]
incoming = [Document("Title", URL, "New extract", term="t", user_ids=[3])]
- assert find_agreements(incoming, existing) == set()
+ assert find_stored_copies(incoming, existing) == []
-def test_find_agreements_compares_against_another_crawlers_text_the_crawler_is_credited_on():
+def test_find_stored_copies_finds_another_crawlers_text_the_crawler_is_credited_on():
"""The crawler is on the stored copy's user_ids, but the text is the last one's."""
existing = [Document("Title", URL, "Old extract", term="t", user_ids=[3, 1])]
incoming = [Document("Title", URL, "New extract", term="t", user_ids=[3])]
- (agreement,) = find_agreements(incoming, existing)
+ ((stored_copy, _),) = find_stored_copies(incoming, existing)
- assert agreement.existing_user_id == 1
+ assert stored_copy.author_id == 1
-def test_find_agreements_skips_a_curated_copy():
+def test_find_stored_copies_skips_a_curated_copy():
"""A curated copy always wins its page and takes on the user_ids of the copies it beat,
so its last id is not its author."""
existing = [Document("Title", URL, "Curated extract", term="t", state=DocumentState.ORGANIC_APPROVED, user_ids=[1])]
incoming = [Document("Title", URL, "Extract", term="t", user_ids=[2])]
- assert find_agreements(incoming, existing) == set()
+ assert find_stored_copies(incoming, existing) == []
-def test_find_agreements_skips_a_copy_of_staans():
+def test_find_stored_copies_skips_a_copy_of_staans():
"""Like a curated copy, it has no author of its own but takes on the user_ids of the
copies it beats."""
existing = [Document("Title", URL, "Staan snippet", term="t", source=DocumentSource.STAAN_INDEXED, user_ids=[1])]
incoming = [Document("Title", URL, "Extract", term="t", user_ids=[2])]
- assert find_agreements(incoming, existing) == set()
+ assert find_stored_copies(incoming, existing) == []
-def test_find_agreements_skips_unattributed_documents():
- """Seed crawls and the main index sync write documents with no user_ids: there is no
- crawler to hold them against."""
+def test_find_stored_copies_skips_unattributed_documents():
+ """There is no crawler to hold an unattributed copy against, nor one to compare it for."""
attributed = Document("Title", URL, "Extract", term="t", user_ids=[1])
unattributed = Document("Title", URL, "Extract", term="t")
- assert find_agreements([attributed], [unattributed]) == set()
- assert find_agreements([unattributed], [attributed]) == set()
+ assert find_stored_copies([attributed], [unattributed]) == []
+ assert find_stored_copies([unattributed], [attributed]) == []
-def test_find_agreements_skips_other_urls():
+def test_find_stored_copies_skips_other_urls():
existing = [Document("Title", "https://example.com/other", "Extract", term="t", user_ids=[1])]
incoming = [Document("Title", URL, "Extract", term="t", user_ids=[2])]
- assert find_agreements(incoming, existing) == set()
+ assert find_stored_copies(incoming, existing) == []
+
+def test_compare():
+ incoming = Document("Title", URL, "Buy cheap pills", user_ids=[3], last_crawled=1600)
-def test_find_agreements_without_crawl_times_has_no_delta():
- existing = [Document("Title", URL, "Extract", term="t", user_ids=[1])]
- incoming = [Document("Title", URL, "Extract", term="t", user_ids=[2], last_crawled=1000)]
+ agreement = compare(incoming, StoredCopy(URL, 2, "Title", "An extract"), stored_last_crawled=1000)
+
+ assert agreement == Agreement(
+ url=URL, existing_user_id=2, title_similarity=1.0, extract_similarity=0.0, last_crawled_delta=600
+ )
- (agreement,) = find_agreements(incoming, existing)
+
+def test_compare_without_crawl_times_has_no_delta():
+ incoming = Document("Title", URL, "Extract", user_ids=[2], last_crawled=1000)
+
+ agreement = compare(incoming, StoredCopy(URL, 1, "Title", "Extract"), stored_last_crawled=None)
assert agreement.last_crawled_delta is None
@@ -135,7 +137,7 @@ def test_index_documents_reports_one_agreement_per_url(index_path, no_blacklist)
indexed = index_documents([Document("Python tutorial", URL, "Learn python today", user_ids=[2])], index_path)
- assert indexed.agreements == {
+ assert indexed.agreements == [
Agreement(
url=URL,
existing_user_id=1,
@@ -143,7 +145,7 @@ def test_index_documents_reports_one_agreement_per_url(index_path, no_blacklist)
extract_similarity=1.0,
last_crawled_delta=None,
)
- }
+ ]
@pytest.mark.parametrize(
@@ -183,22 +185,36 @@ def test_index_documents_reports_one_agreement_when_stored_copies_differ(index_p
assert agreement.extract_similarity == 1.0
-def test_one_agreement_per_url_votes_on_the_copy_not_the_crawl_time_gap():
- """A page's stored crawl time is the latest of the copies merged on it, so one stored
- copy can carry a different gap on each page; it still gets all of its pages' votes."""
- held_copy = Agreement(URL, existing_user_id=1, title_similarity=1.0, extract_similarity=0.2, last_crawled_delta=10)
- other_copy = Agreement(URL, existing_user_id=2, title_similarity=1.0, extract_similarity=0.9, last_crawled_delta=10)
- page_agreements = Counter({held_copy: 2, held_copy._replace(last_crawled_delta=20): 2, other_copy: 3})
+def test_most_held_copies_takes_the_copy_most_pages_hold_for_each_url():
+ held_copy = StoredCopy(URL, 1, "Title", "Held extract")
+ other_copy = StoredCopy(URL, 2, "Title", "Other extract")
+ other_url_copy = StoredCopy("https://example.com/other", 3, "Title", "Extract")
- (agreement,) = _one_agreement_per_url(page_agreements)
+ copies = _most_held_copies(Counter({held_copy: 3, other_copy: 2, other_url_copy: 1}))
- assert agreement.existing_user_id == 1
+ assert copies == [held_copy, other_url_copy]
+
+
+def test_index_documents_compares_a_repeated_url_once_against_its_last_copy(index_path, no_blacklist):
+ """However the copies of a URL a submission repeats score, they make one agreement."""
+ index_documents([Document("Python tutorial", URL, "Learn python today", user_ids=[1])], index_path)
+
+ indexed = index_documents(
+ [
+ Document("Python tutorial", URL, "Something else entirely", user_ids=[2]),
+ Document("Python tutorial", URL, "Learn python today", user_ids=[2]),
+ ],
+ index_path,
+ )
+
+ (agreement,) = indexed.agreements
+ assert agreement.extract_similarity == 1.0
def test_index_documents_reports_no_agreement_for_a_new_url(index_path, no_blacklist):
indexed = index_documents([Document("Python tutorial", URL, "Learn python today", user_ids=[1])], index_path)
- assert indexed.agreements == set()
+ assert indexed.agreements == []
@pytest.fixture
@@ -218,7 +234,7 @@ def _agreement(url=URL):
@pytest.mark.django_db
def test_record_agreements(user):
- record_agreements({_agreement()}, user, "1.2.0")
+ record_agreements([_agreement()], user, "1.2.0")
stored = CrawlerAgreement.objects.get()
assert stored.url == URL
@@ -232,7 +248,7 @@ def test_record_agreements(user):
@pytest.mark.django_db
def test_prune_agreements_deletes_only_expired_rows(user):
- record_agreements({_agreement("https://example.com/old"), _agreement("https://example.com/new")}, user, None)
+ record_agreements([_agreement("https://example.com/old"), _agreement("https://example.com/new")], user, None)
expired = timezone.now() - AGREEMENT_RETENTION - timedelta(days=1)
CrawlerAgreement.objects.filter(url="https://example.com/old").update(created_at=expired)
diff --git a/test/test_search_api_key.py b/test/test_search_api_key.py
index 05e5d83..c5ff070 100644
--- a/test/test_search_api_key.py
+++ b/test/test_search_api_key.py
@@ -494,7 +494,7 @@ def test_search_keyed_cap_shrinks_with_combined_search_spend(api_client, search_
def _capturing_index(captured):
def index_documents(documents, index_path):
captured.extend(documents)
- return IndexedDocuments(datetime.now(stdlib_timezone.utc), Counter(), set())
+ return IndexedDocuments(datetime.now(stdlib_timezone.utc), Counter(), [])
return index_documents