Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Record how closely crawlers' copies of the same URL agree

Claudeaafbdc31f004
diff --git a/dump.rdb b/dump.rdb
new file mode 100644
index 0000000..7c93c23
Binary files /dev/null and b/dump.rdb differ
diff --git a/mwmbl/apps.py b/mwmbl/apps.py
index 10b6890..85630a4 100644
--- a/mwmbl/apps.py
+++ b/mwmbl/apps.py
@@ -143,6 +143,7 @@ class MwmblConfig(AppConfig):
from mwmbl.background import (
count_index_urls,
flush_expired_tokens,
+ prune_crawler_agreements,
purge_blacklisted_from_queue,
refresh_blacklist_snapshot,
report_usage_to_polar,
@@ -157,6 +158,7 @@ class MwmblConfig(AppConfig):
MODERATION_RETRAIN_TASK = "mwmbl.background.retrain_domain_moderation_model"
INDEX_COUNT_TASK = "mwmbl.background.count_index_urls"
FLUSH_TOKENS_TASK = "mwmbl.background.flush_expired_tokens"
+ PRUNE_AGREEMENTS_TASK = "mwmbl.background.prune_crawler_agreements"
# Sync search counts once per hour (3600 seconds)
if not Task.objects.filter(task_name=SYNC_TASK).exists():
@@ -201,6 +203,9 @@ class MwmblConfig(AppConfig):
if not Task.objects.filter(task_name=FLUSH_TOKENS_TASK).exists():
flush_expired_tokens(repeat=Task.DAILY, repeat_until=None)
+ if not Task.objects.filter(task_name=PRUNE_AGREEMENTS_TASK).exists():
+ prune_crawler_agreements(repeat=Task.DAILY, repeat_until=None)
+
except Exception:
# Don't prevent startup if background task scheduling fails
log.exception("Failed to schedule background tasks")
diff --git a/mwmbl/background.py b/mwmbl/background.py
index bb806c7..148f820 100644
--- a/mwmbl/background.py
+++ b/mwmbl/background.py
@@ -25,6 +25,7 @@ from redis import Redis
from mwmbl import pricing
from mwmbl.count_urls import count_urls_step, get_redis
+from mwmbl.crawler.agreement import prune_agreements
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
@@ -356,3 +357,10 @@ def retrain_domain_moderation_model():
def flush_expired_tokens():
"""Delete expired JWT refresh tokens from the blacklist tables, which gain a row per refresh."""
call_command("flushexpiredtokens")
+
+
+@background(schedule=0)
+def prune_crawler_agreements():
+ """Delete crawler agreements older than their retention, since every shared URL adds a row."""
+ deleted = prune_agreements()
+ logger.info("Pruned %d crawler agreements", deleted)
diff --git a/mwmbl/crawler/agreement.py b/mwmbl/crawler/agreement.py
new file mode 100644
index 0000000..1930480
--- /dev/null
+++ b/mwmbl/crawler/agreement.py
@@ -0,0 +1,31 @@
+from datetime import timedelta
+
+from django.utils import timezone
+
+from mwmbl.indexer.agreement import Agreement
+from mwmbl.models import CrawlerAgreement, MwmblUser
+
+# Long enough to see a crawler's agreement settle over many partners, short enough that the
+# table, a row per URL two crawlers share, stays small.
+AGREEMENT_RETENTION = timedelta(days=90)
+
+
+def record_agreements(agreements: set[Agreement], user: MwmblUser, crawler_version: str | None):
+ CrawlerAgreement.objects.bulk_create(
+ CrawlerAgreement(
+ url=agreement.url,
+ user=user,
+ existing_user_ids=list(agreement.existing_user_ids),
+ title_similarity=agreement.title_similarity,
+ extract_similarity=agreement.extract_similarity,
+ last_crawled_delta=agreement.last_crawled_delta,
+ crawler_version=crawler_version,
+ )
+ for agreement in agreements
+ )
+
+
+def prune_agreements() -> int:
+ cutoff = timezone.now() - AGREEMENT_RETENTION
+ deleted, _ = CrawlerAgreement.objects.filter(created_at__lt=cutoff).delete()
+ return deleted
diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.py
index dbfc58a..6096694 100644
--- a/mwmbl/crawler/app.py
+++ b/mwmbl/crawler/app.py
@@ -13,6 +13,7 @@ from ninja import NinjaAPI, Router, Schema
from ninja.errors import HttpError
from redis import Redis
+from mwmbl.crawler.agreement import record_agreements
from mwmbl.crawler.batch import (
DatasetRequest,
Error,
@@ -266,7 +267,8 @@ def _register_routes(r: Router | NinjaAPI):
record_device(api_key.user, results.device_name)
index_path = f"{settings.DATA_PATH}/{settings.INDEX_NAME}"
- index_documents(documents, index_path)
+ 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.
diff --git a/mwmbl/indexer/agreement.py b/mwmbl/indexer/agreement.py
new file mode 100644
index 0000000..503a3a3
--- /dev/null
+++ b/mwmbl/indexer/agreement.py
@@ -0,0 +1,67 @@
+"""
+How closely two crawlers' copies of the same URL agree.
+
+Every submission is written to the pages of each of its terms, and a page already holding
+the URL holds another crawler's copy of it. Comparing the two at that point costs nothing,
+and a crawler whose copies disagree with many different crawlers is one whose submissions
+are worth a closer look.
+"""
+
+from typing import Iterable, NamedTuple, Optional
+
+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."""
+ title_similarity: float
+ 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."""
+
+
+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.
+ attributed_by_url = {document.url: document for document in existing if document.user_ids}
+ agreements = set()
+ for document in incoming:
+ stored = attributed_by_url.get(document.url)
+ if stored is None or document.user_ids is None:
+ continue
+ # 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),
+ last_crawled_delta=last_crawled_delta,
+ )
+ )
+ return agreements
+
+
+def trigram_similarity(first: str, second: str) -> float:
+ """Jaccard similarity of the two strings' character trigrams."""
+ first_trigrams = _trigrams(first)
+ second_trigrams = _trigrams(second)
+ return len(first_trigrams & second_trigrams) / len(first_trigrams | second_trigrams)
+
+
+def _trigrams(text: str) -> set[str]:
+ normalised = " ".join(text.lower().split())
+ # A string shorter than a trigram is its own only gram, so "" matches "" and "a" does not match "b".
+ return {normalised[i : i + 3] for i in range(max(len(normalised) - 2, 1))}
diff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.py
index e02c475..96a32fe 100644
--- a/mwmbl/indexer/index_batches.py
+++ b/mwmbl/indexer/index_batches.py
@@ -10,6 +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.blacklist_snapshot import get_snapshot_blacklist
from mwmbl.indexer.index import prepare_url_for_tokenizing, tokenize_document
from mwmbl.tinysearchengine.indexer import (
@@ -58,12 +59,19 @@ def get_url_score(url):
def index_batches(batch_data: Collection[HashedBatch], index_path: str) -> Counter:
start_time = datetime.now(timezone.utc)
documents = list(get_documents_from_batches(batch_data))
- end_time, new_page_doc_counts = index_documents(documents, index_path)
- logger.info(f"Indexing took {end_time - start_time}")
- return new_page_doc_counts
+ indexed = index_documents(documents, index_path)
+ logger.info(f"Indexing took {indexed.end_time - start_time}")
+ return indexed.new_page_doc_counts
-def index_documents(documents, index_path):
+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."""
+
+
+def index_documents(documents, index_path) -> IndexedDocuments:
"""The common choke point every indexing path (the trusted-crawler POST /results
endpoint, the standalone crawl tool) goes through, so
this is where the blacklist is enforced. Crawling/link-discovery also check the
@@ -77,9 +85,15 @@ def index_documents(documents, index_path):
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)
+ 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)
end_time = datetime.now(timezone.utc)
- return end_time, new_page_doc_counts
+ return IndexedDocuments(end_time, new_page_doc_counts, agreements)
class IndexedURLs(NamedTuple):
@@ -100,7 +114,7 @@ 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):
+ 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}
@@ -140,16 +154,18 @@ 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
- )
+ for _, stored_documents, _ in _store_pages(index_path, page_documents, mark_synced):
+ term_new_doc_counts.update(_new_terms(stored_documents))
return term_new_doc_counts
+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)
+
+
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."""
+ """Merge the documents into their pages, yielding for each page written its index, 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():
@@ -170,7 +186,7 @@ def _store_pages(index_path: str, page_documents: dict[int, list[Document]], mar
logger.exception("Skipping index page %d", page_index)
continue
- yield combined_documents[:num_stored], existing_documents
+ yield page_index, combined_documents[:num_stored], existing_documents
def _document_token_set(doc: Document) -> set[str]:
diff --git a/mwmbl/migrations/0047_crawleragreement.py b/mwmbl/migrations/0047_crawleragreement.py
new file mode 100644
index 0000000..975a6a8
--- /dev/null
+++ b/mwmbl/migrations/0047_crawleragreement.py
@@ -0,0 +1,52 @@
+# Generated by Django 5.2.13 on 2026-10-17 21:50
+
+import django.contrib.postgres.fields
+import django.db.models.deletion
+from django.conf import settings
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("mwmbl", "0046_usernotification"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="CrawlerAgreement",
+ fields=[
+ (
+ "id",
+ models.BigAutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("url", models.TextField()),
+ (
+ "existing_user_ids",
+ django.contrib.postgres.fields.ArrayField(base_field=models.IntegerField(), size=None),
+ ),
+ ("title_similarity", models.FloatField()),
+ ("extract_similarity", models.FloatField()),
+ ("last_crawled_delta", models.IntegerField(null=True)),
+ ("crawler_version", models.TextField(null=True)),
+ ("created_at", models.DateTimeField(auto_now_add=True)),
+ ],
+ ),
+ migrations.AddField(
+ model_name="crawleragreement",
+ name="user",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="+",
+ to=settings.AUTH_USER_MODEL,
+ ),
+ ),
+ migrations.AddIndex(
+ model_name="crawleragreement",
+ index=models.Index(fields=["created_at"], name="mwmbl_crawl_created_7f0783_idx"),
+ ),
+ ]
diff --git a/mwmbl/models.py b/mwmbl/models.py
index 8b90be1..9037410 100644
--- a/mwmbl/models.py
+++ b/mwmbl/models.py
@@ -575,3 +575,27 @@ class SeedDomainCrawl(models.Model):
indexes = [
models.Index(fields=["seed_domain", "-crawled_at"]),
]
+
+
+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.
+ """
+
+ url = models.TextField()
+ user = models.ForeignKey(MwmblUser, on_delete=models.CASCADE, related_name="+")
+ # Not foreign keys: up to two users, and the stored text is one of theirs without saying which.
+ existing_user_ids = ArrayField(models.IntegerField())
+ title_similarity = models.FloatField()
+ extract_similarity = models.FloatField()
+ last_crawled_delta = models.IntegerField(null=True) # seconds, incoming crawl minus stored crawl
+ crawler_version = models.TextField(null=True) # of the incoming submission; the stored copy's is unknown
+ created_at = models.DateTimeField(auto_now_add=True)
+
+ class Meta:
+ indexes = [
+ models.Index(fields=["created_at"]),
+ ]
diff --git a/test/test_apps_background_scheduling.py b/test/test_apps_background_scheduling.py
index 273dc62..ee07828 100644
--- a/test/test_apps_background_scheduling.py
+++ b/test/test_apps_background_scheduling.py
@@ -22,8 +22,16 @@ POLAR_REPORT_TASK = "mwmbl.background.report_usage_to_polar"
BLACKLIST_SNAPSHOT_TASK = "mwmbl.background.refresh_blacklist_snapshot"
BLACKLIST_PURGE_TASK = "mwmbl.background.purge_blacklisted_from_queue"
INDEX_COUNT_TASK = "mwmbl.background.count_index_urls"
-
-ALL_TASKS = {SYNC_TASK, POLAR_REPORT_TASK, BLACKLIST_SNAPSHOT_TASK, BLACKLIST_PURGE_TASK, INDEX_COUNT_TASK}
+PRUNE_AGREEMENTS_TASK = "mwmbl.background.prune_crawler_agreements"
+
+ALL_TASKS = {
+ SYNC_TASK,
+ POLAR_REPORT_TASK,
+ BLACKLIST_SNAPSHOT_TASK,
+ BLACKLIST_PURGE_TASK,
+ INDEX_COUNT_TASK,
+ PRUNE_AGREEMENTS_TASK,
+}
@pytest.fixture(autouse=True)
diff --git a/test/test_crawler_agreement.py b/test/test_crawler_agreement.py
new file mode 100644
index 0000000..22791a3
--- /dev/null
+++ b/test/test_crawler_agreement.py
@@ -0,0 +1,194 @@
+from datetime import timedelta
+from unittest.mock import patch
+
+import fakeredis
+import pytest
+from django.contrib.auth import get_user_model
+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.blacklist_providers import StaticBlacklistProvider
+from mwmbl.indexer.blacklist_snapshot import SnapshotBlacklist
+from mwmbl.indexer.index_batches import index_documents
+from mwmbl.models import ApiKey, CrawlerAgreement, generate_api_key
+from mwmbl.tinysearchengine.indexer import PAGE_SIZE, Document, TinyIndex
+
+URL = "https://example.com/page"
+
+
+def test_trigram_similarity_of_identical_text_is_one():
+ assert trigram_similarity("The Python Tutorial", "the python tutorial") == 1.0
+
+
+def test_trigram_similarity_of_unrelated_text_is_zero():
+ assert trigram_similarity("abcdef", "uvwxyz") == 0.0
+
+
+def test_trigram_similarity_of_short_text():
+ assert trigram_similarity("", "") == 1.0
+ assert trigram_similarity("a", "b") == 0.0
+
+
+def test_trigram_similarity_of_an_edit_is_between():
+ similarity = trigram_similarity("Python is a programming language", "Python is a great programming language")
+ assert 0.5 < similarity < 1.0
+
+
+def test_find_agreements_compares_against_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)]
+
+ (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
+ assert agreement.last_crawled_delta == 600
+
+
+def test_find_agreements_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()
+
+
+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."""
+ 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()
+
+
+def test_find_agreements_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()
+
+
+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,) = find_agreements(incoming, existing)
+
+ assert agreement.last_crawled_delta is None
+
+
+def index_path(tmp_path):
+ path = tmp_path / "test.tinysearch"
+ TinyIndex.create(item_factory=Document, index_path=str(path), num_pages=10, page_size=PAGE_SIZE)
+ return str(path)
+
+
+def no_blacklist():
+ blacklist = SnapshotBlacklist(built_in_rules=StaticBlacklistProvider(set()), redis_client=fakeredis.FakeRedis())
+ with patch("mwmbl.indexer.index_batches.get_snapshot_blacklist", return_value=blacklist):
+ yield
+
+
+def test_index_documents_reports_one_agreement_per_url(index_path, no_blacklist):
+ """The URL is written to the page of each of its terms, most of them holding the same
+ stored copy, and that is one agreement, not one per term."""
+ index_documents([Document("Python tutorial", URL, "Learn python today", user_ids=[1])], index_path)
+
+ indexed = index_documents([Document("Python tutorial", URL, "Learn python today", user_ids=[2])], index_path)
+
+ assert indexed.agreements == {
+ Agreement(
+ url=URL,
+ user_id=2,
+ existing_user_ids=(1,),
+ title_similarity=1.0,
+ extract_similarity=1.0,
+ last_crawled_delta=None,
+ )
+ }
+
+
+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()
+
+
+def user(db):
+ return get_user_model().objects.create_user(username="crawler", email="[email protected]", password="pw")
+
+
+def _agreement(url=URL):
+ return Agreement(
+ url=url,
+ user_id=0,
+ existing_user_ids=(1, 2),
+ title_similarity=0.9,
+ extract_similarity=0.4,
+ last_crawled_delta=60,
+ )
+
+
+def test_record_agreements(user):
+ record_agreements({_agreement()}, user, "1.2.0")
+
+ stored = CrawlerAgreement.objects.get()
+ assert stored.url == URL
+ assert stored.user == user
+ assert stored.existing_user_ids == [1, 2]
+ assert stored.title_similarity == 0.9
+ assert stored.extract_similarity == 0.4
+ assert stored.last_crawled_delta == 60
+ assert stored.crawler_version == "1.2.0"
+
+
+def test_prune_agreements_deletes_only_expired_rows(user):
+ 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)
+
+ assert prune_agreements() == 1
+ assert list(CrawlerAgreement.objects.values_list("url", flat=True)) == ["https://example.com/new"]
+
+
+def test_post_results_records_agreements(user, index_path, no_blacklist):
+ other_user = get_user_model().objects.create_user(username="other", email="[email protected]", password="pw")
+ index_documents([Document("Python tutorial", URL, "Learn python today", user_ids=[other_user.id])], index_path)
+ raw_key, key_hash = generate_api_key()
+ ApiKey.objects.create(user=user, key=key_hash, name="Crawl key", scopes=[ApiKey.Scope.CRAWL])
+
+ with (
+ patch("mwmbl.crawler.app.settings.DATA_PATH", str(index_path).rsplit("/", 1)[0]),
+ patch("mwmbl.crawler.app.settings.INDEX_NAME", "test.tinysearch"),
+ patch("mwmbl.crawler.app.upload_object", return_value="fake/path.json.gz"),
+ patch("mwmbl.crawler.app.stats_manager"),
+ ):
+ response = Client().post(
+ "/api/v1/crawler/results",
+ content_type="application/json",
+ data={
+ "results": [{"url": URL, "title": "Python tutorial", "extract": "Learn rust today"}],
+ "crawler_version": "1.2.0",
+ },
+ HTTP_X_API_KEY=raw_key,
+ )
+
+ assert response.status_code == 200
+ stored = CrawlerAgreement.objects.get()
+ assert stored.user == user
+ assert stored.existing_user_ids == [other_user.id]
+ assert stored.title_similarity == 1.0
+ assert stored.extract_similarity < 1.0
+ assert stored.crawler_version == "1.2.0"
diff --git a/test/test_search_api_key.py b/test/test_search_api_key.py
index 5621654..05e5d83 100644
--- a/test/test_search_api_key.py
+++ b/test/test_search_api_key.py
@@ -9,6 +9,7 @@ Covers:
- flush_search_counts background task
"""
+from collections import Counter
from datetime import datetime
from datetime import timezone as stdlib_timezone
from unittest.mock import patch
@@ -23,6 +24,7 @@ from ninja_jwt.tokens import RefreshToken
from mwmbl import pricing
from mwmbl.background import sync_search_counts
+from mwmbl.indexer.index_batches import IndexedDocuments
from mwmbl.models import AgreementType, ApiKey, UsageBucket, UserAgreement, UserBilling, generate_api_key
from mwmbl.quota import (
RATE_LIMIT,
@@ -489,6 +491,14 @@ 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 index_documents
+
+
@pytest.mark.django_db
def test_post_results_no_key_returns_401(api_client):
response = api_client.post(
@@ -579,7 +589,7 @@ def test_post_results_uses_submitted_last_crawled(api_client, crawl_api_key):
captured = []
with (
- patch("mwmbl.crawler.app.index_documents", side_effect=lambda docs, path: captured.extend(docs)),
+ patch("mwmbl.crawler.app.index_documents", side_effect=_capturing_index(captured)),
patch("mwmbl.crawler.app.upload_object", return_value="fake/path.json.gz"),
patch("mwmbl.crawler.app.stats_manager"),
):
@@ -647,7 +657,7 @@ def test_post_results_sets_user_id(api_client, crawl_api_key, verified_user):
captured = []
with (
- patch("mwmbl.crawler.app.index_documents", side_effect=lambda docs, path: captured.extend(docs)),
+ patch("mwmbl.crawler.app.index_documents", side_effect=_capturing_index(captured)),
patch("mwmbl.crawler.app.upload_object", return_value="fake/path.json.gz"),
patch("mwmbl.crawler.app.stats_manager"),
):