An open source, non-profit web search engine
Fix four review findings in the domain moderation suggester
Daoud Clarkecf1a36721183
diff --git a/mwmbl/moderation/evidence.py b/mwmbl/moderation/evidence.pyindex 9cab277..da143f7 100644--- a/mwmbl/moderation/evidence.py+++ b/mwmbl/moderation/evidence.py@@ -72,8 +72,8 @@ def crawl_domain(domain: str, redis, max_pages: int = None) -> dict:}-def _fetch_homepage(domain: str, redis) -> tuple[dict, bool]:- """The homepage, and whether it came back over TLS.+def _fetch_homepage(domain: str, redis) -> tuple[dict, bool | None]:+ """The homepage, and whether it came back over TLS - None when nothing came back.Only https used to be tried, which made "this site has no certificate" and "this site isdown" the same result - a decisive REJECT for being unreachable. They are not the same@@ -83,6 +83,9 @@ def _fetch_homepage(domain: str, redis) -> tuple[dict, bool]:Only a fetch *error* is retried. A 404 over https is an answer, and asking the sameserver the same question again without TLS will get the same one.++ A domain neither attempt reached has no answer either way, and says so with None: False+ there would be read as a fact about the site rather than about the fetch."""over_https = crawl_url(f"https://{domain}/", redis)if not over_https.get("error"):@@ -92,8 +95,10 @@ def _fetch_homepage(domain: str, redis) -> tuple[dict, bool]:if over_http.get("error"):# Neither worked. Report the https attempt: it is the one whose error describes what# we would do in production, and reporting the http failure would say "no TLS" about- # a domain that simply is not there.- return over_https, False+ # a domain that simply is not there. TLS is unknown rather than absent for the same+ # reason: the queue card reads this signal directly, and False draws a definite+ # "no TLS" on a domain nothing ever reached.+ return over_https, Nonereturn over_http, False@@ -194,7 +199,7 @@ def _final_domain(homepage: dict, domain: str) -> str:return final if final and final != domain else ""-def _signals(domain: str, pages: list[dict], https: bool) -> dict:+def _signals(domain: str, pages: list[dict], https: bool | None) -> dict:text = " ".join(f"{page['title']} {page['extract']}" for page in pages).lower()try:blacklisted = get_snapshot_blacklist().is_domain_blacklisted(domain)diff --git a/mwmbl/moderation/model.py b/mwmbl/moderation/model.pyindex 4243c64..beaacd5 100644--- a/mwmbl/moderation/model.py+++ b/mwmbl/moderation/model.py@@ -25,6 +25,7 @@ import jsonimport threadingimport timefrom dataclasses import dataclass, field+from datetime import datetimefrom logging import getLoggerfrom pathlib import Pathfrom typing import Optional@@ -32,6 +33,7 @@ from typing import Optionalimport joblibimport numpy as npfrom django.conf import settings+from django.utils import timezonefrom mwmbl.models import ModerationModelArtifactfrom mwmbl.moderation.features import Featuriser, ModerationExample@@ -167,7 +169,7 @@ def suggest(domain: str, page_texts: list[str], evidence_items: list[EvidenceIte_model: Optional[ModerationModel] = None-_loaded_version: Optional[str] = None+_loaded_stamp: Optional[tuple[str, datetime]] = None_checked_at: Optional[float] = None_lock = threading.Lock()@@ -175,17 +177,17 @@ _lock = threading.Lock()def get_model() -> Optional[ModerationModel]:"""The published model, reloaded when a retrain has published a newer one.- None (until the published version changes) when nothing can be loaded, so a suggestion+ None (until the published artifact changes) when nothing can be loaded, so a suggestionfalls back to the deterministic checks rather than failing."""- global _model, _loaded_version, _checked_at+ global _model, _loaded_stamp, _checked_atwith _lock:if _checked_at is not None and time.monotonic() - _checked_at < MODEL_REFRESH_SECONDS:return _model- published = _published_version()- if _checked_at is None or published != _loaded_version:- _model = _load(published)- _loaded_version = published+ published = _published_stamp()+ if _checked_at is None or published != _loaded_stamp:+ _model = _load(published[0] if published else None)+ _loaded_stamp = published_checked_at = time.monotonic()return _model@@ -195,27 +197,36 @@ def publish(model: ModerationModel, metrics: dict) -> ModerationModelArtifact:buffer = io.BytesIO()joblib.dump(model, buffer)# Versions are dated, so a second retrain on the same day replaces the first rather than- # colliding on the unique version.+ # colliding on the unique version. created_on is refreshed along with the bytes: it is+ # what tells the other workers this row has changed, since the version they compare+ # against has not.artifact, _ = ModerationModelArtifact.objects.update_or_create(version=model.version,- defaults={"model": buffer.getvalue(), "metrics": metrics})+ defaults={"model": buffer.getvalue(), "metrics": metrics,+ "created_on": timezone.now()})reset_model_cache()return artifactdef reset_model_cache() -> None:"""Drop the cached model so the next call reloads. Used after a retrain, and by tests."""- global _model, _loaded_version, _checked_at+ global _model, _loaded_stamp, _checked_atwith _lock:_model = None- _loaded_version = None+ _loaded_stamp = None_checked_at = None-def _published_version() -> Optional[str]:- """The version of the newest stored artifact, or None to fall back to the bundled one."""- row = ModerationModelArtifact.objects.order_by("-created_on").values("version").first()- return row["version"] if row else None+def _published_stamp() -> Optional[tuple[str, datetime]]:+ """Version and write time of the newest stored artifact, None to fall back to the bundled.++ The write time is part of the identity because versions are dated: a second retrain on the+ same day replaces that row's bytes under the same version, and a worker comparing versions+ alone would keep serving the superseded pickle until it restarted.+ """+ row = (ModerationModelArtifact.objects.order_by("-created_on")+ .values("version", "created_on").first())+ return (row["version"], row["created_on"]) if row else Nonedef _load(version: Optional[str]) -> Optional[ModerationModel]:diff --git a/mwmbl/moderation/train.py b/mwmbl/moderation/train.pyindex 3ac58bc..9082060 100644--- a/mwmbl/moderation/train.py+++ b/mwmbl/moderation/train.py@@ -183,11 +183,17 @@ def _suggestion_influence(rows: list[TrainingRow]) -> dict:"""real = [row for row in rows if row.source == REAL]shown = [row for row in real if row.suggested_status]- agreed = [row for row in shown- if (row.suggested_status == "REJECTED") == row.rejected]+ # suggested_status holds the *action* the tool displayed - APPROVE, REJECT or UNSURE -+ # and not a submission status, so it is never "REJECTED". A suggestion of UNSURE takes no+ # side, and a decision made against one agrees with nothing: it counts as shown, but is+ # not part of the population agreement is measured over.+ took_a_side = [row for row in shown if row.suggested_status in ("APPROVE", "REJECT")]+ agreed = [row for row in took_a_side+ if (row.suggested_status == "REJECT") == row.rejected]return {"real_rows": len(real),"shown_a_suggestion": len(shown),+ "suggested_a_side": len(took_a_side),"agreed_with_it": len(agreed),}diff --git a/mwmbl/platform/schemas.py b/mwmbl/platform/schemas.pyindex a3d510c..1dae703 100644--- a/mwmbl/platform/schemas.py+++ b/mwmbl/platform/schemas.py@@ -167,24 +167,33 @@ class ConfirmEmail(Schema):class RejectionFieldsMixin:- """Validate the rejection reason and its detail, wherever a decision arrives.+ """Validate a decision's status, its rejection reason and the detail, wherever it arrives.- Django enforces neither of these. ``choices`` is not checked on ``save()``, so an- arbitrary string of twenty characters or fewer lands in the column and comes back out at- a moderator as a reason nothing knows how to render; and nothing has ever required the- detail that "Other - needs detail" promises, which is the only place a rejected submitter- finds out what was actually wrong.+ Django enforces none of these. ``choices`` is not checked on ``save()``, so an arbitrary+ string of twenty characters or fewer lands in the column and comes back out at a moderator+ as a reason nothing knows how to render; and nothing has ever required the detail that+ "Other - needs detail" promises, which is the only place a rejected submitter finds out+ what was actually wrong.++ The same goes for ``status``, and there it is worse than unrenderable: a decision carrying+ the *suggestion* action instead of a status - "APPROVE" for "APPROVED", which the same+ payload also sends as ``suggested_status`` - is accepted and written to every submission of+ the domain, which then matches neither the pending queue nor the approved set the blocklist+ is built from, and disappears from moderation entirely.A schema validator rather than a check in the view, so these come back as a 422 namingthe field, the same as an over-long audit value."""@model_validator(mode="after")- def _check_rejection(self):+ def _check_decision_fields(self):# Both columns are blank=True, so ninja types them Optional and an omitted field# arrives as None rather than "".reason = self.rejection_reason or ""detail = self.rejection_detail or ""+ if self.status not in DomainSubmission.DOMAIN_SUBMISSION_STATUS:+ allowed = ", ".join(DomainSubmission.DOMAIN_SUBMISSION_STATUS)+ raise ValueError(f"status must be one of: {allowed}")if reason and reason not in DomainSubmission.DOMAIN_REJECTION_REASON:allowed = ", ".join(DomainSubmission.DOMAIN_REJECTION_REASON)raise ValueError(f"rejection_reason must be one of: {allowed}")diff --git a/test/test_domain_moderation.py b/test/test_domain_moderation.pyindex b941ad0..78eedcf 100644--- a/test/test_domain_moderation.py+++ b/test/test_domain_moderation.py@@ -27,7 +27,7 @@ from mwmbl.moderation.features import Featuriser, ModerationExamplefrom mwmbl.moderation.model import (Suggestion, get_model, load_metrics, publish, reset_model_cache, suggest)from mwmbl.moderation.suggest import annotate_queue, refresh_suggestion, suggestion_for-from mwmbl.moderation.train import passes_gate+from mwmbl.moderation.train import _suggestion_influence, passes_gatefrom mwmbl.moderation.training_data import TrainingRow, is_trainable_domainQUEUE_URL = "/api/v1/platform/domain-submissions/queue"@@ -203,6 +203,25 @@ def test_derived_rows_never_reach_the_test_split():assert {row.source for row in train_rows} == {"real", "derived", "seed"}+def test_agreement_is_measured_against_the_action_that_was_shown():+ """suggested_status records what the tool displayed - APPROVE, REJECT or UNSURE - so+ comparing it against a submission status ("REJECTED") matched nothing and inverted the+ count: every rejection the moderator agreed with was scored as a disagreement."""+ def decided(rejected, shown):+ return TrainingRow("example.com", rejected, "", "real", [], suggested_status=shown)++ influence = _suggestion_influence([+ decided(rejected=True, shown="REJECT"), # agreed+ decided(rejected=False, shown="REJECT"), # disagreed+ decided(rejected=False, shown="APPROVE"), # agreed+ decided(rejected=True, shown="UNSURE"), # shown, but took no side+ decided(rejected=True, shown=""), # nothing was shown+ ])++ assert influence == {"real_rows": 5, "shown_a_suggestion": 4,+ "suggested_a_side": 3, "agreed_with_it": 2}++# --------------------------------------------------------------------- API@pytest.mark.django_db@@ -423,6 +442,9 @@ def test_the_card_carries_its_sample_pages_and_padlock(client, moderator, establDomainSubmission.objects.create(name="crawled.com", submitted_by=established)ready_evidence("crawled.com", signals={"has_links": True, "https": False})DomainSubmission.objects.create(name="uncrawled.com", submitted_by=established)+ DomainSubmission.objects.create(name="unreachable.com", submitted_by=established)+ ready_evidence("unreachable.com", signals={"has_links": False, "https": None},+ error="AbortError", http_status=None)items = {item["name"]: itemfor item in client.get(QUEUE_URL,@@ -433,6 +455,8 @@ def test_the_card_carries_its_sample_pages_and_padlock(client, moderator, establ# Not False: an uncrawled domain must not draw an open padlock.assert items["uncrawled.com"]["https"] is Noneassert items["uncrawled.com"]["pages"] == []+ # Nor a domain that was crawled and never answered - nothing was learned about its TLS.+ assert items["unreachable.com"]["https"] is None@pytest.mark.django_db@@ -935,7 +959,10 @@ def test_a_domain_that_is_simply_down_is_still_reported_as_unreachable():"http://gone.example/": ConnectionError("no route to host"),}, "gone.example")- assert crawl["signals"]["https"] is False+ # Unknown, not absent: the rules layer already gates "no TLS" behind having reached the+ # site, but the queue card reads this signal straight out of the row, and False there+ # draws a definite "no TLS" for a domain nothing ever answered for.+ assert crawl["signals"]["https"] is Noneassert crawl["error"] == "AbortError"kinds = {item.kind for item in rules.crawl_evidence("gone.example", crawl)}assert "no_tls" not in kinds@@ -1100,11 +1127,12 @@ def test_a_withheld_approval_outranks_a_confident_one(client, moderator, submittclass _StubModel:"""A stand-in for ModerationModel. joblib only needs it to pickle and carry a version."""- def __init__(self, version):+ def __init__(self, version, score=0.5):self.version = version+ self.score = scoredef predict(self, examples):- return [(0.5, "SPAM", 0.5) for _ in examples]+ return [(self.score, "SPAM", self.score) for _ in examples]def artifact_bytes(model) -> bytes:@@ -1138,6 +1166,22 @@ def test_a_worker_picks_up_a_retrain_it_did_not_run(monkeypatch):assert get_model().version == "domain-mod-2026-10-01"+def test_a_second_retrain_on_the_same_day_still_reaches_the_other_workers(monkeypatch):+ """Versions are dated, so a same-day republish keeps the version and replaces the bytes.+ A worker comparing versions alone would serve the superseded model until it restarted."""+ publish(_StubModel("domain-mod-2026-09-01"), {"cold_start": {"pr_auc": 0.5}})+ assert get_model().predict([None]) == [(0.5, "SPAM", 0.5)]++ monkeypatch.setattr(model_module, "MODEL_REFRESH_SECONDS", 0)+ # publish() drops the cache of the process that ran it, and this is any other worker.+ monkeypatch.setattr(model_module, "reset_model_cache", lambda: None)+ publish(_StubModel("domain-mod-2026-09-01", score=0.9), {"cold_start": {"pr_auc": 0.8}})++ assert get_model().predict([None]) == [(0.9, "SPAM", 0.9)]+ assert load_metrics()["cold_start"]["pr_auc"] == 0.8++@pytest.mark.django_dbdef test_the_bundled_artifact_is_the_warm_start_until_a_retrain_publishes(tmp_path, settings):"""A deploy against a database with no artifact in it still suggests something."""@@ -1217,6 +1261,24 @@ def test_a_rejection_reason_outside_the_four_choices_is_refused(client, moderatoassert response.status_code == 422+def test_a_decision_carrying_the_suggestion_action_as_its_status_is_refused(+ client, moderator, submitter):+ """"APPROVE" is what the tool suggests; "APPROVED" is what a submission becomes. Django+ does not check choices on save(), so the near-miss used to be written to every submission+ of the domain, which then matched neither the pending queue nor the approved set."""+ DomainSubmission.objects.create(name="example.com", submitted_by=submitter)++ response = client.post(+ DECISIONS_URL,+ data={"decisions": [{"domain": "example.com", "status": "APPROVE",+ "suggested_status": "APPROVE"}]},+ content_type="application/json", headers={"Authorization": token(moderator)})++ assert response.status_code == 422+ assert DomainSubmission.objects.get(name="example.com").status == "PENDING"++@pytest.mark.django_dbdef test_an_approval_cannot_carry_a_rejection_reason(client, moderator, submitter):DomainSubmission.objects.create(name="example.com", submitted_by=submitter)