Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Credit seed crawl pages to a seed crawler user; skip curated copies

Claude7f2d2c553f16
diff --git a/mwmbl/crawler/stats.py b/mwmbl/crawler/stats.py
index 34262fc..a5d1372 100644
--- a/mwmbl/crawler/stats.py
+++ b/mwmbl/crawler/stats.py
@@ -10,7 +10,7 @@ from redis import Redis
from mwmbl.count_urls import get_counts, get_domain_result_count
from mwmbl.crawler.batch import Results
-from mwmbl.models import MwmblUser, UserStats
+from mwmbl.models import SEED_CRAWLER_USERNAME, MwmblUser, UserStats
from mwmbl.utils import utc_today
from mwmbl.volunteer_membership import update_volunteer_memberships
@@ -148,6 +148,7 @@ class StatsManager:
first_week_start = this_week_start - timedelta(weeks=REGISTRATION_WEEKS - 1)
weekly_counts = (
MwmblUser.objects.filter(date_joined__date__gte=first_week_start)
+ .exclude(username=SEED_CRAWLER_USERNAME)
.annotate(week=TruncWeek("date_joined"))
.values("week")
.annotate(num_users=Count("id"))
diff --git a/mwmbl/indexer/agreement.py b/mwmbl/indexer/agreement.py
index 126adc2..4d6eb5b 100644
--- a/mwmbl/indexer/agreement.py
+++ b/mwmbl/indexer/agreement.py
@@ -9,7 +9,7 @@ are worth a closer look.
from typing import Iterable, NamedTuple, Optional
-from mwmbl.tinysearchengine.indexer import Document
+from mwmbl.tinysearchengine.indexer import CURATED_STATES, Document
class Agreement(NamedTuple):
@@ -27,8 +27,14 @@ 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.
- authors_by_url = {document.url: (document, document.user_ids[-1]) for document in existing if document.user_ids}
+ # 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.
+ 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
+ }
agreements = set()
for document in incoming:
if document.url not in authors_by_url or document.user_ids is None:
diff --git a/mwmbl/indexer/seed_crawl.py b/mwmbl/indexer/seed_crawl.py
index b8ca365..e00ef9b 100644
--- a/mwmbl/indexer/seed_crawl.py
+++ b/mwmbl/indexer/seed_crawl.py
@@ -57,7 +57,7 @@ from redis.client import Pipeline
from mwmbl.crawler.retrieve import crawl_batch
from mwmbl.indexer.index_batches import index_new_documents
from mwmbl.indexer.seed_domains import new_page_score, record_seed_domain_crawls, register_seed_domains
-from mwmbl.models import MwmblUser, SeedDomain
+from mwmbl.models import SEED_CRAWLER_USERNAME, MwmblUser, SeedDomain
from mwmbl.tinysearchengine.indexer import Document
from mwmbl.tinysearchengine.rank import find_blacklisted_urls
from mwmbl.utils import bare_host
@@ -195,7 +195,7 @@ class Frontier:
self.queues[domain].clear()
-def crawl_round(frontier: Frontier, batch: list[str], redis) -> list[Document]:
+def crawl_round(frontier: Frontier, batch: list[str], redis, seed_crawler_id: int) -> list[Document]:
"""Fetch a round's URLs, adding their links to the frontier and returning their documents."""
results = crawl_batch(batch, settings.SEED_CRAWL_THREADS, 0, redis)
documents = []
@@ -210,6 +210,7 @@ def crawl_round(frontier: Frontier, batch: list[str], redis) -> list[Document]:
content["title"],
result["url"],
content["extract"],
+ user_ids=[seed_crawler_id],
last_crawled=result["timestamp"] // 1000,
)
)
@@ -460,7 +461,8 @@ def _run_round(redis, record_key: str, token: int, fields: dict[str, str], index
next_round_due = float(fields["last_round_started"]) + settings.SEED_CRAWL_DOMAIN_DELAY_SECONDS
time.sleep(max(0.0, next_round_due - time.time()))
round_started = time.time()
- documents = crawl_round(frontier, batch, redis)
+ seed_crawler_id = MwmblUser.objects.values_list("id", flat=True).get(username=SEED_CRAWLER_USERNAME)
+ documents = crawl_round(frontier, batch, redis, seed_crawler_id)
# Should the worker die between indexing the round and recording it, the round is run
# again, and finds its pages already indexed: they are lost from the record, not counted twice.
indexed = index_new_documents(documents, index_path)
diff --git a/mwmbl/migrations/0049_seed_crawler_user.py b/mwmbl/migrations/0049_seed_crawler_user.py
new file mode 100644
index 0000000..39fc671
--- /dev/null
+++ b/mwmbl/migrations/0049_seed_crawler_user.py
@@ -0,0 +1,28 @@
+from django.contrib.auth.hashers import make_password
+from django.db import migrations
+
+# A frozen copy of mwmbl.models.SEED_CRAWLER_USERNAME: a migration has to keep
+# producing the same data forever, so it must not depend on application code.
+SEED_CRAWLER_USERNAME = "mwmbl-seed-crawler"
+
+
+def create_seed_crawler(apps, schema_editor):
+ """The user the seed crawl's pages are credited to. Inactive and without a usable
+ password, so nobody can sign in as it."""
+ MwmblUser = apps.get_model("mwmbl", "MwmblUser")
+ MwmblUser.objects.create(username=SEED_CRAWLER_USERNAME, password=make_password(None), is_active=False)
+
+
+def delete_seed_crawler(apps, schema_editor):
+ MwmblUser = apps.get_model("mwmbl", "MwmblUser")
+ MwmblUser.objects.filter(username=SEED_CRAWLER_USERNAME).delete()
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("mwmbl", "0048_crawleragreement"),
+ ]
+
+ operations = [
+ migrations.RunPython(create_seed_crawler, delete_seed_crawler),
+ ]
diff --git a/mwmbl/models.py b/mwmbl/models.py
index 6575eaa..a9f6935 100644
--- a/mwmbl/models.py
+++ b/mwmbl/models.py
@@ -9,6 +9,12 @@ from django.utils import timezone
from mwmbl.membership import MembershipTier, VolunteerTier
from mwmbl.utils import bare_host
+# The seed crawl fetches its pages itself rather than through a volunteer, so they are credited
+# to a user of their own, made by migration 0049: the user who asked for the crawl did not
+# write them. It gives every copy the crawl writes an author, which the crawler agreement log
+# relies on, and a copy of a page that no volunteer could have tampered with.
+SEED_CRAWLER_USERNAME = "mwmbl-seed-crawler"
+
class MwmblUser(AbstractUser):
# Pages the user's seed crawls (Combined Search with crawl=true) have added to the index,
@@ -587,6 +593,11 @@ class CrawlerAgreement(models.Model):
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.
+
+ 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.
"""
url = models.TextField()
diff --git a/test/test_crawler_agreement.py b/test/test_crawler_agreement.py
index 59b2eea..2cf9892 100644
--- a/test/test_crawler_agreement.py
+++ b/test/test_crawler_agreement.py
@@ -14,7 +14,7 @@ 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.models import ApiKey, CrawlerAgreement, generate_api_key
-from mwmbl.tinysearchengine.indexer import PAGE_SIZE, Document, TinyIndex
+from mwmbl.tinysearchengine.indexer import PAGE_SIZE, Document, DocumentState, TinyIndex
URL = "https://example.com/page"
@@ -67,6 +67,15 @@ def test_find_agreements_compares_against_another_crawlers_text_the_crawler_is_c
assert agreement.existing_user_id == 1
+def test_find_agreements_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()
+
+
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."""
diff --git a/test/test_seed_crawl.py b/test/test_seed_crawl.py
index 6dd80a0..d0ce155 100644
--- a/test/test_seed_crawl.py
+++ b/test/test_seed_crawl.py
@@ -14,12 +14,14 @@ from ninja_jwt.tokens import RefreshToken
from mwmbl.indexer import index_batches, seed_crawl, seed_domains
from mwmbl.indexer.index_batches import index_new_documents
-from mwmbl.models import ApiKey, SeedDomain, SeedDomainCrawl, generate_api_key
+from mwmbl.models import SEED_CRAWLER_USERNAME, ApiKey, SeedDomain, SeedDomainCrawl, generate_api_key
from mwmbl.tinysearchengine.indexer import Document, DocumentSource, TinyIndex
User = get_user_model()
SEED = "https://www.tokio.rs/"
+# For the rounds run without the worker, which looks the seed crawler's user up itself.
+SEED_CRAWLER_ID = 0
STAAN_RESULTS = [
Document("Tokio", SEED, "An async runtime.", source=DocumentSource.STAAN),
Document("Async book", "https://rust-lang.github.io/async-book/", "Async Rust.", source=DocumentSource.STAAN),
@@ -106,7 +108,7 @@ def _crawl(seed_urls, domains, is_new=lambda url: True):
frontier = seed_crawl.Frontier.from_seeds(seed_urls, set(domains))
crawled = []
while batch := frontier.next_batch():
- documents = seed_crawl.crawl_round(frontier, batch, redis=None)
+ documents = seed_crawl.crawl_round(frontier, batch, redis=None, seed_crawler_id=SEED_CRAWLER_ID)
crawled.append((len(batch), documents))
frontier.record_round(batch, {document.url for document in documents if is_new(document.url)})
return crawled
@@ -380,6 +382,20 @@ def test_the_crawled_pages_are_in_the_index(fake_web, redis_cache, user, index_p
assert "https://tokio.rs/tutorial/spawning" in {document.url for document in index.retrieve("spawning")}
+def test_the_crawled_pages_are_credited_to_the_seed_crawler(fake_web, redis_cache, user, index_path):
+ """Not to the user who asked for the crawl: the pages were fetched here, not by them."""
+ seed_crawler = User.objects.get(username=SEED_CRAWLER_USERNAME)
+
+ _run(user, index_path)
+
+ with 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_db
def test_pages_already_in_the_index_are_not_counted_as_new(fake_web, redis_cache, user, index_path):
_run(user, index_path)