Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Compare crawlers' copies before combining merges them

Claude6d41940c4e1d
diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.py
index 6096694..a627a4c 100644
--- a/mwmbl/crawler/app.py
+++ b/mwmbl/crawler/app.py
@@ -268,11 +268,13 @@ def _register_routes(r: Router | NinjaAPI):
index_path = f"{settings.DATA_PATH}/{settings.INDEX_NAME}"
indexed = index_documents(documents, index_path)
- record_agreements(indexed.agreements, api_key.user, results.crawler_version)
# Without api_key: the bucket is world-readable (get_batch_from_id fetches from it
# with a plain unauthenticated GET), so uploading the object as submitted would
# publish the plaintext key of any client still using the deprecated body field.
filename = upload_object(results.model_copy(update={"api_key": None}), now, api_key.user.username, "results")
+ # After the upload: the agreements are analytics, and failing to store them should not
+ # cost the batch.
+ record_agreements(indexed.agreements, api_key.user, results.crawler_version)
# Update stats for the user
stats_manager.record_results(results, api_key.user)
diff --git a/mwmbl/indexer/agreement.py b/mwmbl/indexer/agreement.py
index 503a3a3..fcb17c8 100644
--- a/mwmbl/indexer/agreement.py
+++ b/mwmbl/indexer/agreement.py
@@ -14,8 +14,6 @@ from mwmbl.tinysearchengine.indexer import Document
class Agreement(NamedTuple):
url: str
- user_id: int
- """The crawler submitting the incoming copy."""
existing_user_ids: tuple[int, ...]
"""The crawlers the stored copy is attributed to. Up to two of them, and the text is
whichever of their versions ranked higher, so it cannot be pinned on just one."""
@@ -23,7 +21,8 @@ class Agreement(NamedTuple):
extract_similarity: float
last_crawled_delta: Optional[int]
"""Seconds from the stored copy's crawl to the incoming one's: pages change, so a large
- gap explains a low similarity that a small one does not."""
+ gap explains a low similarity that a small one does not. The stored crawl time is the
+ latest of the copies merged into it, not necessarily that of its text."""
def find_agreements(incoming: Iterable[Document], existing: Iterable[Document]) -> set[Agreement]:
@@ -38,13 +37,11 @@ def find_agreements(incoming: Iterable[Document], existing: Iterable[Document])
# The stored copy may be this crawler's own, from an earlier submission.
if set(document.user_ids) & set(stored.user_ids):
continue
- (user_id,) = document.user_ids
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,
- user_id=user_id,
existing_user_ids=tuple(stored.user_ids),
title_similarity=trigram_similarity(document.title, stored.title),
extract_similarity=trigram_similarity(document.extract, stored.extract),
diff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.py
index 96a32fe..bef5e22 100644
--- a/mwmbl/indexer/index_batches.py
+++ b/mwmbl/indexer/index_batches.py
@@ -86,14 +86,23 @@ def index_documents(documents, index_path) -> IndexedDocuments:
blacklist_snapshot."""
page_documents = _page_documents(documents, index_path)
new_page_doc_counts = Counter()
- agreements = set()
- for page_index, stored_documents, existing_documents in _store_pages(index_path, page_documents):
- new_page_doc_counts.update(_new_terms(stored_documents))
- # A set, because the URL is on the page of each of its terms and most of those pages
- # hold the same stored copy.
- agreements |= find_agreements(page_documents[page_index], existing_documents)
+ page_agreements = Counter()
+ for page in _store_pages(index_path, page_documents):
+ new_page_doc_counts.update(_new_terms(page.stored))
+ page_agreements.update(page.agreements)
end_time = datetime.now(timezone.utc)
- return IndexedDocuments(end_time, new_page_doc_counts, agreements)
+ return IndexedDocuments(end_time, new_page_doc_counts, _one_agreement_per_url(page_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."""
+ agreements_by_url = {}
+ for agreement, _ in page_agreements.most_common():
+ agreements_by_url.setdefault(agreement.url, agreement)
+ return set(agreements_by_url.values())
class IndexedURLs(NamedTuple):
@@ -114,9 +123,9 @@ def index_new_documents(documents, index_path) -> IndexedURLs:
page_documents = _page_documents(documents, index_path)
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}
+ for page in _store_pages(index_path, page_documents):
+ stored_urls |= {document.url for document in page.stored}
+ held_urls |= {document.url for document in page.existing}
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)
@@ -154,8 +163,8 @@ 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(_new_terms(stored_documents))
+ for page in _store_pages(index_path, page_documents, mark_synced):
+ term_new_doc_counts.update(_new_terms(page.stored))
return term_new_doc_counts
@@ -163,15 +172,26 @@ def _new_terms(stored_documents: list[Document]) -> Iterable[str | None]:
return (document.term for document in stored_documents if document.state != DocumentState.SYNCED_WITH_MAIN_INDEX)
+class StoredPage(NamedTuple):
+ stored: list[Document]
+ """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."""
+
+
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 its index, what
- it now stores and what it held before."""
+ """Merge the documents into their pages, yielding a StoredPage for each page written."""
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:
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)
combined_documents = combine_documents(existing_documents, documents, mark_synced, ranker)
num_stored = page.store(combined_documents)
logger.info(
@@ -186,7 +206,7 @@ def _store_pages(index_path: str, page_documents: dict[int, list[Document]], mar
logger.exception("Skipping index page %d", page_index)
continue
- yield page_index, combined_documents[:num_stored], existing_documents
+ yield StoredPage(combined_documents[:num_stored], existing_documents, agreements)
def _document_token_set(doc: Document) -> set[str]:
diff --git a/mwmbl/models.py b/mwmbl/models.py
index 9037410..d018ea2 100644
--- a/mwmbl/models.py
+++ b/mwmbl/models.py
@@ -581,8 +581,10 @@ class CrawlerAgreement(models.Model):
"""A crawler's submission of a URL meeting another crawler's stored copy of it, and how
closely the two agreed - see mwmbl.indexer.agreement.
- For finding crawlers whose copies disagree with many different crawlers. Keeps the
- similarities rather than the text, which the submitted batches in object storage hold.
+ For finding crawlers whose copies disagree with many different crawlers. A low
+ similarity says the two sides disagree, not which one is wrong, so the analysis has to
+ hold it against both: user is often the honest crawler revisiting a polluted URL. Keeps
+ the similarities rather than the text, which the submitted batches in object storage hold.
"""
url = models.TextField()
diff --git a/test/test_crawler_agreement.py b/test/test_crawler_agreement.py
index 22791a3..88e4c8f 100644
--- a/test/test_crawler_agreement.py
+++ b/test/test_crawler_agreement.py
@@ -43,7 +43,6 @@ def test_find_agreements_compares_against_another_crawlers_copy():
(agreement,) = find_agreements(incoming, existing)
assert agreement.url == URL
- assert agreement.user_id == 3
assert agreement.existing_user_ids == (1, 2)
assert agreement.title_similarity == 1.0
assert agreement.extract_similarity == 0.0
@@ -85,8 +84,11 @@ def test_find_agreements_without_crawl_times_has_no_delta():
@pytest.fixture
def index_path(tmp_path):
+ """Enough pages that a document's terms land on pages of their own, as they do in the
+ real index. On a few pages they collide, and a page can then hold an incoming copy that
+ combining a colliding term's documents has not touched, hiding what it does to the rest."""
path = tmp_path / "test.tinysearch"
- TinyIndex.create(item_factory=Document, index_path=str(path), num_pages=10, page_size=PAGE_SIZE)
+ TinyIndex.create(item_factory=Document, index_path=str(path), num_pages=100_000, page_size=PAGE_SIZE)
return str(path)
@@ -107,7 +109,6 @@ def test_index_documents_reports_one_agreement_per_url(index_path, no_blacklist)
assert indexed.agreements == {
Agreement(
url=URL,
- user_id=2,
existing_user_ids=(1,),
title_similarity=1.0,
extract_similarity=1.0,
@@ -116,6 +117,43 @@ def test_index_documents_reports_one_agreement_per_url(index_path, no_blacklist)
}
+ "title, extract",
+ [
+ ("Python tutorial", "Learn python today"),
+ ("Python tutorial", "Buy cheap pills buy cheap pills python python python"),
+ ("Python tutorial python python python", "Learn python today"),
+ ],
+)
+def test_index_documents_reports_the_agreement_whichever_copy_wins(index_path, no_blacklist, title, extract):
+ """Combining merges the copies' user_ids into whichever one ranks first, so the
+ comparison has to see them before that, whether the incoming copy ranks above the stored
+ one or not."""
+ index_documents([Document("Python tutorial", URL, "Learn python today", user_ids=[1])], index_path)
+
+ indexed = index_documents([Document(title, URL, extract, user_ids=[2])], index_path)
+
+ (agreement,) = indexed.agreements
+ assert agreement.existing_user_ids == (1,)
+ assert agreement.title_similarity == trigram_similarity(title, "Python tutorial")
+ assert agreement.extract_similarity == trigram_similarity(extract, "Learn python today")
+
+
+def test_index_documents_reports_one_agreement_when_stored_copies_differ(index_path, no_blacklist):
+ """Two crawlers' versions of a URL have different terms, so the pages it is on hold
+ different stored copies. A submission meeting both is still one agreement, against the
+ copy most of its pages hold."""
+ index_documents([Document("Python tutorial", URL, "Learn python today with examples", user_ids=[1])], index_path)
+ index_documents([Document("Python tutorial", URL, "Spam", user_ids=[2])], index_path)
+
+ indexed = index_documents(
+ [Document("Python tutorial", URL, "Learn python today with examples", user_ids=[3])], 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)
@@ -130,7 +168,6 @@ def user(db):
def _agreement(url=URL):
return Agreement(
url=url,
- user_id=0,
existing_user_ids=(1, 2),
title_similarity=0.9,
extract_similarity=0.4,