An open source, non-profit web search engine
Mark indexed Staan copies; validate crawl times; reserve the seed crawler
Claude11579b120fb9
diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.pyindex 165319c..33fb134 100644--- a/mwmbl/crawler/app.py+++ b/mwmbl/crawler/app.py@@ -272,6 +272,7 @@ def _register_routes(r: Router | NinjaAPI):# 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")+# Update stats for the userstats_manager.record_results(results, api_key.user)diff --git a/mwmbl/crawler/batch.py b/mwmbl/crawler/batch.pyindex acb7aed..09e6513 100644--- a/mwmbl/crawler/batch.py+++ b/mwmbl/crawler/batch.py@@ -170,6 +170,7 @@ class Result(Schema):)last_crawled: Optional[int] = Field(default=None,+ ge=0,description="Unix timestamp (seconds since epoch) when the page was crawled.",example=1704672000,)diff --git a/mwmbl/format.py b/mwmbl/format.pyindex ec61be5..edf8d55 100644--- a/mwmbl/format.py+++ b/mwmbl/format.py@@ -21,6 +21,8 @@ DOCUMENT_PROVIDERS = {# Staan's results go out as "eusp" (European Search Perspective): the label our# agreement with the provider requires, so it deliberately differs from the enum name.DocumentSource.STAAN: "eusp",+ # The same label for Staan's results once they are in our index: they are still Staan's.+ DocumentSource.STAAN_INDEXED: "eusp",}diff --git a/mwmbl/indexer/agreement.py b/mwmbl/indexer/agreement.pyindex 4d6eb5b..f8d9794 100644--- a/mwmbl/indexer/agreement.py+++ b/mwmbl/indexer/agreement.py@@ -28,12 +28,12 @@ class Agreement(NamedTuple):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 has no author of its own but always wins its page, so it takes on the- # user_ids of the copies it beat, and its last id names one of them.+ # 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+ if document.user_ids and document.state not in CURATED_STATES and document.source is None}agreements = set()for document in incoming:diff --git a/mwmbl/indexer/index_batches.py b/mwmbl/indexer/index_batches.pyindex 6ae322c..02414a0 100644--- a/mwmbl/indexer/index_batches.py+++ b/mwmbl/indexer/index_batches.py@@ -16,6 +16,7 @@ from mwmbl.indexer.index import prepare_url_for_tokenizing, tokenize_documentfrom mwmbl.tinysearchengine.indexer import (CURATED_STATES,Document,+ DocumentSource,DocumentState,PageError,TinyIndex,@@ -29,6 +30,10 @@ logger = getLogger(__name__)MAX_USER_IDS = 2+# What an external result's source becomes in the search index. Only Staan's results are+# kept with one, under a source of their own - see DocumentSource.STAAN_INDEXED.+INDEXED_SOURCES = {DocumentSource.STAAN: DocumentSource.STAAN_INDEXED}+def _merge_user_ids(existing: Optional[list[int]], incoming: Optional[list[int]]) -> Optional[list[int]]:"""The incoming ids go last, moved there if already present, and the oldest are dropped@@ -275,6 +280,7 @@ def index_new_results_against_query(documents: list[Document], query: str, indexcleaned.extract,term=term,last_crawled=cleaned.last_crawled,+ source=INDEXED_SOURCES.get(cleaned.source),))if page not in existing_keys:@@ -314,7 +320,8 @@ def combine_documents(existing_documents, documents, mark_synced, ranker):document.state = DocumentState.SYNCED_WITH_MAIN_INDEX# The kept copy's ids merged last, so the last id is always the crawler whose text the# page holds - see mwmbl.indexer.agreement. Its own last id is its author by the same- # rule, and a fresh submission carries only its submitter's.+ # rule, and a fresh submission carries only its submitter's. Only that last id is+ # meaningful: once the kept copy holds two, those of the copies it beats are dropped.document.user_ids = _merge_user_ids(url_user_ids.get(document.url), document.user_ids)document.last_crawled = url_last_crawled.get(document.url)combined_documents.append(document)diff --git a/mwmbl/migrations/0048_crawleragreement.py b/mwmbl/migrations/0048_crawleragreement.pyindex bc7b8ab..2721c9c 100644--- a/mwmbl/migrations/0048_crawleragreement.py+++ b/mwmbl/migrations/0048_crawleragreement.py@@ -27,7 +27,7 @@ class Migration(migrations.Migration):("existing_user_id", models.IntegerField(db_index=True)),("title_similarity", models.FloatField()),("extract_similarity", models.FloatField()),- ("last_crawled_delta", models.IntegerField(null=True)),+ ("last_crawled_delta", models.BigIntegerField(null=True)),("crawler_version", models.TextField(null=True)),("created_at", models.DateTimeField(auto_now_add=True)),],diff --git a/mwmbl/models.py b/mwmbl/models.pyindex a9f6935..b8b6444 100644--- a/mwmbl/models.py+++ b/mwmbl/models.py@@ -595,9 +595,10 @@ class CrawlerAgreement(models.Model):the similarities rather than the text, which the submitted batches in object storage hold.existing_user_id names the stored text's author only on pages written since that became- the last of a copy's user_ids. Before then the ids were in rank order, and a Super Search- copy, which has none of its own, took on those of the copies it beat. Such a page keeps- the wrong author until a fresh copy wins it, so early rows deserve less weight.+ the last of a copy's user_ids. Before then the ids were in rank order, and a copy of+ Staan's or Super Search's, which has none of its own and was written without a source,+ took on those of the copies it beat. Such a page keeps the wrong author until a fresh+ copy wins it, so early rows deserve less weight."""url = models.TextField()@@ -606,7 +607,7 @@ class CrawlerAgreement(models.Model):existing_user_id = models.IntegerField(db_index=True)title_similarity = models.FloatField()extract_similarity = models.FloatField()- last_crawled_delta = models.IntegerField(null=True) # seconds, incoming crawl minus stored crawl+ last_crawled_delta = models.BigIntegerField(null=True) # seconds, incoming crawl minus stored crawlcrawler_version = models.TextField(null=True) # of the incoming submission; the stored copy's is unknowncreated_at = models.DateTimeField(auto_now_add=True)diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.pyindex a8744b7..7f039f4 100644--- a/mwmbl/platform/api.py+++ b/mwmbl/platform/api.py@@ -26,6 +26,7 @@ from mwmbl import membership, pricingfrom mwmbl.background import enrich_domain_submission, stats_managerfrom mwmbl.exceptions import InvalidRequestfrom mwmbl.models import (+ SEED_CRAWLER_USERNAME,AgreementType,ApiKey,Device,@@ -127,7 +128,9 @@ def register(request, registration: Registration):raise InvalidRequest("Email already registered")username = registration.username or generate_username()- if registration.username and MwmblUser.objects.filter(username=registration.username).exists():+ username_taken = MwmblUser.objects.filter(username=registration.username).exists()+ # Reserved even before migration 0049 makes the user, so nobody can take it first and fail it.+ if registration.username and (username_taken or registration.username == SEED_CRAWLER_USERNAME):raise InvalidRequest("Username already exists")user = MwmblUser(username=username, email=registration.email)diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.pyindex 933f053..f4cf616 100644--- a/mwmbl/settings_common.py+++ b/mwmbl/settings_common.py@@ -146,6 +146,8 @@ AUTH_USER_MODEL = "mwmbl.MwmblUser"ACCOUNT_EMAIL_REQUIRED = TrueACCOUNT_EMAIL_VERIFICATION = "mandatory"ACCOUNT_USERNAME_REQUIRED = False+# mwmbl.models.SEED_CRAWLER_USERNAME, which settings cannot import.+ACCOUNT_USERNAME_BLACKLIST = ["mwmbl-seed-crawler"]ACCOUNT_AUTHENTICATION_METHOD = "username_email"DEFAULT_FROM_EMAIL = "[email protected]"diff --git a/mwmbl/tinysearchengine/indexer.py b/mwmbl/tinysearchengine/indexer.pyindex 07fea42..763f469 100644--- a/mwmbl/tinysearchengine/indexer.py+++ b/mwmbl/tinysearchengine/indexer.py@@ -85,10 +85,11 @@ CURATED_STATES = {state for state in DocumentState if state.value >= 7}class DocumentSource(IntEnum):"""Which external provider a document came from. None means our own crawl.- Only the external results cache sets this (see mwmbl.indexer.external_cache); documents- in the search index leave it None, and as_tuple truncates trailing Nones, so they cost- nothing for it. The values are written to disk, so they are append-only: never reuse a- number for a different provider, or a stale cache entry becomes a lie about where its+ The external results cache sets this (see mwmbl.indexer.external_cache). In the search+ index only STAAN_INDEXED is set, on the copies of Staan's results Combined Search writes+ there; crawled documents leave it None, and as_tuple truncates trailing Nones, so they+ cost nothing for it. The values are written to disk, so they are append-only: never reuse+ a number for a different provider, or a stale cache entry becomes a lie about where itsresults came from."""@@ -97,6 +98,10 @@ class DocumentSource(IntEnum):# because it is the numbering registry: with only one member the source field cannot be# told apart from "unset" and the cache's per-source behaviour cannot be tested at all.STAAN = 2+ # A Staan result as written to the search index. Apart from STAAN because the rankers read+ # a STAAN document's score as the rank Staan gave it in this request, which a stored copy+ # does not carry. It also tells the crawler agreement log that no crawler wrote the copy.+ STAAN_INDEXED = 3@dataclassdiff --git a/test/test_combined_search.py b/test/test_combined_search.pyindex e12713e..3b12954 100644--- a/test/test_combined_search.py+++ b/test/test_combined_search.py@@ -518,6 +518,21 @@ def test_index_staan_results_writes_new_pages_once(tmp_path, monkeypatch):assert [document.url for document in index.retrieve("tokio")] == [STAAN_RESULT.url]+def test_index_staan_results_marks_them_as_staans_in_the_index(tmp_path, monkeypatch):+ """Not as STAAN, which the rankers read as a result of this request with Staan's rank in+ its score, and not as nothing, which would pass them off as our own crawl."""+ index_path = Path(tmp_path) / "index.tinysearch"+ with TinyIndex.create(Document, str(index_path), num_pages=64, page_size=4096):+ pass+ monkeypatch.setattr(combined_search, "index_path", index_path)+ monkeypatch.setattr(combined_search, "find_blacklisted_urls", lambda documents: set())++ combined_search.index_staan_results("tokio", [STAAN_RESULT])++ with TinyIndex(Document, str(index_path), "r") as index:+ assert [document.source for document in index.retrieve("tokio")] == [DocumentSource.STAAN_INDEXED]++# ---------------------------------------------------------------------------# Seed crawls (the crawl itself is tested in test_seed_crawl.py)# ---------------------------------------------------------------------------diff --git a/test/test_crawler_agreement.py b/test/test_crawler_agreement.pyindex 2cf9892..da2cf17 100644--- a/test/test_crawler_agreement.py+++ b/test/test_crawler_agreement.py@@ -14,7 +14,7 @@ from mwmbl.indexer.blacklist_providers import StaticBlacklistProviderfrom mwmbl.indexer.blacklist_snapshot import SnapshotBlacklistfrom mwmbl.indexer.index_batches import _one_agreement_per_url, index_documentsfrom mwmbl.models import ApiKey, CrawlerAgreement, generate_api_key-from mwmbl.tinysearchengine.indexer import PAGE_SIZE, Document, DocumentState, TinyIndex+from mwmbl.tinysearchengine.indexer import PAGE_SIZE, Document, DocumentSource, DocumentState, TinyIndexURL = "https://example.com/page"@@ -76,6 +76,15 @@ def test_find_agreements_skips_a_curated_copy():assert find_agreements(incoming, existing) == set()+def test_find_agreements_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()++def test_find_agreements_skips_unattributed_documents():"""Seed crawls and the main index sync write documents with no user_ids: there is nocrawler to hold them against."""@@ -231,6 +240,24 @@ def test_prune_agreements_deletes_only_expired_rows(user):assert list(CrawlerAgreement.objects.values_list("url", flat=True)) == ["https://example.com/new"]+def test_post_results_rejects_a_crawl_time_before_the_epoch(user):+ """A crawl time from the distant past made the gap to the next crawler's copy overflow."""+ 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.index_documents") as index_documents:+ response = Client().post(+ "/api/v1/crawler/results",+ content_type="application/json",+ data={"results": [{"url": URL, "title": "t", "extract": "e", "last_crawled": -1_000_000_000}]},+ HTTP_X_API_KEY=raw_key,+ )++ assert response.status_code == 422+ index_documents.assert_not_called()++@pytest.mark.django_dbdef 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")diff --git a/test/test_format.py b/test/test_format.pyindex 9f5ffcf..0c8b30c 100644--- a/test/test_format.py+++ b/test/test_format.py@@ -33,6 +33,12 @@ def test_an_external_provider_names_itself():assert format_result_v2(result, 1, "tokio")["engine"] == "eusp"+def test_a_staan_result_from_our_index_still_names_staan():+ result = Document("Tokio", "https://tokio.rs/", "An async runtime.", source=DocumentSource.STAAN_INDEXED)++ assert get_result_source(result) == "eusp"++def test_a_document_with_no_source_still_answers_from_its_state():result = Document("Python", "https://en.wikipedia.org/wiki/Python", "", state=DocumentState.FROM_WIKI)diff --git a/test/test_seed_crawl.py b/test/test_seed_crawl.pyindex d0ce155..7fb9c38 100644--- a/test/test_seed_crawl.py+++ b/test/test_seed_crawl.py@@ -392,8 +392,6 @@ def test_the_crawled_pages_are_credited_to_the_seed_crawler(fake_web, redis_cachwith TinyIndex(Document, index_path, "r") as index:(spawning,) = [d for d in index.retrieve("spawning") if d.url == "https://tokio.rs/tutorial/spawning"]assert spawning.user_ids == [seed_crawler.id]- assert not seed_crawler.is_active- assert not seed_crawler.has_usable_password()@pytest.mark.django_dbdiff --git a/test/test_system_users.py b/test/test_system_users.pynew file mode 100644index 0000000..914414c--- /dev/null+++ b/test/test_system_users.py@@ -0,0 +1,40 @@+"""The user migration 0049 makes to credit the seed crawl's pages to."""++import json++import pytest+from django.conf import settings+from django.contrib.auth import get_user_model++from mwmbl.models import SEED_CRAWLER_USERNAME++User = get_user_model()+++def test_the_seed_crawler_exists_and_cannot_sign_in():+ seed_crawler = User.objects.get(username=SEED_CRAWLER_USERNAME)++ assert not seed_crawler.is_active+ assert not seed_crawler.has_usable_password()+++def test_the_seed_crawlers_username_cannot_be_registered(client):+ """Even without the user, as before migration 0049 has run: whoever took the name first+ would fail the migration."""+ User.objects.filter(username=SEED_CRAWLER_USERNAME).delete()++ response = client.post(+ "/api/v1/platform/register",+ data=json.dumps({"email": "[email protected]", "password": "correctpassword", "username": SEED_CRAWLER_USERNAME}),+ content_type="application/json",+ )++ assert response.status_code == 400+ assert not User.objects.filter(username=SEED_CRAWLER_USERNAME).exists()+++def test_allauth_refuses_the_seed_crawlers_username():+ """Settings cannot import SEED_CRAWLER_USERNAME, so they repeat it."""+ assert settings.ACCOUNT_USERNAME_BLACKLIST == [SEED_CRAWLER_USERNAME]