An open source, non-profit web search engine
Address review of the worst agreements store
Claudeef5ff4a72b12
diff --git a/mwmbl/admin_views.py b/mwmbl/admin_views.pyindex 034c9c5..1702e60 100644--- a/mwmbl/admin_views.py+++ b/mwmbl/admin_views.py@@ -30,7 +30,7 @@ from django.conf import settingsfrom django.contrib.admin.views.decorators import staff_member_requiredfrom django.core.cache import cachefrom django.db.models import F, OuterRef, Q, Subquery-from django.http import HttpRequest+from django.http import HttpRequest, HttpResponseBadRequestfrom django.shortcuts import renderfrom redis import RedisError@@ -550,26 +550,28 @@ def paying_users_view(request):return render(request, "admin/paying_users.html", context)-WORST_AGREEMENT_GAP_LABELS = {- "hour": "Crawled within an hour of each other",- "day": "Crawled within a day of each other",- "week": "Crawled within a week of each other",- "older": "Crawled more than a week apart",- worst_agreements.UNKNOWN_GAP: "Crawl gap unknown",+WORST_AGREEMENT_ROLE_TITLES = {+ worst_agreements.SUBMITTER: "Its copies, submitted over other crawlers'",+ worst_agreements.STORED: "Other crawlers' copies, submitted over its own",}+WORST_AGREEMENT_BUCKET_LABELS = {bucket.name: bucket.label for bucket in worst_agreements.BUCKETS}@staff_member_requireddef worst_agreements_view(request):username = request.GET.get("username", "").strip()- weeks_ago = int(request.GET.get("weeks_ago", 0))+ week_choices = range(worst_agreements.KEPT_WINDOWS)+ weeks_ago_param = request.GET.get("weeks_ago", "0")+ if weeks_ago_param not in {str(choice) for choice in week_choices}:+ return HttpResponseBadRequest(f"weeks_ago must be a whole number below {worst_agreements.KEPT_WINDOWS}")+ weeks_ago = int(weeks_ago_param)window = search_callers.window_start(utc_today()) - timedelta(weeks=weeks_ago)context = {"title": "Worst agreements","username": username,"window": window,"weeks_ago": weeks_ago,- "week_choices": range(worst_agreements.KEPT_WINDOWS),+ "week_choices": week_choices,"per_bucket": worst_agreements.WORST_PER_BUCKET,}if not username:@@ -581,25 +583,39 @@ def worst_agreements_view(request):return render(request, "admin/worst_agreements.html", context)try:- by_bucket = worst_agreements.read_worst_agreements(worst_agreements.get_redis(), crawler.id, window)+ by_role = worst_agreements.read_worst_agreements(worst_agreements.get_redis(), crawler.id, window)except RedisError as e:logger.exception("Could not read the worst agreements from Redis")context["redis_error"] = str(e)return render(request, "admin/worst_agreements.html", context)- other_ids = {entry["other_user_id"] for entries in by_bucket.values() for entry in entries}+ other_ids = {+ entry["other_user_id"] for by_bucket in by_role.values() for entries in by_bucket.values() for entry in entries+ }# The index keeps the ids of deleted users, so some have no name left.usernames = dict(MwmblUser.objects.filter(id__in=other_ids).values_list("id", "username"))- context["buckets"] = [+ context["roles"] = [{- "label": WORST_AGREEMENT_GAP_LABELS[bucket],- "entries": [- entry- | {"other_username": usernames.get(entry["other_user_id"], f"deleted user {entry['other_user_id']}")}- for entry in entries+ "title": WORST_AGREEMENT_ROLE_TITLES[role],+ "submitter": role == worst_agreements.SUBMITTER,+ "buckets": [+ {+ "label": WORST_AGREEMENT_BUCKET_LABELS[bucket],+ "entries": [+ entry+ | {+ "other_username": usernames.get(+ entry["other_user_id"], f"deleted user {entry['other_user_id']}"+ )+ }+ for entry in entries+ ],+ }+ for bucket, entries in by_bucket.items()+ if entries],}- for bucket, entries in by_bucket.items()- if entries+ for role, by_bucket in by_role.items()]+ context["empty"] = not any(role["buckets"] for role in context["roles"])return render(request, "admin/worst_agreements.html", context)diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.pyindex 8471f8c..bec09c8 100644--- a/mwmbl/crawler/app.py+++ b/mwmbl/crawler/app.py@@ -36,6 +36,8 @@ from mwmbl.settings import (ENDPOINT_URL,FILE_NAME_SUFFIX,KEY_ID,+ NUM_EXTRACT_CHARS,+ NUM_TITLE_CHARS,PUBLIC_URL_PREFIX,PUBLIC_USER_ID_LENGTH,USER_ID_LENGTH,@@ -50,6 +52,14 @@ stats_manager = StatsManager(logger = getLogger(__name__)++def _truncated(text: str, limit: int) -> str:+ """The text cut to the limit the crawler cuts it to, so a client that does not cannot+ store more: a result is shown at that length, and its text is copied to every page of+ its terms and kept for comparison with other crawlers' copies."""+ return text if len(text) <= limit else text[: limit - 1] + "…"++INVALID_CRAWL_KEY_MESSAGE = "Invalid API key or insufficient scope (crawl scope required)."# Module-level router used by the unified v1 API@@ -250,8 +260,8 @@ def _register_routes(r: Router | NinjaAPI):documents.append(Document(url=result.url,- title=result.title,- extract=result.extract,+ title=_truncated(result.title, NUM_TITLE_CHARS),+ extract=_truncated(result.extract, NUM_EXTRACT_CHARS),user_ids=[api_key.user.id],last_crawled=last_crawled,)diff --git a/mwmbl/crawler/worst_agreements.py b/mwmbl/crawler/worst_agreements.pyindex f770f0b..4aa61d7 100644--- a/mwmbl/crawler/worst_agreements.py+++ b/mwmbl/crawler/worst_agreements.py@@ -8,16 +8,18 @@ similarity below which a comparison is judged bad.They are ranked within buckets of the gap between the two crawls. Pages change, so rankedtogether, stale copies of busy pages would crowd out copies crawled minutes apart that differ-by one inserted sentence - the ones most worth reading.+by one inserted sentence - the ones most worth reading. Both crawl times are the crawlers' own+claims, so a crawler can put its comparisons in the stale buckets by claiming old ones.Each comparison is kept under both crawlers, since a low similarity says the copies differ,not which one is wrong: the honest crawler revisiting a spammed URL holds the spam as the-other copy.+other copy. The two roles are ranked apart, so that other crawlers' copies cannot push a+crawler's own submissions out of its list, nor its own submissions push out theirs."""import jsonfrom datetime import date, datetime, time, timedelta, timezone-from typing import Optional+from typing import NamedTuple, Optionalimport redisfrom django.conf import settings@@ -25,24 +27,41 @@ from django.conf import settingsfrom mwmbl.indexer.agreement import Agreementfrom mwmbl.search_callers import window_start-WORST_KEY = "crawler:worst-agreements:{user_id}:{window}:{bucket}"+# The comparisons in a sorted set, scored by agreement_score, and their copies in a hash+# keyed the same, so that a URL compared again replaces its entry rather than adding one.+RANK_KEY = "crawler:worst-agreements:{user_id}:{role}:{window}:{bucket}"+ENTRIES_KEY = RANK_KEY + ":entries"WORST_PER_BUCKET = 50WINDOW_DAYS = 7-# This week and the three before it. A few hundred kilobytes per crawler at most.+# This week and the three before it. Titles and extracts are truncated when submitted, so a+# few hundred kilobytes per crawler at most.KEPT_WINDOWS = 4-# Upper bounds of the gap between the two crawls, in seconds, either way round.-GAP_BUCKETS = {- "hour": 60 * 60,- "day": 60 * 60 * 24,- "week": 60 * 60 * 24 * 7,- "older": None,-}-UNKNOWN_GAP = "unknown"-BUCKETS = list(GAP_BUCKETS) + [UNKNOWN_GAP]+SUBMITTER = "submitter"+"""The crawler's copy, compared with another crawler's stored copy it met."""+STORED = "stored"+"""The crawler's stored copy, met by another crawler's."""+ROLES = [SUBMITTER, STORED]+++class GapBucket(NamedTuple):+ name: str+ limit: Optional[int]+ """Upper bound of the gap between the two crawls, in seconds, either way round."""+ label: str+++GAP_BUCKETS = [+ GapBucket("hour", 60 * 60, "Crawled within an hour of each other"),+ GapBucket("day", 60 * 60 * 24, "Crawled within a day of each other"),+ GapBucket("week", 60 * 60 * 24 * 7, "Crawled within a week of each other"),+ GapBucket("older", None, "Crawled more than a week apart"),+]+UNKNOWN_GAP = GapBucket("unknown", None, "Crawl gap unknown")+BUCKETS = GAP_BUCKETS + [UNKNOWN_GAP]_redis: Optional[redis.Redis] = None@@ -54,35 +73,60 @@ def get_redis() -> redis.Redis:return _redis-def gap_bucket(last_crawled_delta: Optional[int]) -> str:+def gap_bucket(last_crawled_delta: Optional[int]) -> GapBucket:if last_crawled_delta is None:return UNKNOWN_GAPgap = abs(last_crawled_delta)- return next(name for name, limit in GAP_BUCKETS.items() if limit is None or gap < limit)+ return next(bucket for bucket in GAP_BUCKETS if bucket.limit is None or gap < bucket.limit)+++def agreement_score(agreement: Agreement) -> float:+ """The lower of the title and extract similarities, so that a rewritten title ranks as+ low as a rewritten extract. An empty extract scores zero against anything, so where+ either is empty the titles alone are compared; CrawlerAgreement counts the empty ones."""+ if agreement.extract_empty or agreement.existing_extract_empty:+ return agreement.title_similarity+ return min(agreement.title_similarity, agreement.extract_similarity)def record_worst_agreements(client: redis.Redis, agreements: list[Agreement], user_id: int, today: date):- window = window_start(today)- expire_at = datetime.combine(window + timedelta(days=WINDOW_DAYS * KEPT_WINDOWS), time(), tzinfo=timezone.utc)+ window = window_start(today).isoformat()+ expire_at = datetime.combine(+ window_start(today) + timedelta(days=WINDOW_DAYS * KEPT_WINDOWS), time(), tzinfo=timezone.utc+ )+ keys = {}pipeline = client.pipeline()for agreement in agreements:- # An empty extract scores zero against anything, so these would fill every bucket.- # CrawlerAgreement counts them.- if agreement.extract_empty or agreement.existing_extract_empty:- continue- bucket = gap_bucket(agreement.last_crawled_delta)- for owner_id, entry in _entries(agreement, user_id):- key = WORST_KEY.format(user_id=owner_id, window=window.isoformat(), bucket=bucket)- pipeline.zadd(key, {json.dumps(entry, sort_keys=True): agreement.extract_similarity})- # Lowest first, so everything from this rank on is the best of the rest.- pipeline.zremrangebyrank(key, WORST_PER_BUCKET, -1)- pipeline.expireat(key, expire_at)- pipeline.execute()---def _entries(agreement: Agreement, user_id: int) -> list[tuple[int, dict]]:+ score = agreement_score(agreement)+ bucket = gap_bucket(agreement.last_crawled_delta).name+ for owner_id, role, entry in _entries(agreement, user_id, score):+ rank_key = RANK_KEY.format(user_id=owner_id, role=role, window=window, bucket=bucket)+ entries_key = ENTRIES_KEY.format(user_id=owner_id, role=role, window=window, bucket=bucket)+ member = f"{entry['other_user_id']} {agreement.url}"+ pipeline.zadd(rank_key, {member: score})+ pipeline.hset(entries_key, member, json.dumps(entry))+ pipeline.expireat(rank_key, expire_at)+ pipeline.expireat(entries_key, expire_at)+ keys[rank_key] = entries_key+ if not keys:+ return+ for rank_key in keys:+ # Lowest first, so everything from this rank on is the best of the rest.+ pipeline.zrange(rank_key, WORST_PER_BUCKET, -1)+ results = pipeline.execute()++ trim = client.pipeline()+ for (rank_key, entries_key), dropped in zip(keys.items(), results[-len(keys) :]):+ if dropped:+ trim.zrem(rank_key, *dropped)+ trim.hdel(entries_key, *dropped)+ trim.execute()+++def _entries(agreement: Agreement, user_id: int, score: float) -> list[tuple[int, str, dict]]:scores = {"url": agreement.url,+ "score": score,"title_similarity": agreement.title_similarity,"extract_similarity": agreement.extract_similarity,"last_crawled_delta": agreement.last_crawled_delta,@@ -90,22 +134,22 @@ def _entries(agreement: Agreement, user_id: int) -> list[tuple[int, dict]]:submitted = {"title": agreement.title, "extract": agreement.extract}stored = {"title": agreement.existing_title, "extract": agreement.existing_extract}return [- (- user_id,- scores- | {"role": "submitter", "other_user_id": agreement.existing_user_id, "own": submitted, "other": stored},- ),- (- agreement.existing_user_id,- scores | {"role": "stored", "other_user_id": user_id, "own": stored, "other": submitted},- ),+ (user_id, SUBMITTER, scores | {"other_user_id": agreement.existing_user_id, "own": submitted, "other": stored}),+ (agreement.existing_user_id, STORED, scores | {"other_user_id": user_id, "own": stored, "other": submitted}),]-def read_worst_agreements(client: redis.Redis, user_id: int, window: date) -> dict[str, list[dict]]:- """The kept comparisons of each gap bucket, least agreeing first."""+def read_worst_agreements(client: redis.Redis, user_id: int, window: date) -> dict[str, dict[str, list[dict]]]:+ """For each role, the kept comparisons of each gap bucket, least agreeing first."""+ slots = [(role, bucket.name) for role in ROLES for bucket in BUCKETS]pipeline = client.pipeline()- for bucket in BUCKETS:- pipeline.zrange(WORST_KEY.format(user_id=user_id, window=window.isoformat(), bucket=bucket), 0, -1)- members_by_bucket = pipeline.execute()- return {bucket: [json.loads(member) for member in members] for bucket, members in zip(BUCKETS, members_by_bucket)}+ for role, bucket in slots:+ key_parts = {"user_id": user_id, "role": role, "window": window.isoformat(), "bucket": bucket}+ pipeline.zrange(RANK_KEY.format(**key_parts), 0, -1)+ pipeline.hgetall(ENTRIES_KEY.format(**key_parts))+ results = pipeline.execute()++ worst = {role: {} for role in ROLES}+ for (role, bucket), members, entries in zip(slots, results[0::2], results[1::2]):+ worst[role][bucket] = [json.loads(entries[member]) for member in members]+ return worstdiff --git a/mwmbl/templates/admin/worst_agreements.html b/mwmbl/templates/admin/worst_agreements.htmlindex ae72756..bdd13f5 100644--- a/mwmbl/templates/admin/worst_agreements.html+++ b/mwmbl/templates/admin/worst_agreements.html@@ -41,10 +41,10 @@<input type="submit" value="Show"></form><p class="note" style="padding: 0 10px">- The {{ per_bucket }} comparisons with the lowest extract similarity this crawler was part- of in the week from {{ window }}, in either role, for each gap between the two crawls.- A low similarity says the copies differ, not which is wrong: read both. Comparisons- with an empty extract on either side are left out.+ The {{ per_bucket }} least agreeing comparisons this crawler was part of in the week+ from {{ window }}, in each role and for each gap between the two crawls, scored by the+ lower of the title and extract similarities (titles alone where an extract is empty).+ A low similarity says the copies differ, not which is wrong: read both.</p></div>@@ -55,36 +55,41 @@<h2>Redis unreachable</h2><p class="bad">{{ redis_error }}</p></div>- {% elif username and not buckets %}+ {% elif username and empty %}<div class="module"><p style="padding: 10px">Nothing kept for {{ username }} that week.</p></div>{% endif %}- {% for bucket in buckets %}- <div class="module">- <h2>{{ bucket.label }}</h2>- {% for entry in bucket.entries %}- <div class="result">- <div class="copies">- <div class="url">{{ entry.url }}</div>- <div class="title">{{ entry.own.title }}</div>- <p class="extract">{{ entry.own.extract }}</p>- <div class="other">- <div class="note">{{ entry.other_username }}'s copy</div>- <div class="title">{{ entry.other.title }}</div>- <p class="extract">{{ entry.other.extract }}</p>+ {% for role in roles %}+ {% if role.buckets %}+ <h2>{{ role.title }}</h2>+ {% endif %}+ {% for bucket in role.buckets %}+ <div class="module">+ <h2>{{ bucket.label }}</h2>+ {% for entry in bucket.entries %}+ <div class="result">+ <div class="copies">+ <div class="url">{{ entry.url }}</div>+ <div class="title">{{ entry.own.title }}</div>+ <p class="extract">{{ entry.own.extract }}</p>+ <div class="other">+ <div class="note">{{ entry.other_username }}'s copy</div>+ <div class="title">{{ entry.other.title }}</div>+ <p class="extract">{{ entry.other.extract }}</p>+ </div></div>- </div>- <div class="scores">- <div>Extract similarity <strong>{{ entry.extract_similarity|floatformat:2 }}</strong></div>- <div>Title similarity <strong>{{ entry.title_similarity|floatformat:2 }}</strong></div>- <div class="note">- {% if entry.role == "submitter" %}{{ username }} submitted over {{ entry.other_username }}'s copy- {% else %}{{ entry.other_username }} submitted over {{ username }}'s copy{% endif %}+ <div class="scores">+ <div>Title similarity <strong>{{ entry.title_similarity|floatformat:2 }}</strong></div>+ <div>Extract similarity <strong>{{ entry.extract_similarity|floatformat:2 }}</strong></div>+ <div class="note">+ {% if role.submitter %}{{ username }} submitted over {{ entry.other_username }}'s copy+ {% else %}{{ entry.other_username }} submitted over {{ username }}'s copy{% endif %}+ </div></div></div>- </div>- {% endfor %}- </div>+ {% endfor %}+ </div>+ {% endfor %}{% endfor %}</div>diff --git a/test/test_crawler_agreement.py b/test/test_crawler_agreement.pyindex c865bde..4fd5de9 100644--- a/test/test_crawler_agreement.py+++ b/test/test_crawler_agreement.py@@ -9,13 +9,14 @@ from django.test import Clientfrom django.utils import timezonefrom mwmbl.crawler.agreement import AGREEMENT_RETENTION, prune_agreements, record_agreements-from mwmbl.crawler.worst_agreements import UNKNOWN_GAP, read_worst_agreements+from mwmbl.crawler.worst_agreements import SUBMITTER, UNKNOWN_GAP, read_worst_agreementsfrom mwmbl.indexer.agreement import Agreement, StoredCopy, compare, find_stored_copies, trigram_similarityfrom mwmbl.indexer.blacklist_providers import StaticBlacklistProviderfrom mwmbl.indexer.blacklist_snapshot import SnapshotBlacklistfrom mwmbl.indexer.index_batches import _most_held_copies, index_documentsfrom mwmbl.models import ApiKey, CrawlerAgreement, generate_api_keyfrom mwmbl.search_callers import window_start+from mwmbl.settings import NUM_EXTRACT_CHARS, NUM_TITLE_CHARSfrom mwmbl.tinysearchengine.indexer import PAGE_SIZE, Document, DocumentSource, DocumentState, TinyIndexfrom mwmbl.utils import utc_today@@ -317,6 +318,31 @@ def test_post_results_rejects_a_crawl_time_before_the_epoch(user):index_documents.assert_not_called()+def test_post_results_truncates_titles_and_extracts(user):+ """To what the crawler truncates them to, so a client that does not cannot store more."""+ 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,+ patch("mwmbl.crawler.app.upload_object", return_value="fake/path.json.gz"),+ patch("mwmbl.crawler.app.stats_manager"),+ patch("mwmbl.crawler.app.record_agreements"),+ patch("mwmbl.crawler.worst_agreements.record_worst_agreements"),+ ):+ Client().post(+ "/api/v1/crawler/results",+ content_type="application/json",+ data={"results": [{"url": URL, "title": "t" * 1000, "extract": "e" * 1_000_000}]},+ HTTP_X_API_KEY=raw_key,+ )++ ((document,), _), _ = index_documents.call_args+ assert document.title == "t" * (NUM_TITLE_CHARS - 1) + "…"+ assert document.extract == "e" * (NUM_EXTRACT_CHARS - 1) + "…"++@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")@@ -350,4 +376,4 @@ def test_post_results_records_agreements(user, index_path, no_blacklist):assert stored.extract_similarity < 1.0assert stored.crawler_version == "1.2.0"kept = read_worst_agreements(worst_redis, user.id, window_start(utc_today()))- assert [entry["own"]["extract"] for entry in kept[UNKNOWN_GAP]] == ["Learn rust today"]+ assert [entry["own"]["extract"] for entry in kept[SUBMITTER][UNKNOWN_GAP.name]] == ["Learn rust today"]diff --git a/test/test_worst_agreements.py b/test/test_worst_agreements.pyindex 4a6242b..4b9c311 100644--- a/test/test_worst_agreements.py+++ b/test/test_worst_agreements.py@@ -1,4 +1,4 @@-from datetime import date, timedelta+from datetime import timedeltaimport fakeredisimport pytest@@ -6,8 +6,11 @@ from django.contrib.auth import get_user_modelfrom django.test import Clientfrom mwmbl.crawler.worst_agreements import (+ STORED,+ SUBMITTER,UNKNOWN_GAP,WORST_PER_BUCKET,+ agreement_score,gap_bucket,read_worst_agreements,record_worst_agreements,@@ -16,8 +19,6 @@ from mwmbl.indexer.agreement import Agreementfrom mwmbl.search_callers import window_startfrom mwmbl.utils import utc_today-TODAY = date(2026, 10, 21)-WINDOW = window_start(TODAY)SUBMITTER_ID = 1STORED_ID = 2@@ -27,11 +28,28 @@ def client():return fakeredis.FakeRedis(decode_responses=True)-def _agreement(url="https://example.com/", extract_similarity=0.5, delta=60, extract="Spam", existing_extract="Real"):+def _today():+ """Not a fixed date: the keys expire a few weeks after the week they are for."""+ return utc_today()+++def _window():+ return window_start(_today())+++def _agreement(+ url="https://example.com/",+ title_similarity=1.0,+ extract_similarity=0.5,+ delta=60,+ extract="Spam",+ existing_extract="Real",+ existing_user_id=STORED_ID,+):return Agreement(url=url,- existing_user_id=STORED_ID,- title_similarity=1.0,+ existing_user_id=existing_user_id,+ title_similarity=title_similarity,extract_similarity=extract_similarity,extract_empty=not extract.strip(),existing_extract_empty=not existing_extract.strip(),@@ -43,26 +61,50 @@ def _agreement(url="https://example.com/", extract_similarity=0.5, delta=60, ext)+def _record(client, agreements, user_id=SUBMITTER_ID):+ record_worst_agreements(client, agreements, user_id, _today())+++def _read(client, user_id, role, bucket="hour"):+ return read_worst_agreements(client, user_id, _window())[role][bucket]++@pytest.mark.parametrize("delta, bucket",- [(None, UNKNOWN_GAP), (0, "hour"), (-3599, "hour"), (3600, "day"), (-86400 * 3, "week"), (86400 * 30, "older")],+ [+ (None, UNKNOWN_GAP.name),+ (0, "hour"),+ (-3599, "hour"),+ (3600, "day"),+ (-86400 * 3, "week"),+ (86400 * 30, "older"),+ ],)def test_gap_bucket(delta, bucket):- assert gap_bucket(delta) == bucket+ assert gap_bucket(delta).name == bucket+++def test_agreement_score_takes_the_lower_similarity():+ assert agreement_score(_agreement(title_similarity=0.2, extract_similarity=0.9)) == 0.2+ assert agreement_score(_agreement(title_similarity=0.9, extract_similarity=0.3)) == 0.3+++def test_agreement_score_compares_titles_alone_when_an_extract_is_empty():+ assert agreement_score(_agreement(title_similarity=0.7, extract_similarity=0.0, extract="")) == 0.7def test_keeps_the_comparison_under_both_crawlers(client):- record_worst_agreements(client, [_agreement()], SUBMITTER_ID, TODAY)+ _record(client, [_agreement()])- (submitted,) = read_worst_agreements(client, SUBMITTER_ID, WINDOW)["hour"]- (stored,) = read_worst_agreements(client, STORED_ID, WINDOW)["hour"]+ (submitted,) = _read(client, SUBMITTER_ID, SUBMITTER)+ (stored,) = _read(client, STORED_ID, STORED)- assert submitted["role"] == "submitter"assert submitted["other_user_id"] == STORED_IDassert (submitted["own"]["extract"], submitted["other"]["extract"]) == ("Spam", "Real")- assert stored["role"] == "stored"assert stored["other_user_id"] == SUBMITTER_IDassert (stored["own"]["extract"], stored["other"]["extract"]) == ("Real", "Spam")+ assert _read(client, SUBMITTER_ID, STORED) == []+ assert _read(client, STORED_ID, SUBMITTER) == []def test_keeps_only_the_least_agreeing(client):@@ -70,10 +112,11 @@ def test_keeps_only_the_least_agreeing(client):_agreement(url=f"https://example.com/{i}", extract_similarity=i / 100) for i in range(WORST_PER_BUCKET + 10)]- record_worst_agreements(client, agreements, SUBMITTER_ID, TODAY)+ _record(client, agreements)- kept = read_worst_agreements(client, SUBMITTER_ID, WINDOW)["hour"]- assert [entry["extract_similarity"] for entry in kept] == [i / 100 for i in range(WORST_PER_BUCKET)]+ kept = _read(client, SUBMITTER_ID, SUBMITTER)+ assert [entry["score"] for entry in kept] == [i / 100 for i in range(WORST_PER_BUCKET)]+ assert client.hlen(next(iter(client.keys("*:submitter:*:entries")))) == WORST_PER_BUCKETdef test_ranks_each_crawl_gap_separately(client):@@ -81,61 +124,90 @@ def test_ranks_each_crawl_gap_separately(client):stale = [_agreement(url=f"https://example.com/{i}", extract_similarity=0.1, delta=86400 * 30) for i in range(60)]fresh = _agreement(url="https://example.com/fresh", extract_similarity=0.6, delta=60)- record_worst_agreements(client, stale + [fresh], SUBMITTER_ID, TODAY)+ _record(client, stale + [fresh])++ assert [entry["url"] for entry in _read(client, SUBMITTER_ID, SUBMITTER)] == ["https://example.com/fresh"]+ assert len(_read(client, SUBMITTER_ID, SUBMITTER, "older")) == WORST_PER_BUCKET+++def test_other_crawlers_cannot_push_out_a_crawlers_own_submissions(client):+ _record(client, [_agreement(url="https://example.com/spam", extract_similarity=0.3)], user_id=SUBMITTER_ID)+ junk = [+ _agreement(url=f"https://example.com/{i}", extract_similarity=0.01, existing_user_id=SUBMITTER_ID)+ for i in range(WORST_PER_BUCKET)+ ]+ _record(client, junk, user_id=3)++ assert [entry["url"] for entry in _read(client, SUBMITTER_ID, SUBMITTER)] == ["https://example.com/spam"]+ assert len(_read(client, SUBMITTER_ID, STORED)) == WORST_PER_BUCKET+- kept = read_worst_agreements(client, SUBMITTER_ID, WINDOW)- assert [entry["url"] for entry in kept["hour"]] == ["https://example.com/fresh"]- assert len(kept["older"]) == WORST_PER_BUCKET+def test_a_url_compared_again_replaces_its_entry(client):+ for delta in range(60):+ _record(client, [_agreement(delta=delta, extract=f"Spam {delta}")])+ (kept,) = _read(client, SUBMITTER_ID, SUBMITTER)+ assert kept["own"]["extract"] == "Spam 59"-def test_skips_empty_extracts(client):- record_worst_agreements(client, [_agreement(extract=""), _agreement(existing_extract=" ")], SUBMITTER_ID, TODAY)- assert not any(read_worst_agreements(client, SUBMITTER_ID, WINDOW).values())+def test_keeps_empty_extracts_ranked_by_title(client):+ _record(client, [_agreement(title_similarity=0.4, extract="")])++ (kept,) = _read(client, SUBMITTER_ID, SUBMITTER)+ assert kept["score"] == 0.4def test_keeps_each_week_apart(client):- record_worst_agreements(client, [_agreement()], SUBMITTER_ID, TODAY)+ _record(client, [_agreement()])- assert not any(read_worst_agreements(client, SUBMITTER_ID, WINDOW - timedelta(weeks=1)).values())+ previous_week = read_worst_agreements(client, SUBMITTER_ID, _window() - timedelta(weeks=1))+ assert not any(entries for by_bucket in previous_week.values() for entries in by_bucket.values())def test_keys_expire(client):- record_worst_agreements(client, [_agreement()], SUBMITTER_ID, TODAY)+ _record(client, [_agreement()])- assert all(client.ttl(key) > 0 for key in client.keys("crawler:worst-agreements:*"))+ keys = client.keys("crawler:worst-agreements:*")+ assert keys+ assert all(client.ttl(key) > 0 for key in keys)+++def admin_browser(db):+ admin = get_user_model().objects.create_superuser(username="admin", email="[email protected]", password="pw")+ browser = Client()+ browser.force_login(admin)+ return browser@pytest.mark.django_db-def test_admin_page_shows_both_copies(client):+def test_admin_page_shows_both_copies(client, admin_browser, monkeypatch):User = get_user_model()- admin = User.objects.create_superuser(username="admin", email="[email protected]", password="pw")submitter = User.objects.create_user(username="sneaky", email="[email protected]", password="pw")other = User.objects.create_user(username="honest", email="[email protected]", password="pw")- agreement = _agreement(extract="Buy cheap pills", existing_extract="Learn python")._replace(- existing_user_id=other.id- )- record_worst_agreements(client, [agreement], submitter.id, utc_today())- browser = Client()- browser.force_login(admin)+ agreement = _agreement(extract="Buy cheap pills", existing_extract="Learn python", existing_user_id=other.id)+ _record(client, [agreement], user_id=submitter.id)+ monkeypatch.setattr("mwmbl.crawler.worst_agreements.get_redis", lambda: client)- with pytest.MonkeyPatch.context() as monkeypatch:- monkeypatch.setattr("mwmbl.crawler.worst_agreements.get_redis", lambda: client)- response = browser.get("/admin/worst-agreements/", {"username": "sneaky"})+ response = admin_browser.get("/admin/worst-agreements/", {"username": "sneaky"})content = response.content.decode()assert response.status_code == 200assert "Buy cheap pills" in contentassert "Learn python" in content- assert "honest's copy" in content+ assert "sneaky submitted over honest's copy" in content@pytest.mark.django_db-def test_admin_page_with_an_unknown_user(client):- admin = get_user_model().objects.create_superuser(username="admin", email="[email protected]", password="pw")- browser = Client()- browser.force_login(admin)-- response = browser.get("/admin/worst-agreements/", {"username": "nobody"})+def test_admin_page_with_an_unknown_user(admin_browser):+ response = admin_browser.get("/admin/worst-agreements/", {"username": "nobody"})assert "No user named nobody" in response.content.decode()++[email protected]("weeks_ago", ["abc", "-1", "4"])+def test_admin_page_rejects_a_week_it_does_not_keep(admin_browser, weeks_ago):+ response = admin_browser.get("/admin/worst-agreements/", {"username": "nobody", "weeks_ago": weeks_ago})++ assert response.status_code == 400