An open source, non-profit web search engine
Suggest approve/reject to domain moderators, with the evidence behind it
Daoud Clarke2576953b1d6c
diff --git a/devdata/moderation_seed_labels.jsonl b/devdata/moderation_seed_labels.jsonlnew file mode 100644index 0000000..f905930--- /dev/null+++ b/devdata/moderation_seed_labels.jsonl@@ -0,0 +1,45 @@+# Hand-written moderation examples covering concepts neither the real decisions nor the public+# blocklists supply. Small and deliberately so: this exists to teach the model that a category+# exists, not to move aggregate numbers. Each row mirrors a rejection reason a moderator has+# actually written in DomainSubmission.rejection_detail.+#+# Format: {"domain": ..., "status": APPROVED|REJECTED, "reason": ..., "text": optional page text}+#+# OFFENSIVE that is not adult content, which the blocklist rule in rules.py already covers+# exactly. Only one real domain appears here - theonion.com, the single submission a moderator+# actually labelled OFFENSIVE ("known to be satire still might be misleading"). The rest use+# the reserved .example TLD: they are synthetic exemplars of a category, written so the class+# has some shape, and deliberately not real sites. Converting a terse moderator note on a real+# domain into a reason they did not themselves record would be putting our judgement into the+# training data under their name.+{"domain": "theonion.com", "status": "REJECTED", "reason": "OFFENSIVE", "text": "America's Finest News Source. Satirical news and headlines."}+{"domain": "stormfront-mirror.example", "status": "REJECTED", "reason": "OFFENSIVE", "text": "White nationalist community forum and discussion board"}+{"domain": "gore-archive.example", "status": "REJECTED", "reason": "OFFENSIVE", "text": "Shock content archive, graphic violence and death imagery"}+{"domain": "8kunboards.example", "status": "REJECTED", "reason": "OFFENSIVE", "text": "Unmoderated imageboard, hate speech and harassment campaigns"}+#+# Do-not-crawl policy: other search engines and ourselves. Rejected with details such as+# "don't crawl ourselves" and "same as google.com no actual useful links apart from the search UI".+{"domain": "mwmbl.org", "status": "REJECTED", "reason": "OTHER", "text": "Mwmbl search. Free, open-source, non-profit search engine."}+{"domain": "scholar.google.com", "status": "REJECTED", "reason": "OTHER", "text": "Google Scholar search. Stand on the shoulders of giants."}+{"domain": "duckduckgo.com", "status": "REJECTED", "reason": "OTHER", "text": "Privacy, simplified. Search the web without being tracked."}+{"domain": "4get.ca", "status": "REJECTED", "reason": "OTHER", "text": "Search. A proxy search engine front end."}+{"domain": "startpage.com", "status": "REJECTED", "reason": "OTHER", "text": "Private search engine. Search results without tracking."}+#+# Promotion of a paid product: a real site, but the domain exists to sell one thing.+{"domain": "receipt-bot.com", "status": "REJECTED", "reason": "OTHER", "text": "Automate your bookkeeping. Start your free trial today. Pricing from $29/month."}+{"domain": "valvepackingsealkits.com", "status": "REJECTED", "reason": "OTHER", "text": "Buy valve packing seal kits online. Request a quote. Free shipping on orders over $500."}+{"domain": "wheel-excavators.com", "status": "REJECTED", "reason": "OTHER", "text": "Wheel excavators for sale. Contact our sales team for a quote today."}+{"domain": "royallp.example", "status": "REJECTED", "reason": "OTHER", "text": "Invest with us. Guaranteed returns. Sign up now and claim your bonus."}+{"domain": "satire-headlines.example", "status": "REJECTED", "reason": "OFFENSIVE", "text": "Fake news you can trust. Satirical headlines presented as real reporting."}+#+# Sites whose content is not text, so there is nothing for a search index to hold.+{"domain": "tiktok.com", "status": "REJECTED", "reason": "OTHER", "text": "Watch short videos. Trending videos and creators."}+{"domain": "many.fan", "status": "REJECTED", "reason": "OTHER", "text": "Subscribe to creators. Unlock exclusive content with a paid membership."}+#+# Approvals, to keep the seed set from teaching the model that everything hand-written is bad.+# These are the kinds of site the index exists for: documentation, reference, and long-form writing.+{"domain": "docs.python.org", "status": "APPROVED", "reason": "", "text": "Python documentation. The Python language reference, library reference and tutorials."}+{"domain": "developer.mozilla.org", "status": "APPROVED", "reason": "", "text": "MDN Web Docs. Resources for developers, by developers. HTML, CSS and JavaScript reference."}+{"domain": "en.wikisource.org", "status": "APPROVED", "reason": "", "text": "Wikisource, the free library. Source texts and historical documents."}+{"domain": "plato.stanford.edu", "status": "APPROVED", "reason": "", "text": "Stanford Encyclopedia of Philosophy. Peer-reviewed reference articles on philosophy."}+{"domain": "lwn.net", "status": "APPROVED", "reason": "", "text": "LWN.net news from the source. In-depth reporting on the Linux kernel and free software."}diff --git a/mwmbl/apps.py b/mwmbl/apps.pyindex c4e2939..2d5a48f 100644--- a/mwmbl/apps.py+++ b/mwmbl/apps.py@@ -145,13 +145,14 @@ class MwmblConfig(AppConfig):from background_task.models import Taskfrom mwmbl.background import (purge_blacklisted_from_queue, refresh_blacklist_snapshot, report_usage_to_polar,- sync_search_counts,+ retrain_domain_moderation_model, sync_search_counts,)SYNC_TASK = "mwmbl.background.sync_search_counts"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"+ MODERATION_RETRAIN_TASK = "mwmbl.background.retrain_domain_moderation_model"# Sync search counts once per hour (3600 seconds)if not Task.objects.filter(task_name=SYNC_TASK).exists():@@ -178,6 +179,14 @@ class MwmblConfig(AppConfig):purge_blacklisted_from_queue(repeat=settings.BLACKLIST_PURGE_INTERVAL_SECONDS, repeat_until=None)+ # Retrain the moderation suggester monthly. Scheduled a month out rather than+ # schedule=0: unlike the blacklist snapshot there is nothing useful about+ # retraining at deploy time, and the shipped artifact is already current.+ if not Task.objects.filter(task_name=MODERATION_RETRAIN_TASK).exists():+ retrain_domain_moderation_model(+ schedule=settings.MODERATION_RETRAIN_INTERVAL_SECONDS,+ repeat=settings.MODERATION_RETRAIN_INTERVAL_SECONDS, repeat_until=None)+except Exception:# Don't prevent startup if background task scheduling failslog.exception("Failed to schedule background tasks")diff --git a/mwmbl/background.py b/mwmbl/background.pyindex 0b68016..d7b8dfc 100644--- a/mwmbl/background.py+++ b/mwmbl/background.py@@ -9,7 +9,7 @@ Also contains Django Background Tasks for periodic maintenance:"""import loggingimport sys-from datetime import datetime, timezone+from datetime import datetime, timedelta, timezonefrom logging import getLogger, basicConfigfrom pathlib import Pathfrom time import sleep@@ -17,6 +17,7 @@ from time import sleepfrom background_task import backgroundfrom django.conf import settingsfrom django.core.cache import cache+from django.core.management import call_commandfrom redis import Redisfrom mwmbl import pricing@@ -26,7 +27,10 @@ from mwmbl.indexer.batch_cache import BatchCachefrom mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklist, refresh_snapshotfrom mwmbl.indexer.purge_blacklisted import purge_documentsfrom mwmbl.indexer.purge_queue import drain_purge_queue, queue_size-from mwmbl.models import OldIndex, UsageBucket+from mwmbl.models import DomainEvidence, DomainSubmission, OldIndex, UsageBucket+from mwmbl.moderation.evidence import crawl_domain, store_evidence+from mwmbl.moderation.model import reset_model_cache+from mwmbl.moderation.suggest import refresh_suggestionfrom mwmbl.quota import MONTHLY_TTL, _monthly_key, get_all_monthly_keysfrom mwmbl.tinysearchengine.copy_index import copy_pagesfrom mwmbl.tinysearchengine.indexer import Document, TinyIndex@@ -230,3 +234,75 @@ def report_usage_to_polar():returnUsageBucket.objects.bulk_update(buckets_to_update, ["reported_overage"])+++# ---------------------------------------------------------------------------+# Domain moderation suggestions (Django Background Tasks)+# ---------------------------------------------------------------------------++@background(schedule=0)+def enrich_domain_submission(domain: str):+ """Crawl a submitted domain and store the suggestion the moderation queue will read.++ All of the cost of a suggestion lives here rather than on the moderator's request: three+ page fetches, the deterministic checks, and the model. Scheduled by a post_save receiver+ when a submission is created (mwmbl.signals).++ Idempotent by design - the queue only asks for a suggestion, never for a fresh crawl - so+ a domain whose evidence is still fresh is left alone. That matters because 615 of 6,949+ distinct submitted domains have been submitted more than once.+ """+ cutoff = datetime.now(timezone.utc) - timedelta(+ days=settings.MODERATION_EVIDENCE_MAX_AGE_DAYS)+ existing = DomainEvidence.objects.filter(domain=domain).first()+ if (existing is not None and existing.state == DomainEvidence.State.READY+ and existing.fetched_at and existing.fetched_at > cutoff):+ logger.info("Evidence for %s is still fresh, skipping crawl", domain)+ return++ redis = Redis.from_url(settings.REDIS_URL)+ try:+ evidence = store_evidence(domain, crawl_domain(domain, redis))+ except Exception:+ logger.exception("Failed to crawl %s for moderation", domain)+ DomainEvidence.objects.update_or_create(+ domain=domain, defaults={"state": DomainEvidence.State.FAILED})+ return++ refresh_suggestion(evidence)+ logger.info("Enriched %s: %s (%.2f)", domain, evidence.suggested_action,+ evidence.confidence or 0.0)+++@background(schedule=0)+def rescore_pending_submissions():+ """Recompute stored suggestions for everything still awaiting moderation.++ Run after a retrain. Without it a new model would only ever affect submissions made after+ it shipped, leaving the existing queue scored by its predecessor. No crawling is involved+ - the page text is already stored - so the whole backlog re-scores in seconds.+ """+ reset_model_cache()+ pending_domains = set(DomainSubmission.objects+ .filter(status="PENDING")+ .values_list("name", flat=True))+ queryset = DomainEvidence.objects.filter(domain__in=pending_domains,+ state=DomainEvidence.State.READY)++ rescored = 0+ for evidence in queryset.iterator():+ refresh_suggestion(evidence)+ rescored += 1+ logger.info("Rescored %d pending submissions", rescored)+++@background(schedule=0)+def retrain_domain_moderation_model():+ """Retrain the moderation suggester on the decisions made since the last run.++ Safe to automate because the gate, not a human, is what stops a regression: the new model+ is only published if its cold-start PR-AUC clears the lower bound of the incumbent's+ bootstrap interval. It runs in this worker, which is also the only process that loads the+ model, so the reload and the pending-queue rescore both take effect immediately.+ """+ call_command("train_domain_moderation_model")diff --git a/mwmbl/management/commands/backfill_domain_evidence.py b/mwmbl/management/commands/backfill_domain_evidence.pynew file mode 100644index 0000000..ef18823--- /dev/null+++ b/mwmbl/management/commands/backfill_domain_evidence.py@@ -0,0 +1,81 @@+"""Crawl and score domains that have no evidence yet.++Two populations, both needed:++ # give the moderation queue suggestions on day one+ uv run manage.py backfill_domain_evidence --status PENDING++ # give the model page text to train on+ uv run manage.py backfill_domain_evidence --status APPROVED --status REJECTED --since 2025-01-01++Resumable: it only ever looks at domains with no DomainEvidence row, so interrupting it and+running it again picks up where it stopped.++``--since`` matters for the training population. The crawl happens now but the labels were+made up to two years ago, so the further back you reach the more the page text describes a+site that has changed since a moderator judged it.+"""+import time++from django.core.management.base import BaseCommand+from django.utils.dateparse import parse_date++from mwmbl.crawler.env_vars import CRAWL_DELAY_SECONDS+from mwmbl.indexer.blacklist_snapshot import get_redis+from mwmbl.models import DomainEvidence, DomainSubmission+from mwmbl.moderation.evidence import crawl_domain, store_evidence+from mwmbl.moderation.suggest import refresh_suggestion+from mwmbl.moderation.training_data import is_trainable_domain+++class Command(BaseCommand):+ help = "Crawl submitted domains that have no moderation evidence yet"++ def add_arguments(self, parser):+ parser.add_argument("--status", action="append", default=None,+ choices=list(DomainSubmission.DOMAIN_SUBMISSION_STATUS))+ parser.add_argument("--since", type=parse_date, default=None)+ parser.add_argument("--limit", type=int, default=None)+ parser.add_argument("--delay", type=float, default=CRAWL_DELAY_SECONDS,+ help="Seconds to wait between domains")++ def handle(self, *args, **options):+ domains = self._domains_to_crawl(options)+ self.stdout.write(f"{len(domains)} domains to crawl")++ redis = get_redis()+ for number, domain in enumerate(domains, start=1):+ try:+ evidence = store_evidence(domain, crawl_domain(domain, redis))+ refresh_suggestion(evidence)+ self.stdout.write(+ f"[{number}/{len(domains)}] {domain}: {evidence.suggested_action or '?'} "+ f"({evidence.state})")+ except Exception as exception:+ # One unfetchable domain must not end a backfill of thousands.+ DomainEvidence.objects.update_or_create(+ domain=domain,+ defaults={"state": DomainEvidence.State.FAILED,+ "error": type(exception).__name__})+ self.stderr.write(f"[{number}/{len(domains)}] {domain}: FAILED ({exception})")+ if options["delay"]:+ time.sleep(options["delay"])++ @staticmethod+ def _domains_to_crawl(options) -> list[str]:+ submissions = DomainSubmission.objects.all()+ if options["status"]:+ submissions = submissions.filter(status__in=options["status"])+ if options["since"]:+ submissions = submissions.filter(submitted_on__date__gte=options["since"])++ already_have = set(DomainEvidence.objects.values_list("domain", flat=True))+ seen, domains = set(), []+ for name in submissions.order_by("submitted_on").values_list("name", flat=True):+ if name in seen or name in already_have or not is_trainable_domain(name):+ continue+ seen.add(name)+ domains.append(name)+ if options["limit"] and len(domains) >= options["limit"]:+ break+ return domainsdiff --git a/mwmbl/management/commands/train_domain_moderation_model.py b/mwmbl/management/commands/train_domain_moderation_model.pynew file mode 100644index 0000000..8fcd0b8--- /dev/null+++ b/mwmbl/management/commands/train_domain_moderation_model.py@@ -0,0 +1,99 @@+"""Train the domain moderation suggester and, if it passes the gate, publish the artifact.++ uv run manage.py train_domain_moderation_model --dry-run+ uv run manage.py train_domain_moderation_model++The gate compares the new model's cold-start PR-AUC against the lower bound of the incumbent's+bootstrap interval, so a change that only looks like an improvement does not ship.+"""+import json+from datetime import date+from pathlib import Path++from django.conf import settings+from django.core.management.base import BaseCommand++from mwmbl.background import rescore_pending_submissions+from mwmbl.models import DomainSubmission+from mwmbl.moderation import training_data+from mwmbl.moderation.model import (+ METRICS_FILENAME, MODEL_FILENAME, load_metrics, reset_model_cache)+from mwmbl.moderation.train import passes_gate, train++# A reason class with fewer real examples than this is a candidate for blocklist-derived+# rows, but only when --derived is passed. See mwmbl.moderation.training_data: derived rows+# cost the classes that do have real labels more than they are worth here, and OFFENSIVE -+# the only class short of data - is served exactly by the blocklist check in rules.py instead.+MIN_REAL_ROWS_PER_REASON = 30+DERIVED_ROWS_PER_REASON = 300+++class Command(BaseCommand):+ help = "Train the domain moderation approve/reject suggester"++ def add_arguments(self, parser):+ parser.add_argument("--dry-run", action="store_true",+ help="Train and report metrics without writing the artifact")+ parser.add_argument("--force", action="store_true",+ help="Publish even if the gate fails")+ parser.add_argument("--output-dir", default=settings.DOMAIN_MODERATION_MODEL_DIR)+ parser.add_argument(+ "--derived", action="store_true",+ help=("Add blocklist-derived rows for reason classes short of real data. Off by "+ "default: measured at 100 rows this drops real SPAM F1 from 0.839 to 0.688, "+ "and OFFENSIVE is already covered exactly by the blocklist check."))++ def handle(self, *args, **options):+ rows = training_data.real_rows()+ self.stdout.write(f"Real decided submissions usable for training: {len(rows)}")+ if not rows:+ self.stderr.write("No decided submissions to train on.")+ return++ rows += training_data.seed_rows()++ if options["derived"]:+ needed = self._reasons_needing_data(rows)+ if needed:+ self.stdout.write(f"Reason classes with too little real data: {sorted(needed)}")+ rows += training_data.derived_rows(+ needed, DERIVED_ROWS_PER_REASON,+ exclude={row.domain for row in rows})++ version = f"domain-mod-{date.today():%Y-%m-%d}"+ model, metrics = train(rows, version)+ self.stdout.write(json.dumps(metrics, indent=2))++ allowed, explanation = passes_gate(metrics, load_metrics())+ self.stdout.write(("PASS: " if allowed else "FAIL: ") + explanation)++ if options["dry_run"]:+ self.stdout.write("Dry run - artifact not written.")+ return+ if not allowed and not options["force"]:+ self.stderr.write("Gate failed; not publishing. Re-run with --force to override.")+ return++ self._publish(model, metrics, Path(options["output_dir"]))++ @staticmethod+ def _reasons_needing_data(rows) -> set[str]:+ counts: dict[str, int] = {}+ for row in rows:+ if row.source == training_data.REAL and row.rejected and row.reason:+ counts[row.reason] = counts.get(row.reason, 0) + 1+ return {reason for reason in DomainSubmission.DOMAIN_REJECTION_REASON+ if counts.get(reason, 0) < MIN_REAL_ROWS_PER_REASON}++ def _publish(self, model, metrics, output_dir: Path):+ import joblib++ output_dir.mkdir(parents=True, exist_ok=True)+ joblib.dump(model, output_dir / MODEL_FILENAME)+ (output_dir / METRICS_FILENAME).write_text(json.dumps(metrics, indent=2))+ self.stdout.write(self.style.SUCCESS(+ f"Wrote {model.version} to {output_dir / MODEL_FILENAME}"))++ reset_model_cache()+ rescore_pending_submissions(schedule=0)+ self.stdout.write("Scheduled a rescore of the pending queue with the new model.")diff --git a/mwmbl/migrations/0034_domainsubmission_suggested_reason_and_more.py b/mwmbl/migrations/0034_domainsubmission_suggested_reason_and_more.pynew file mode 100644index 0000000..873f50f--- /dev/null+++ b/mwmbl/migrations/0034_domainsubmission_suggested_reason_and_more.py@@ -0,0 +1,56 @@+# Generated by Django 5.2.13 on 2026-08-28 16:25++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('mwmbl', '0033_fix_domain_submission_names'),+ ]++ operations = [+ migrations.AddField(+ model_name='domainsubmission',+ name='suggested_reason',+ field=models.CharField(blank=True, max_length=20),+ ),+ migrations.AddField(+ model_name='domainsubmission',+ name='suggested_status',+ field=models.CharField(blank=True, max_length=20),+ ),+ migrations.AddField(+ model_name='domainsubmission',+ name='suggestion_confidence',+ field=models.FloatField(blank=True, null=True),+ ),+ migrations.AddField(+ model_name='domainsubmission',+ name='suggestion_model_version',+ field=models.CharField(blank=True, max_length=50),+ ),+ migrations.CreateModel(+ name='DomainEvidence',+ fields=[+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),+ ('domain', models.CharField(max_length=300, unique=True)),+ ('state', models.CharField(choices=[('PENDING', 'Queued for crawling'), ('READY', 'Crawled and scored'), ('FAILED', 'Crawling failed')], default='PENDING', max_length=20)),+ ('fetched_at', models.DateTimeField(blank=True, null=True)),+ ('http_status', models.IntegerField(blank=True, null=True)),+ ('final_domain', models.CharField(blank=True, max_length=300)),+ ('error', models.CharField(blank=True, max_length=100)),+ ('pages', models.JSONField(default=list)),+ ('signals', models.JSONField(default=dict)),+ ('suggested_action', models.CharField(blank=True, max_length=10)),+ ('suggested_reason', models.CharField(blank=True, max_length=20)),+ ('confidence', models.FloatField(blank=True, null=True)),+ ('review_priority', models.FloatField(blank=True, null=True)),+ ('evidence', models.JSONField(default=list)),+ ('model_version', models.CharField(blank=True, max_length=50)),+ ],+ options={+ 'indexes': [models.Index(fields=['state', '-review_priority'], name='mwmbl_domai_state_1c3406_idx'), models.Index(fields=['suggested_action', 'suggested_reason'], name='mwmbl_domai_suggest_68cee1_idx')],+ },+ ),+ ]diff --git a/mwmbl/models.py b/mwmbl/models.pyindex ee103d2..be37e9b 100644--- a/mwmbl/models.py+++ b/mwmbl/models.py@@ -106,6 +106,16 @@ class DomainSubmission(models.Model):rejection_reason = models.CharField(max_length=20, choices=[(k, v) for k, v in DOMAIN_REJECTION_REASON.items()], blank=True)rejection_detail = models.CharField(max_length=300, blank=True)+ # What the suggestion model was showing when the moderator made this decision. Deliberately+ # separate storage from the live suggestion on DomainEvidence: a retrain rewrites that row,+ # and sharing the columns would silently rewrite the record of what was actually on screen.+ # These are what let us measure whether the suggestions help, and de-bias the next retrain+ # against decisions that merely confirmed a suggestion.+ suggested_status = models.CharField(max_length=20, blank=True)+ suggested_reason = models.CharField(max_length=20, blank=True)+ suggestion_confidence = models.FloatField(null=True, blank=True)+ suggestion_model_version = models.CharField(max_length=50, blank=True)+def random_api_key():"""Kept for migration compatibility (0010_apikey references this by name)."""@@ -286,3 +296,53 @@ class SourceProvenance(models.Model):models.Index(fields=['source']),models.Index(fields=['timestamp']),]+++class DomainEvidence(models.Model):+ """Crawl evidence and the precomputed suggestion for a submitted domain.++ Both the moderator's detail panel and the suggestion model read these rows, so what the+ moderator is shown and what the model judged can never disagree. Everything here is+ computed by a background task at submission time: the moderation queue is a plain indexed+ read, with no inference on the request path.++ Keyed on the domain rather than the submission because domains get resubmitted - 615 of+ 6,949 distinct names in the last judgments export had more than one submission - and the+ crawl is about the domain, not about who asked for it.+ """++ class State(models.TextChoices):+ PENDING = "PENDING", "Queued for crawling"+ READY = "READY", "Crawled and scored"+ FAILED = "FAILED", "Crawling failed"++ domain = models.CharField(max_length=300, unique=True)+ state = models.CharField(max_length=20, choices=State.choices, default=State.PENDING)+ fetched_at = models.DateTimeField(null=True, blank=True)++ # Crawl results.+ http_status = models.IntegerField(null=True, blank=True)+ final_domain = models.CharField(max_length=300, blank=True) # after redirects+ error = models.CharField(max_length=100, blank=True) # RobotsDenied, AbortError, ...+ pages = models.JSONField(default=list) # [{url, status, title, extract}], up to 3+ signals = models.JSONField(default=dict) # derived: lang, has_links, ad_script_count, ...++ # Precomputed suggestion. The queue reads these columns; it never calls the model.+ suggested_action = models.CharField(max_length=10, blank=True) # APPROVE | REJECT | UNSURE+ suggested_reason = models.CharField(max_length=20, blank=True)+ confidence = models.FloatField(null=True, blank=True)+ # One number combining direction and confidence so "confident rejects and genuinely+ # uncertain rows first, obvious approvals last" is a single indexed ORDER BY. Sorting on+ # confidence alone cannot express that, because it is highest at both ends.+ review_priority = models.FloatField(null=True, blank=True)+ evidence = models.JSONField(default=list) # cached rule + model evidence items+ model_version = models.CharField(max_length=50, blank=True)++ class Meta:+ indexes = [+ models.Index(fields=["state", "-review_priority"]),+ models.Index(fields=["suggested_action", "suggested_reason"]),+ ]++ def __str__(self):+ return f"{self.domain} ({self.state})"diff --git a/mwmbl/moderation/__init__.py b/mwmbl/moderation/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/mwmbl/moderation/artifacts/README.md b/mwmbl/moderation/artifacts/README.mdnew file mode 100644index 0000000..9530121--- /dev/null+++ b/mwmbl/moderation/artifacts/README.md@@ -0,0 +1,42 @@+# Domain moderation model artifact++`model.joblib` is the trained approve/reject suggester; `metrics.json` is how it scored on+held-out real decisions when it was built. Both are committed deliberately, for the same reason+`super_search_select/artifacts/xgb` is: without an artifact the suggester degrades to the+deterministic checks alone, so shipping one means a fresh deploy is useful on day one instead of+after the first retrain.++## Regenerating++ uv run manage.py train_domain_moderation_model --dry-run # report metrics only+ uv run manage.py train_domain_moderation_model # publish if it passes the gate++The gate compares the new model's cold-start PR-AUC against the *lower bound* of the incumbent's+bootstrap interval in `metrics.json`, so a change that only looks like an improvement does not+ship. Publishing also schedules `rescore_pending_submissions`, which re-scores the existing queue+with the new model.++To reproduce the numbers without a production database, train from the sanitized judgments export+instead:++ uv run python scripts/moderation_eval.py++## What this version was trained on++The committed artifact comes from the judgments export, which carries no page text, so its+featuriser has **no text block** — it judges on the domain name, TLD and shape alone. Once+`backfill_domain_evidence` has crawled real submissions, a retrain picks up the titles and+extracts of the three crawled pages and the text block appears. Expect the first post-backfill+retrain to change the artifact substantially.++## Format++`joblib`, because the model is a fitted scikit-learn `TfidfVectorizer` vocabulary plus two+`LogisticRegression` heads, and ONNX export of a TF-IDF pipeline is far more trouble than it is+worth at this size. Two consequences worth knowing:++- Unpickling executes code, so this file is trusted exactly as much as the rest of the repo. Do+ not point `DOMAIN_MODERATION_MODEL_DIR` at a directory anyone else can write to.+- A scikit-learn upgrade can make an old pickle unloadable. `mwmbl.moderation.model` catches that+ and logs it rather than failing, falling back to the deterministic checks — so the symptom is+ "every suggestion says UNSURE", and the fix is a retrain.diff --git a/mwmbl/moderation/artifacts/metrics.json b/mwmbl/moderation/artifacts/metrics.jsonnew file mode 100644index 0000000..bb35c53--- /dev/null+++ b/mwmbl/moderation/artifacts/metrics.json@@ -0,0 +1,41 @@+{+ "all": {+ "slice": "all",+ "rows": 949,+ "positives": 89,+ "pr_auc": 0.3987,+ "pr_auc_ci": [+ 0.3007,+ 0.4949+ ],+ "recall_at_precision_75": 0.2135+ },+ "cold_start": {+ "slice": "cold_start",+ "rows": 150,+ "positives": 81,+ "pr_auc": 0.7788,+ "pr_auc_ci": [+ 0.6885,+ 0.8588+ ],+ "recall_at_precision_75": 0.4074+ },+ "reason_head": {+ "rows": 71,+ "f1": {+ "LANGUAGE": 0.0,+ "OTHER": 0.3448,+ "SPAM": 0.8288+ },+ "support": {+ "LANGUAGE": 2,+ "OTHER": 13,+ "SPAM": 56+ }+ },+ "train_rows_by_source": {+ "real": 2847,+ "seed": 21+ }+}diff --git a/mwmbl/moderation/artifacts/model.joblib b/mwmbl/moderation/artifacts/model.joblibnew file mode 100644index 0000000..0bc1e24Binary files /dev/null and b/mwmbl/moderation/artifacts/model.joblib differdiff --git a/mwmbl/moderation/evidence.py b/mwmbl/moderation/evidence.pynew file mode 100644index 0000000..4ea0e07--- /dev/null+++ b/mwmbl/moderation/evidence.py@@ -0,0 +1,157 @@+"""Crawl a submitted domain so a moderator - and the model - can see what is actually there.++Three pages, not one: a homepage alone is often a splash screen, and the reject reasons+moderators write ("obtrusive ads", "doesn't render anything/no links", "is search UI and bot+detection") are judgements about a site, not a page. The same three pages are shown in the+moderator's detail panel and fed to the model, so what a moderator sees and what the model+judged can never disagree.++This reuses mwmbl.crawler.retrieve.crawl_url, which already does robots.txt with Redis+caching, SSRF validation, a 3 second timeout, a 1 MB cap and justext extraction with Open+Graph fallbacks. Super Search already calls it from inside the server process, so nothing+here is a new capability - it is the existing crawler pointed at one domain.+"""+from __future__ import annotations++import time+from logging import getLogger+from urllib.parse import urlparse++from django.conf import settings+from django.utils import timezone++from mwmbl.crawler.env_vars import CRAWL_DELAY_SECONDS+from mwmbl.crawler.retrieve import crawl_url+from mwmbl.indexer.blacklist_snapshot import get_snapshot_blacklist+from mwmbl.models import DomainEvidence+from mwmbl.moderation import rules++logger = getLogger(__name__)++# Paths that tell you nothing about whether a site is worth crawling.+BORING_PATH_WORDS = ("privacy", "terms", "cookie", "legal", "login", "signin", "sign-in",+ "register", "cart", "checkout", "contact", "rss", "feed")++# Markers counted as signals for the moderator. Not model features - they are far too crude+# for that - but "we found 4 ad-network scripts" is a useful line in an evidence list, and+# moderators do reject for "obtrusive ads" and "paywall".+AD_MARKERS = ("googlesyndication", "doubleclick", "adsbygoogle", "adnxs", "taboola",+ "outbrain", "criteo", "media.net")+PAYWALL_MARKERS = ("paywall", "subscribe to continue", "subscribers only",+ "create a free account to")+++def crawl_domain(domain: str, redis, max_pages: int = None) -> dict:+ """Fetch up to ``max_pages`` pages of ``domain`` and derive the signals rules care about.++ Never raises: a domain that cannot be fetched is a *result* here, and one of the more+ informative ones, so failures come back as ``error`` rather than as an exception.+ """+ if max_pages is None:+ max_pages = settings.MODERATION_PAGES_PER_DOMAIN++ homepage = crawl_url(f"https://{domain}/", redis)+ pages = [_page(homepage)]+ error = (homepage.get("error") or {}).get("name", "") if homepage.get("error") else ""++ for url in _follow_up_urls(domain, homepage, max_pages - 1):+ if CRAWL_DELAY_SECONDS:+ time.sleep(CRAWL_DELAY_SECONDS)+ pages.append(_page(crawl_url(url, redis)))++ return {+ "http_status": homepage.get("status"),+ "final_domain": _final_domain(homepage, domain),+ "error": error,+ "pages": pages,+ "signals": _signals(domain, pages),+ }+++def store_evidence(domain: str, crawl: dict) -> DomainEvidence:+ """Persist a crawl and the checks derived from it, ready for the queue to read."""+ evidence, _ = DomainEvidence.objects.update_or_create(+ domain=domain,+ defaults={+ "state": DomainEvidence.State.READY,+ "fetched_at": timezone.now(),+ "http_status": crawl["http_status"],+ "final_domain": crawl["final_domain"],+ "error": crawl["error"],+ "pages": crawl["pages"],+ "signals": crawl["signals"],+ "evidence": [item.to_dict() for item in rules.crawl_evidence(domain, crawl)],+ },+ )+ return evidence+++def _page(result: dict) -> dict:+ content = result.get("content") or {}+ error = result.get("error") or {}+ return {+ "url": result.get("url", ""),+ "status": result.get("status"),+ "title": content.get("title", ""),+ "extract": content.get("extract", ""),+ "num_links": len(content.get("links") or []) + len(content.get("extra_links") or []),+ "error": error.get("name", ""),+ }+++def _follow_up_urls(domain: str, homepage: dict, limit: int) -> list[str]:+ """Pick further pages from the homepage's links: same site, shallow, not boilerplate.++ Shallow paths are preferred because a site's top-level sections say more about what it+ publishes than an arbitrary deep article does, and they are what a moderator would click.+ """+ if limit <= 0:+ return []+ content = homepage.get("content") or {}+ candidates = list(content.get("links") or []) + list(content.get("extra_links") or [])++ same_site = []+ for url in candidates:+ parsed = urlparse(url)+ if rules.registrable(parsed.netloc) != rules.registrable(domain):+ continue+ path = parsed.path.strip("/")+ if not path or any(word in path.lower() for word in BORING_PATH_WORDS):+ continue+ same_site.append(url)++ same_site.sort(key=lambda url: (urlparse(url).path.count("/"), len(url)))+ return same_site[:limit]+++def _final_domain(homepage: dict, domain: str) -> str:+ """The host we ended up on. crawl_url follows redirects and reports the URL it fetched."""+ final = urlparse(homepage.get("url") or "").netloc+ return final if final and final != domain else ""+++def _signals(domain: str, pages: list[dict]) -> dict:+ text = " ".join(f"{page['title']} {page['extract']}" for page in pages).lower()+ try:+ blacklisted = get_snapshot_blacklist().is_domain_blacklisted(domain)+ except Exception:+ # The snapshot lives in Redis and is rebuilt periodically; if it is not there yet this+ # is one missing evidence line, not a reason to fail the whole enrichment.+ logger.warning("Blacklist snapshot unavailable while enriching %s", domain)+ blacklisted = False++ return {+ "has_links": any(page["num_links"] for page in pages),+ "num_pages_fetched": sum(1 for page in pages if page["status"] and not page["error"]),+ "ad_markers": sum(marker in text for marker in AD_MARKERS),+ "paywall_markers": sum(marker in text for marker in PAYWALL_MARKERS),+ "blacklisted": blacklisted,+ }+++def page_texts(evidence: DomainEvidence | None) -> list[str]:+ """The text the model reads, in the same shape training built it from."""+ if evidence is None:+ return []+ return [f"{page.get('title', '')} {page.get('extract', '')}".strip()+ for page in (evidence.pages or [])]diff --git a/mwmbl/moderation/features.py b/mwmbl/moderation/features.pynew file mode 100644index 0000000..6d136ff--- /dev/null+++ b/mwmbl/moderation/features.py@@ -0,0 +1,146 @@+"""Featurisation for the domain moderation suggester.++One module builds the feature matrix for both training and serving, so the two cannot drift+apart - the classic way a model that scored well offline quietly stops working in production.++What is deliberately *not* here: liveness, redirects and blocklist membership. Those are+handled by mwmbl.moderation.rules as deterministic checks. Keeping them out of the learned+model avoids a training hazard - the crawl that produces evidence happens now, but the labels+were made up to two years ago, so a site that was live when it was approved in 2024 and is+dead today would teach the model "dead -> approve". The model only judges what is stable about+a domain: whether its name and its text read as spam, promotion or a non-English site.+"""+from __future__ import annotations++from dataclasses import dataclass, field+from logging import getLogger++import numpy as np+from scipy.sparse import csr_matrix, hstack+from sklearn.feature_extraction.text import TfidfVectorizer++logger = getLogger(__name__)++# Substrings that recur in the SEO/AI-slop domains moderators reject: aianimegenerator.cloud,+# seobacklinkhub.org, stepupsipcalculator.net, bestaitoolsforthat.com, collegetools.io.+SPAM_WORDS = [+ "ai", "seo", "generator", "calculator", "tool", "free", "best", "top", "online", "shop",+ "buy", "cheap", "review", "guide", "app", "hub", "pro", "download", "crypto",+]++# How much page text the model reads. Titles and extracts are already truncated by the+# crawler (65 and 155 chars), so three pages is a few hundred characters at most.+MAX_TEXT_CHARS = 2000++NUM_SHAPE_FEATURES = 8+# Shape features are raw counts; scaling them into roughly [0, 1] keeps the regularisation+# comparable across them and the TF-IDF blocks.+SHAPE_SCALE = 40.0+++@dataclass+class ModerationExample:+ """One thing to score: a domain, plus whatever page text we managed to crawl for it."""+ domain: str+ page_texts: list[str] = field(default_factory=list)++ @property+ def text(self) -> str:+ return " ".join(self.page_texts)[:MAX_TEXT_CHARS]+++def tld(domain: str) -> str:+ labels = domain.lower().split(".")+ return labels[-1] if len(labels) > 1 else ""+++def _tld_tokens(domain: str) -> list[str]:+ return [tld(domain)]+++def shape_features(domain: str) -> list[float]:+ host = domain.lower()+ labels = host.split(".")+ return [+ len(host),+ len(labels),+ sum(character.isdigit() for character in host),+ host.count("-"),+ float(host.startswith("www.")),+ len(labels[0]),+ sum(word in host for word in SPAM_WORDS),+ len(tld(domain)),+ ]+++class Featuriser:+ """Fits the vectorisers on a training set, then transforms anything the same way.++ Pickled whole as part of the model artifact, so serving uses the exact vocabulary that+ training saw rather than rebuilding one from different data.+ """++ def __init__(self):+ # char_wb over the domain: catches the morphology of generated spam names, and the+ # word-boundary variant keeps n-grams from spanning label boundaries.+ self.domain_chars = TfidfVectorizer(+ analyzer="char_wb", ngram_range=(2, 5), min_df=2, sublinear_tf=True)+ # The TLD earns its own block rather than being left to the char n-grams: .ai was 30/33+ # rejected and .org 24/1079, and that is a whole-token effect, not a substring one.+ self.tlds = TfidfVectorizer(+ analyzer="word", tokenizer=_tld_tokens, token_pattern=None, min_df=1)+ self.text = TfidfVectorizer(+ analyzer="word", ngram_range=(1, 2), min_df=2, sublinear_tf=True,+ strip_accents="unicode", lowercase=True)++ def fit_transform(self, examples: list[ModerationExample]) -> csr_matrix:+ domains = [example.domain for example in examples]+ blocks = [+ self.domain_chars.fit_transform(domains),+ self.tlds.fit_transform(domains),+ ]++ # Page text is optional, and often absent: the first training run happens before the+ # evidence backfill has crawled anything, and a domain that could not be fetched has+ # no text at all. min_df=2 then prunes the vocabulary to nothing, which sklearn+ # raises on - so a text block is only added when the text can actually support one.+ texts = [example.text for example in examples]+ try:+ blocks.append(self.text.fit_transform(texts))+ except ValueError:+ logger.info("Not enough page text to fit a text block over %d examples; "+ "the model will judge on the domain name alone", len(examples))+ self.text = None++ blocks.append(self._shape_block(examples))+ return hstack(blocks).tocsr()++ def transform(self, examples: list[ModerationExample]) -> csr_matrix:+ domains = [example.domain for example in examples]+ blocks = [+ self.domain_chars.transform(domains),+ self.tlds.transform(domains),+ ]+ if self.text is not None:+ blocks.append(self.text.transform([example.text for example in examples]))+ blocks.append(self._shape_block(examples))+ return hstack(blocks).tocsr()++ @staticmethod+ def _shape_block(examples: list[ModerationExample]) -> csr_matrix:+ shapes = np.array([shape_features(example.domain) for example in examples], dtype=float)+ return csr_matrix(shapes / SHAPE_SCALE)++ def feature_names(self) -> np.ndarray:+ """Feature labels in matrix order, for turning coefficients into moderator-facing text."""+ names = [+ self.domain_chars.get_feature_names_out(),+ np.array([f"tld={name}" for name in self.tlds.get_feature_names_out()]),+ ]+ if self.text is not None:+ names.append(np.array([f"text={name}"+ for name in self.text.get_feature_names_out()]))+ names.append(np.array([+ "len", "labels", "digits", "hyphens", "www", "sld_len", "spamwords", "tld_len",+ ]))+ return np.concatenate(names)diff --git a/mwmbl/moderation/model.py b/mwmbl/moderation/model.pynew file mode 100644index 0000000..199574b--- /dev/null+++ b/mwmbl/moderation/model.py@@ -0,0 +1,202 @@+"""The learned half of a moderation suggestion.++Two heads over the same features: will a moderator reject this, and if so, why. Both are+linear models over TF-IDF, which is the right size for the data - 375 real rejections will+not train anything larger - and costs well under a millisecond per prediction.++Where this runs matters. Predictions are made by the enrichment background task and stored on+DomainEvidence, so the moderation queue is a plain indexed database read and no web worker+ever loads this module. A missing or slow artifact therefore cannot touch a moderator's+request; the worst case is a queue row that honestly says it has not been assessed yet.++Loading mirrors mwmbl.tinysearchengine.super_search_select.judge: a lazy singleton behind a+lock, memoized failure, and graceful degradation to rules-only when the artifact is absent so+a deploy without it keeps working.+"""+from __future__ import annotations++import json+import threading+from dataclasses import dataclass, field+from logging import getLogger+from pathlib import Path+from typing import Optional++import numpy as np+from django.conf import settings++from mwmbl.moderation.features import Featuriser, ModerationExample+from mwmbl.moderation.rules import APPROVE, EvidenceItem, REJECT, decisive++logger = getLogger(__name__)++MODEL_FILENAME = "model.joblib"+METRICS_FILENAME = "metrics.json"++# A reason class with no real decisions behind it must not present as though it had. The+# reason head learns whatever classes the training data contains (reason_head.classes_ is the+# authority); this caps the ones that are not grounded in moderator decisions.+#+# OFFENSIVE is the only one today: there is exactly one real labelled example, so what it+# knows comes from the handful of hand-written seed rows. The stronger signal for that class+# is not learned at all - rules.py checks blocklist membership directly, exactly, at+# prediction time. See mwmbl.moderation.training_data for why that beats training on the+# same lists.+REASON_CONFIDENCE_CAP = {"OFFENSIVE": 0.6}+++@dataclass+class Suggestion:+ action: str # APPROVE | REJECT | UNSURE+ confidence: float+ reason: str = ""+ reason_confidence: float = 0.0+ reason_source: str = "model" # model | derived | rule+ model_version: str = ""+ evidence: list[dict] = field(default_factory=list)++ @property+ def review_priority(self) -> float:+ """Sort key for the queue: what most needs a human, first.++ Highest for confident rejects (someone should look, and probably agree), next for+ genuinely uncertain rows (only a human can settle them), lowest for confident+ approvals. Sorting on confidence alone cannot express this, because confidence is+ high at both ends of the scale.+ """+ if self.action == REJECT.upper():+ return 1.0 + self.confidence+ if self.action == APPROVE.upper():+ return 1.0 - self.confidence+ return 1.0+++class ModerationModel:+ """A fitted featuriser plus the two heads, pickled together as one artifact."""++ def __init__(self, featuriser: Featuriser, reject_head, reason_head, version: str):+ self.featuriser = featuriser+ self.reject_head = reject_head+ self.reason_head = reason_head+ self.version = version++ def predict(self, examples: list[ModerationExample]) -> list[tuple[float, str, float]]:+ """(reject probability, reason, reason probability) for each example, in one pass."""+ if not examples:+ return []+ features = self.featuriser.transform(examples)+ reject_probabilities = self.reject_head.predict_proba(features)[:, 1]++ reason_probabilities = self.reason_head.predict_proba(features)+ best = reason_probabilities.argmax(axis=1)+ reasons = self.reason_head.classes_[best]+ confidences = reason_probabilities[np.arange(len(examples)), best]++ return [+ (float(reject), str(reason), min(float(confidence),+ REASON_CONFIDENCE_CAP.get(str(reason), 1.0)))+ for reject, reason, confidence in zip(reject_probabilities, reasons, confidences)+ ]+++def suggest(domain: str, page_texts: list[str], evidence_items: list[EvidenceItem],+ model: Optional[ModerationModel] = None) -> Suggestion:+ """Compose a suggestion from the deterministic checks and, where they are silent, the model.++ A decisive check always wins. "Homepage returns 404" is not a matter of opinion, and+ letting a probability override it would produce exactly the suggestions a moderator learns+ to distrust.+ """+ if model is None:+ model = get_model()++ decisive_item = decisive(evidence_items)+ if decisive_item is not None:+ return Suggestion(+ action=decisive_item.implies_action,+ confidence=decisive_item.implies_confidence,+ reason=decisive_item.implies_reason,+ reason_confidence=decisive_item.implies_confidence,+ reason_source="rule",+ model_version=model.version if model else "",+ evidence=[item.to_dict() for item in evidence_items],+ )++ if model is None:+ # Rules-only degradation: say we don't know rather than inventing a default.+ return Suggestion(action="UNSURE", confidence=0.0, model_version="",+ evidence=[item.to_dict() for item in evidence_items])++ reject_probability, reason, reason_confidence = model.predict(+ [ModerationExample(domain, page_texts)])[0]++ if reject_probability >= settings.MODERATION_REJECT_THRESHOLD:+ action, confidence = "REJECT", reject_probability+ elif reject_probability <= settings.MODERATION_APPROVE_THRESHOLD:+ action, confidence = "APPROVE", 1.0 - reject_probability+ else:+ action, confidence = "UNSURE", 1.0 - abs(reject_probability - 0.5) * 2++ suggested_reason = reason if action == "REJECT" else ""+ return Suggestion(+ action=action,+ confidence=float(confidence),+ reason=suggested_reason,+ reason_confidence=reason_confidence if action == "REJECT" else 0.0,+ # Describes the reason actually being suggested, so a suggestion carrying no reason+ # is never labelled by whatever the reason head happened to rank first.+ reason_source="derived" if suggested_reason in REASON_CONFIDENCE_CAP else "model",+ model_version=model.version,+ evidence=[item.to_dict() for item in evidence_items],+ )+++_model: Optional[ModerationModel] = None+_load_attempted = False+_lock = threading.Lock()+++def get_model() -> Optional[ModerationModel]:+ """Lazily load the shared model; None (memoized) if the artifact is unavailable."""+ global _model, _load_attempted+ if _load_attempted:+ return _model+ with _lock:+ if _load_attempted:+ return _model+ _model = _load(Path(settings.DOMAIN_MODERATION_MODEL_DIR))+ _load_attempted = True+ return _model+++def reset_model_cache() -> None:+ """Drop the cached model so the next call reloads. Used after a retrain, and by tests."""+ global _model, _load_attempted+ with _lock:+ _model = None+ _load_attempted = False+++def _load(model_dir: Path) -> Optional[ModerationModel]:+ model_path = model_dir / MODEL_FILENAME+ if not model_path.exists():+ logger.warning(+ "Domain moderation model not found at %s; suggestions will use the deterministic "+ "checks only", model_path)+ return None+ try:+ import joblib+ model = joblib.load(model_path)+ except Exception:+ logger.exception("Failed to load the domain moderation model from %s", model_path)+ return None+ logger.info("Domain moderation model %s loaded from %s", model.version, model_path)+ return model+++def load_metrics(model_dir: Optional[Path] = None) -> dict:+ """The metrics written alongside the artifact, so the retrain gate can compare against it."""+ path = Path(model_dir or settings.DOMAIN_MODERATION_MODEL_DIR) / METRICS_FILENAME+ if not path.exists():+ return {}+ return json.loads(path.read_text())diff --git a/mwmbl/moderation/rules.py b/mwmbl/moderation/rules.pynew file mode 100644index 0000000..cc6dfc3--- /dev/null+++ b/mwmbl/moderation/rules.py@@ -0,0 +1,214 @@+"""Deterministic checks over crawl evidence.++These carry most of the weight in a suggestion, and they are the reason a moderator can act+without having to trust a probability: "Homepage returns 404" is checkable, "0.83" is not.+Of the 76 distinct rejection details moderators have written, roughly a third are dead,+expired or squatted domains and another handful are "redirects to somewhere else" - all of+which are facts about a fetch rather than judgements about content.++Two kinds of rule, split by whether the answer can change while the domain does not:++* :func:`crawl_evidence` depends only on the crawl, so it is computed once by the enrichment+ task and stored on DomainEvidence.+* :func:`live_evidence` depends on the database - the submitter's record, and whether this+ domain has since been decided elsewhere - so it is evaluated per request. Both are indexed+ reads, and caching them would mean showing a moderator a stale "first submission from this+ user" after that user's tenth submission.+"""+from __future__ import annotations++from dataclasses import asdict, dataclass+from logging import getLogger+from typing import Optional++logger = getLogger(__name__)++REJECT = "reject"+APPROVE = "approve"+NEUTRAL = "neutral"++# Domains we will not crawl whatever a submitter says, each of which has actually been+# submitted and rejected with a hand-written explanation ("don't crawl ourselves", "same as+# google.com no actual useful links apart from the search UI").+DO_NOT_CRAWL = frozenset({+ "mwmbl.org", "www.mwmbl.org",+ "google.com", "www.google.com", "scholar.google.com",+})++# Country TLDs that mostly carry non-English sites. This only ever produces a *neutral* "worth+# checking" line, never a rejection, because plenty of English sites live under .de and .nl -+# the reject-or-not call belongs to the model, whose TLD block learned .pt, .tw and .cn as+# reject-side features from actual decisions rather than from this list.+NON_ENGLISH_TLDS = frozenset({+ "cn", "tw", "jp", "kr", "ru", "ua", "pl", "cz", "sk", "hu", "ro", "bg", "gr", "tr",+ "pt", "es", "it", "fr", "de", "nl", "se", "no", "fi", "dk", "vn", "th", "id", "il", "ir",+})+++@dataclass(frozen=True)+class EvidenceItem:+ """One checkable fact, shown to the moderator as a line in the evidence list."""+ kind: str+ direction: str # REJECT | APPROVE | NEUTRAL+ label: str # moderator-facing, e.g. "Homepage returns 404"+ # Set when the fact is decisive on its own. The suggester takes the strongest of these+ # in preference to the model, because a 404 is not a matter of opinion.+ implies_action: Optional[str] = None+ implies_reason: str = ""+ implies_confidence: float = 0.0++ def to_dict(self) -> dict:+ return asdict(self)+++def crawl_evidence(domain: str, crawl: dict) -> list[EvidenceItem]:+ """Checks that depend only on the crawl. Stored on DomainEvidence by the enrichment task.++ ``crawl`` is the dict assembled by mwmbl.moderation.evidence.crawl_domain: http_status,+ final_domain, error, pages and signals.+ """+ items: list[EvidenceItem] = []+ pages = crawl.get("pages") or []+ signals = crawl.get("signals") or {}++ if domain in DO_NOT_CRAWL:+ items.append(EvidenceItem(+ "do_not_crawl", REJECT, "On the do-not-crawl list (we don't crawl ourselves, "+ "or it's another search engine)",+ implies_action="REJECT", implies_reason="OTHER", implies_confidence=0.99))++ error = crawl.get("error") or ""+ status = crawl.get("http_status")+ if error == "RobotsDenied":+ # Deliberately not decisive. It reads like a rejection but the record says otherwise:+ # lobste.rs disallows User-agent: * and was approved anyway, and not one of the 76+ # distinct rejection details moderators have written mentions robots.txt. The+ # crawler respects robots regardless of what is approved, so this is information a+ # moderator should have, not a decision to make for them.+ items.append(EvidenceItem(+ "robots", NEUTRAL,+ "robots.txt forbids our crawler - approving will not make this site crawlable"))+ elif error:+ items.append(EvidenceItem(+ "unreachable", REJECT, f"Could not be fetched ({error})",+ implies_action="REJECT", implies_reason="OTHER", implies_confidence=0.9))+ elif status is not None and not 200 <= status < 300:+ items.append(EvidenceItem(+ "http_status", REJECT, f"Homepage returns HTTP {status}",+ implies_action="REJECT", implies_reason="OTHER", implies_confidence=0.9))++ final_domain = crawl.get("final_domain") or ""+ if final_domain and registrable(final_domain) != registrable(domain):+ items.append(EvidenceItem(+ "redirect", REJECT, f"Redirects to {final_domain}",+ implies_action="REJECT", implies_reason="OTHER", implies_confidence=0.85))++ # Only meaningful when we actually got a page. After a failed or forbidden fetch there is+ # trivially no title and no text, and reporting three further "problems" would pad the+ # evidence list with restatements of the one fact that matters.+ fetched = bool(pages) and not error and status is not None and 200 <= status < 300+ if fetched and not any(page.get("title") for page in pages):+ items.append(EvidenceItem("no_title", REJECT, "No page on the site has a title"))+ if fetched and not any(page.get("extract") for page in pages):+ items.append(EvidenceItem(+ "no_extract", REJECT, "No readable body text found on any page"))+ if fetched and not signals.get("has_links"):+ items.append(EvidenceItem(+ "no_links", REJECT, "No links found to crawl on from the homepage"))++ # Language is left to the model rather than asserted here. crawl_url does not surface the+ # <html lang> attribute, and the one behavioural clue - justext finding no 'good'+ # paragraphs, which is why retrieve.py has an Open Graph fallback - fires just as readily+ # on a JavaScript-rendered English site. So: a hint for the moderator, and the model's TLD+ # block (which learned .pt, .tw and .cn as reject-side features) does the calling.+ if _tld(domain) in NON_ENGLISH_TLDS:+ items.append(EvidenceItem(+ "tld_language", NEUTRAL,+ f"Country domain (.{_tld(domain)}) - check the site is in English"))++ if signals.get("blacklisted"):+ # Strong evidence, but not decisive, and the reason is written down in+ # mwmbl.curated_domains: the remote lists are maintained for DNS ad-blocking and carry+ # false positives that are wrong for a search index - pudding.cool, contactmusic.com+ # and character.ai are all in The Block List Project's porn.txt. Overriding those is+ # precisely what an approval is *for*, so a decisive rejection here would have the+ # tool arguing against the mechanism it is supposed to be serving.+ items.append(EvidenceItem(+ "blocklist", REJECT,+ "On a public malware/adult blocklist - approving here also unblocks it. "+ "These lists are built for ad-blocking and do have false positives."))++ if fetched:+ items.append(EvidenceItem(+ "reachable", APPROVE,+ f"Crawled {sum(1 for page in pages if page.get('title'))} of {len(pages)} "+ f"page(s) successfully"))++ return items+++def live_evidence(submitter_record: dict, prior_decisions: dict) -> list[EvidenceItem]:+ """Checks whose answer changes without the domain changing, so never cached.++ ``submitter_record`` is {approved, rejected}; ``prior_decisions`` is {approved, rejected}+ for other submissions of the same domain.+ """+ items: list[EvidenceItem] = []++ approved = submitter_record.get("approved", 0)+ rejected = submitter_record.get("rejected", 0)+ total = approved + rejected+ if total == 0:+ # Worth saying plainly: on the last year of decisions, submissions from someone with no+ # track record were rejected 54% of the time, against 1% for established submitters.+ items.append(EvidenceItem(+ "submitter", NEUTRAL, "First submission from this user - no track record yet"))+ else:+ items.append(EvidenceItem(+ "submitter", APPROVE if rejected == 0 and approved >= 5 else NEUTRAL,+ f"Submitter has {approved} approved and {rejected} rejected"))++ if prior_decisions.get("approved"):+ items.append(EvidenceItem(+ "prior_decision", APPROVE, "This domain has already been approved before",+ implies_action="APPROVE", implies_confidence=0.9))+ elif prior_decisions.get("rejected"):+ items.append(EvidenceItem(+ "prior_decision", REJECT, "This domain has already been rejected before",+ implies_action="REJECT", implies_reason="OTHER", implies_confidence=0.9))++ return items+++def decisive(items: list[EvidenceItem]) -> Optional[EvidenceItem]:+ """The strongest self-evident item, if any. Overrides the model when present."""+ decisive_items = [item for item in items if item.implies_action]+ if not decisive_items:+ return None+ return max(decisive_items, key=lambda item: item.implies_confidence)+++def _tld(domain: str) -> str:+ labels = domain.lower().split(".")+ return labels[-1] if len(labels) > 1 else ""+++def registrable(domain: str) -> str:+ """Last two labels, so www.example.com and example.com compare equal.++ >>> registrable("www.example.com"), registrable("docs.example.com")+ ('example.com', 'example.com')++ Deliberately naive about multi-part suffixes: every .co.uk host collapses to "co.uk", so+ two unrelated .co.uk sites compare equal and a redirect between them is *not* reported.++ >>> registrable("example.co.uk") == registrable("somewhere-else.co.uk")+ True++ That is a missed evidence line rather than a wrong one, which is the direction to be wrong+ in here: the redirect check is decisive, so over-reporting would mean confidently+ rejecting a site for moving between its own subdomains. A public-suffix list would fix it+ properly and is not worth a dependency for this.+ """+ labels = domain.lower().removeprefix("www.").split(".")+ return ".".join(labels[-2:]) if len(labels) >= 2 else domain.lower()diff --git a/mwmbl/moderation/suggest.py b/mwmbl/moderation/suggest.pynew file mode 100644index 0000000..fabe619--- /dev/null+++ b/mwmbl/moderation/suggest.py@@ -0,0 +1,155 @@+"""Tie the checks and the model together, and put the answer where the queue can read it.++Two entry points, split by when they can be run:++:func:`refresh_suggestion` writes the cached suggestion onto a DomainEvidence row. It is+called by the enrichment task, the backfill command and the post-retrain rescore - never by a+request.++:func:`suggestion_for` reads that cached suggestion back and adds the evidence that would go+stale if it were cached: the submitter's record, and whether this domain has been decided+since. Both are indexed lookups.+"""+from __future__ import annotations++from logging import getLogger+from typing import Iterable++from django.db.models import Count, Q++from mwmbl.models import DomainEvidence, DomainSubmission+from mwmbl.moderation import rules+from mwmbl.moderation.evidence import page_texts+from mwmbl.moderation.model import Suggestion, suggest++logger = getLogger(__name__)+++def refresh_suggestion(evidence: DomainEvidence) -> DomainEvidence:+ """Recompute and store the suggestion for one already-crawled domain."""+ items = [rules.EvidenceItem(**item) for item in (evidence.evidence or [])]+ suggestion = suggest(evidence.domain, page_texts(evidence), items)++ evidence.suggested_action = suggestion.action+ evidence.suggested_reason = suggestion.reason+ evidence.confidence = suggestion.confidence+ evidence.review_priority = suggestion.review_priority+ evidence.model_version = suggestion.model_version+ evidence.evidence = suggestion.evidence+ evidence.save(update_fields=[+ "suggested_action", "suggested_reason", "confidence", "review_priority",+ "model_version", "evidence",+ ])+ return evidence+++def suggestion_for(submission: DomainSubmission,+ evidence: DomainEvidence | None,+ submitter: dict | None = None,+ prior: dict | None = None) -> Suggestion | None:+ """The stored suggestion, plus live evidence. None while the domain is still being crawled.++ Returning None rather than a default is deliberate: a queue row that says "not assessed+ yet" is honest, and a fabricated APPROVE at zero confidence is not.++ ``submitter`` and ``prior`` let a caller rendering many rows pass counts it has already+ aggregated, instead of paying two queries per row. See :func:`submitter_records` and+ :func:`prior_decision_counts`.+ """+ if evidence is None or evidence.state != DomainEvidence.State.READY:+ return None++ record = submitter if submitter is not None else submitter_record(submission.submitted_by_id)+ priors = prior if prior is not None else prior_decisions(submission)+ live = rules.live_evidence(record, priors)++ # A live check can be decisive even when the cached ones were not - most usefully "this+ # domain has already been approved before", which is true of 615 resubmitted domains.+ decisive_live = rules.decisive(live)+ cached = [rules.EvidenceItem(**item) for item in (evidence.evidence or [])]+ cached_decisive = rules.decisive(cached)+ if decisive_live is not None and (+ cached_decisive is None+ or decisive_live.implies_confidence > cached_decisive.implies_confidence):+ return Suggestion(+ action=decisive_live.implies_action,+ confidence=decisive_live.implies_confidence,+ reason=decisive_live.implies_reason,+ reason_confidence=decisive_live.implies_confidence,+ reason_source="rule",+ model_version=evidence.model_version,+ evidence=[item.to_dict() for item in cached] + [item.to_dict() for item in live],+ )++ action = evidence.suggested_action+ confidence = evidence.confidence or 0.0+ has_track_record = record["approved"] + record["rejected"] > 0+ if action == "APPROVE" and cached_decisive is None and not has_track_record:+ # Measured on held-out decisions: an APPROVE suggestion is wrong 44% of the time for a+ # submitter with no track record, and lowering the threshold does not rescue it (still+ # 28% wrong at 0.10). The cause is a prior shift, not a bad model - it is trained on a+ # population that rejects 11% and asked about one that rejects 54%, so a low reject+ # score means much less here than the number suggests. Rejections are unaffected+ # (precision 0.88 on this same slice), so only the approve side is withheld.+ action, confidence = "UNSURE", 0.0++ return Suggestion(+ action=action,+ confidence=confidence,+ reason=evidence.suggested_reason if action == "REJECT" else "",+ reason_confidence=confidence if action == "REJECT" else 0.0,+ reason_source="rule" if cached_decisive is not None else "model",+ model_version=evidence.model_version,+ evidence=list(evidence.evidence or []) + [item.to_dict() for item in live],+ )+++def submitter_record(user_id: int) -> dict:+ """How this submitter's previous submissions were decided.++ Worth its own query: on the last year of decisions, a submitter with no track record was+ rejected 54% of the time against 1% for an established one, which is a bigger effect than+ anything the model reads off the domain name.+ """+ counts = (DomainSubmission.objects+ .filter(submitted_by_id=user_id)+ .aggregate(approved=Count("pk", filter=Q(status="APPROVED")),+ rejected=Count("pk", filter=Q(status="REJECTED"))))+ return {"approved": counts["approved"] or 0, "rejected": counts["rejected"] or 0}+++def prior_decisions(submission: DomainSubmission) -> dict:+ """How other submissions of the same domain were decided."""+ counts = (DomainSubmission.objects+ .filter(name=submission.name)+ .exclude(pk=submission.pk)+ .aggregate(approved=Count("pk", filter=Q(status="APPROVED")),+ rejected=Count("pk", filter=Q(status="REJECTED"))))+ return {"approved": counts["approved"] or 0, "rejected": counts["rejected"] or 0}+++def submitter_records(user_ids: Iterable[int]) -> dict[int, dict]:+ """Decision counts for several submitters in one query, for rendering a queue page."""+ counts = (DomainSubmission.objects+ .filter(submitted_by_id__in=list(user_ids))+ .values("submitted_by_id")+ .annotate(approved=Count("pk", filter=Q(status="APPROVED")),+ rejected=Count("pk", filter=Q(status="REJECTED"))))+ return {row["submitted_by_id"]: {"approved": row["approved"], "rejected": row["rejected"]}+ for row in counts}+++def prior_decision_counts(names: Iterable[str]) -> dict[str, dict]:+ """Decision counts per domain name, for rendering a queue page in one query.++ Counts every decided submission of the name, including - unlike :func:`prior_decisions` -+ the row being rendered. That is harmless here because the queue only ever shows PENDING+ submissions, which are by definition not counted.+ """+ counts = (DomainSubmission.objects+ .filter(name__in=list(names))+ .values("name")+ .annotate(approved=Count("pk", filter=Q(status="APPROVED")),+ rejected=Count("pk", filter=Q(status="REJECTED"))))+ return {row["name"]: {"approved": row["approved"], "rejected": row["rejected"]}+ for row in counts}diff --git a/mwmbl/moderation/train.py b/mwmbl/moderation/train.pynew file mode 100644index 0000000..9bdad1d--- /dev/null+++ b/mwmbl/moderation/train.py@@ -0,0 +1,200 @@+"""Fit and evaluate the moderation suggester.++The evaluation is the point of this module, not the fitting. Two things about this data make+a naive accuracy number actively misleading:++* One prolific submitter accounts for 799 of the last 949 decisions at a 1% rejection rate,+ so an aggregate score is dominated by rows no model is needed for. Cold-start submitters -+ the 16% where a moderator is genuinely deciding something - reject at 54%, and that slice is+ what the gate reads.+* That slice has ~81 positives, where point estimates move around far more than they look+ like they do. Bootstrapping the augmentation experiment turned a 0.04 PR-AUC "improvement"+ into two intervals spanning 0.17 that overlapped almost entirely. So the gate compares+ intervals, and every metric is reported with one.+"""+from __future__ import annotations++from collections import Counter+from dataclasses import dataclass+from logging import getLogger+from typing import Optional++import numpy as np+from sklearn.linear_model import LogisticRegression+from sklearn.metrics import average_precision_score, f1_score, precision_recall_curve++from mwmbl.moderation.features import Featuriser+from mwmbl.moderation.model import ModerationModel+from mwmbl.moderation.training_data import REAL, TrainingRow++logger = getLogger(__name__)++TEST_FRACTION = 0.25+BOOTSTRAP_SAMPLES = 400+MIN_CLASS_ROWS = 5+++@dataclass+class Evaluation:+ slice_name: str+ rows: int+ positives: int+ pr_auc: float+ pr_auc_ci: tuple[float, float]+ recall_at_precision_75: float++ def to_dict(self) -> dict:+ return {+ "slice": self.slice_name,+ "rows": self.rows,+ "positives": self.positives,+ "pr_auc": round(self.pr_auc, 4),+ "pr_auc_ci": [round(self.pr_auc_ci[0], 4), round(self.pr_auc_ci[1], 4)],+ "recall_at_precision_75": round(self.recall_at_precision_75, 4),+ }+++def split_by_time(rows: list[TrainingRow]) -> tuple[list[TrainingRow], list[TrainingRow]]:+ """Time-ordered split of the real rows; derived and seed rows always go to training.++ Chronological rather than random because moderation drifts - the .ai spam wave is a 2026+ phenomenon that does not appear in 2024 - and a random split would let the model learn+ from the future it is being tested on.+ """+ real = sorted((row for row in rows if row.source == REAL),+ key=lambda row: row.timestamp or "")+ other = [row for row in rows if row.source != REAL]+ cut = int((1 - TEST_FRACTION) * len(real))+ return real[:cut] + other, real[cut:]+++def train(rows: list[TrainingRow], version: str) -> tuple[ModerationModel, dict]:+ """Fit both heads and evaluate on held-out real rows only."""+ train_rows, test_rows = split_by_time(rows)+ logger.info("Training on %d rows (%d real), testing on %d real rows",+ len(train_rows), sum(r.source == REAL for r in train_rows), len(test_rows))++ featuriser = Featuriser()+ features = featuriser.fit_transform([row.to_example() for row in train_rows])++ # The binary head sees real rows only: blanket augmentation was measured and did not help.+ real_mask = np.array([row.source == REAL for row in train_rows])+ reject_head = LogisticRegression(max_iter=4000, C=4.0, class_weight="balanced")+ reject_head.fit(features[real_mask],+ [row.rejected for row, keep in zip(train_rows, real_mask) if keep])++ # The reason head sees every source, because that is the whole point of the derived rows.+ reason_mask = np.array([row.rejected and bool(row.reason) for row in train_rows])+ reason_head = LogisticRegression(max_iter=4000, C=4.0, class_weight="balanced")+ reason_head.fit(features[reason_mask],+ [row.reason for row, keep in zip(train_rows, reason_mask) if keep])++ model = ModerationModel(featuriser, reject_head, reason_head, version)+ return model, evaluate(model, train_rows, test_rows)+++def evaluate(model: ModerationModel, train_rows: list[TrainingRow],+ test_rows: list[TrainingRow]) -> dict:+ if not test_rows:+ return {"error": "no held-out real rows to evaluate on"}++ predictions = model.predict([row.to_example() for row in test_rows])+ reject_scores = np.array([prediction[0] for prediction in predictions])+ truth = np.array([row.rejected for row in test_rows], dtype=int)++ # The slice that matters. One prolific submitter accounts for most decisions at a 1%+ # rejection rate, so an aggregate score mostly measures rows no model is needed for.+ # Submissions from an account with no track record in the training window reject at 54%,+ # and those are the ones a moderator is genuinely deciding.+ known_submitters = {row.submitter for row in train_rows if row.submitter}+ cold = np.array([row.submitter not in known_submitters for row in test_rows])++ slices = {"all": np.ones(len(test_rows), dtype=bool), "cold_start": cold}+ metrics = {+ name: _evaluate_slice(name, truth[mask], reject_scores[mask]).to_dict()+ for name, mask in slices.items()+ if _has_both_classes(truth[mask])+ }+ metrics["reason_head"] = _evaluate_reason_head(predictions, test_rows)+ metrics["train_rows_by_source"] = _count_sources(train_rows)+ return metrics+++def _evaluate_slice(name: str, truth: np.ndarray, scores: np.ndarray) -> Evaluation:+ generator = np.random.default_rng(0)+ samples = []+ for _ in range(BOOTSTRAP_SAMPLES):+ indices = generator.choice(len(truth), len(truth), replace=True)+ if _has_both_classes(truth[indices]):+ samples.append(average_precision_score(truth[indices], scores[indices]))++ precision, recall, _ = precision_recall_curve(truth, scores)+ return Evaluation(+ slice_name=name,+ rows=len(truth),+ positives=int(truth.sum()),+ pr_auc=float(average_precision_score(truth, scores)),+ pr_auc_ci=(float(np.percentile(samples, 2.5)) if samples else 0.0,+ float(np.percentile(samples, 97.5)) if samples else 0.0),+ recall_at_precision_75=max(+ (r for p, r in zip(precision, recall) if p >= 0.75 and r > 0), default=0.0),+ )+++def _evaluate_reason_head(predictions, test_rows: list[TrainingRow]) -> dict:+ """Per-reason F1 on the real rejections we held out.++ Per class rather than averaged, because the classes are not comparable: SPAM has 208 real+ examples behind it and OFFENSIVE has one. An average would let a collapse in the class+ that works be hidden by the class that never did.+ """+ truth, predicted = [], []+ for prediction, row in zip(predictions, test_rows):+ if row.rejected and row.reason:+ truth.append(row.reason)+ predicted.append(prediction[1])+ if not truth:+ return {"note": "no held-out real rejections with a reason"}++ labels = sorted(set(truth))+ scores = f1_score(truth, predicted, labels=labels, average=None, zero_division=0)+ counts = {label: truth.count(label) for label in labels}+ return {+ "rows": len(truth),+ "f1": {label: round(float(score), 4) for label, score in zip(labels, scores)},+ # Reported alongside the scores because the rare reasons are *very* rare in a+ # chronological split - LANGUAGE lands 2 rows in a typical test set - and an F1 of 0.0+ # on 2 rows is noise that reads like a broken class.+ "support": counts,+ }+++def _has_both_classes(truth: np.ndarray) -> bool:+ return truth.sum() >= MIN_CLASS_ROWS and (1 - truth).sum() >= MIN_CLASS_ROWS+++def _count_sources(rows: list[TrainingRow]) -> dict:+ return dict(Counter(row.source for row in rows))+++def passes_gate(new: dict, current: dict) -> tuple[bool, str]:+ """Whether a freshly trained model may replace the deployed one.++ The comparison is on the cold-start slice, and against the *lower* bound of the incumbent's+ interval rather than its point estimate. A gate on point estimates would have shipped the+ augmentation change that bootstrapping later showed to be noise.+ """+ new_cold = new.get("cold_start")+ if new_cold is None:+ return False, "no cold-start slice in the new metrics - not enough held-out data"++ current_cold = current.get("cold_start")+ if current_cold is None:+ return True, f"no incumbent to compare against; cold-start PR-AUC {new_cold['pr_auc']:.3f}"++ floor = current_cold["pr_auc_ci"][0]+ if new_cold["pr_auc"] < floor:+ return False, (f"cold-start PR-AUC {new_cold['pr_auc']:.3f} is below the incumbent's "+ f"lower bound {floor:.3f}")+ return True, (f"cold-start PR-AUC {new_cold['pr_auc']:.3f} "+ f"(incumbent {current_cold['pr_auc']:.3f}, lower bound {floor:.3f})")diff --git a/mwmbl/moderation/training_data.py b/mwmbl/moderation/training_data.pynew file mode 100644index 0000000..5d29ba9--- /dev/null+++ b/mwmbl/moderation/training_data.py@@ -0,0 +1,193 @@+"""Assemble the training set for the moderation suggester from three sources.++Every row carries its provenance, because the three are not interchangeable and the retrain+gate needs to vary them independently:++``real``+ Human decisions from DomainSubmission. The only source the binary reject head trains on,+ and the only source anything is ever *evaluated* on.++``derived``+ Public blocklists. Available but **off by default**, and the measurements are why.++ Blocklist data can genuinely teach a class from nothing: holding every real SPAM label+ out of the reason head and teaching SPAM only from HaGeZi domains recovered F1 0.58+ against 0.75 for real labels, from a standing start of zero. What it cannot do is share a+ classifier with a class that has real labels. Adding derived OFFENSIVE rows costs the+ real SPAM class badly, and there is no safe dose - even 100 rows takes SPAM F1 from 0.839+ to 0.688, and 2000 takes it to 0.532 - because adult domains and SEO-spam domains look+ alike in name space and the two classes end up competing.++ For OFFENSIVE specifically that trade is not worth making, because the list the labels+ would come from is *also available at prediction time*: the blacklist snapshot is already+ loaded and answers membership with a binary search, so rules.py checks it directly and+ gets an exact answer instead of a 0.58-F1 guess. Derived data is for a class whose source+ cannot be consulted at prediction time, and we do not currently have one.++ Blanket augmentation of the *binary* head was measured too, and did not survive+ bootstrapping (cold-start PR-AUC 0.777 -> 0.821 with CIs [0.686, 0.855] and [0.719,+ 0.896]), so it is not done either.++``seed``+ A small hand-written file covering concepts neither other source has - offensive content+ that is not adult content, the do-not-crawl cases, promotion of a paid product. It exists+ to cover concepts, not to move aggregate numbers.++Historic malformed submissions are excluded. 70 rows are ``null``, an IP address or+capitalised; migrations 0032/0033 fixed that at the API layer, so training on them would teach+the model to detect a problem that can no longer occur.+"""+from __future__ import annotations++import json+import random+from dataclasses import dataclass+from logging import getLogger+from pathlib import Path+from typing import Iterable, Optional++import requests++from mwmbl.indexer.blacklist_providers import (+ AdultContentBlacklistProvider, HaGeZiBlacklistProvider)+from mwmbl.models import DomainEvidence, DomainSubmission+from mwmbl.moderation.evidence import page_texts+from mwmbl.moderation.features import ModerationExample+from mwmbl.utils import VALID_DOMAIN_REGEX++logger = getLogger(__name__)++REAL = "real"+DERIVED = "derived"+SEED = "seed"++SEED_LABELS_PATH = Path(__file__).resolve().parents[2] / "devdata" / "moderation_seed_labels.jsonl"++# Blocklist entries are dominated by generated subdomains and tumblr blogs, which look nothing+# like a hand-typed submission; training on those would teach the model about the blocklist's+# shape rather than about spam. Apex-only, plausible length, no odd characters.+MAX_DERIVED_DOMAIN_LENGTH = 40+++@dataclass+class TrainingRow:+ domain: str+ rejected: bool+ reason: str # "" for approvals+ source: str # REAL | DERIVED | SEED+ page_texts: list[str]+ timestamp: Optional[str] = None+ # Who submitted it. Not a feature - the model deliberately does not read the submitter,+ # because a "trust this account" model is a reputation counter wearing a model's clothes.+ # It is here to *slice the evaluation*: submissions from an account with no track record+ # reject at 54% against 1% for an established one, and only the former needs a model at+ # all, so that is the slice the retrain gate reads. None for derived and seed rows, which+ # are training-only.+ submitter: Optional[str] = None++ def to_example(self) -> ModerationExample:+ return ModerationExample(self.domain, self.page_texts)+++def is_trainable_domain(domain: str) -> bool:+ """Reject the historic malformed names that the API no longer accepts."""+ return (bool(domain)+ and domain == domain.lower()+ and VALID_DOMAIN_REGEX.fullmatch(domain) is not None)+++def real_rows() -> list[TrainingRow]:+ """Decided submissions, joined to whatever page text has been crawled for them."""+ evidence_by_domain = {+ evidence.domain: evidence+ for evidence in DomainEvidence.objects.filter(state=DomainEvidence.State.READY)+ }++ rows = []+ submissions = (DomainSubmission.objects+ .filter(status__in=("APPROVED", "REJECTED"))+ .order_by("submitted_on"))+ for submission in submissions.iterator():+ if not is_trainable_domain(submission.name):+ continue+ rejected = submission.status == "REJECTED"+ rows.append(TrainingRow(+ domain=submission.name,+ rejected=rejected,+ reason=submission.rejection_reason if rejected else "",+ source=REAL,+ page_texts=page_texts(evidence_by_domain.get(submission.name)),+ timestamp=submission.submitted_on.isoformat() if submission.submitted_on else None,+ submitter=str(submission.submitted_by_id),+ ))+ return rows+++def derived_rows(reasons_needing_data: Iterable[str], per_reason: int,+ exclude: set[str], seed: int = 0) -> list[TrainingRow]:+ """Blocklist domains standing in for reason classes with too little real data.++ ``exclude`` must contain every domain that appears in the real data, in either split, so a+ derived row can never duplicate - or leak the label of - something we evaluate on.+ """+ sources = {+ "OFFENSIVE": AdultContentBlacklistProvider.URL,+ "SPAM": HaGeZiBlacklistProvider.HAGEZI_URLS["tif_mini"],+ }++ rows = []+ for reason in reasons_needing_data:+ url = sources.get(reason)+ if url is None:+ logger.warning("No derived data source for reason %s", reason)+ continue+ pool = [domain for domain in _fetch_apex_domains(url) if domain not in exclude]+ random.Random(seed).shuffle(pool)+ rows.extend(+ TrainingRow(domain=domain, rejected=True, reason=reason, source=DERIVED,+ page_texts=[])+ for domain in pool[:per_reason])+ logger.info("Derived %d %s rows from %s", min(per_reason, len(pool)), reason, url)+ return rows+++def seed_rows(path: Path = SEED_LABELS_PATH) -> list[TrainingRow]:+ """Hand-written examples covering concepts the other two sources miss."""+ if not path.exists():+ return []+ rows = []+ for line in path.read_text().splitlines():+ line = line.strip()+ if not line or line.startswith("#"):+ continue+ record = json.loads(line)+ rows.append(TrainingRow(+ domain=record["domain"],+ rejected=record["status"] == "REJECTED",+ reason=record.get("reason", ""),+ source=SEED,+ page_texts=[record["text"]] if record.get("text") else [],+ ))+ return rows+++def _fetch_apex_domains(url: str) -> list[str]:+ """Apex-only entries of a blocklist, in hosts or plain-domain format."""+ response = requests.get(url, timeout=120)+ response.raise_for_status()++ domains = []+ for line in response.text.split("\n"):+ line = line.split("#")[0].strip()+ if not line:+ continue+ parts = line.split()+ domain = (parts[1] if len(parts) >= 2 and parts[0] in ("0.0.0.0", "127.0.0.1")+ else parts[0])+ labels = domain.split(".")+ if len(labels) != 2 or len(domain) > MAX_DERIVED_DOMAIN_LENGTH:+ continue+ if not domain.replace("-", "").replace(".", "").isalnum():+ continue+ domains.append(domain)+ return domainsdiff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.pyindex 640a42f..059fa09 100644--- a/mwmbl/platform/api.py+++ b/mwmbl/platform/api.py@@ -6,7 +6,9 @@ from allauth.account.utils import setup_user_email, send_email_confirmationfrom django.conf import settingsfrom django.core import signingfrom django.core.exceptions import ValidationError+from django.db.models import F, OuterRef, Subqueryfrom django.utils import timezone+from redis import Redisfrom ninja import Routerfrom ninja.pagination import paginatefrom ninja_jwt.authentication import JWTAuth@@ -19,7 +21,13 @@ from mwmbl.exceptions import InvalidRequestfrom mwmbl.search_auth import invalidate_api_key_cache, invalidate_user_api_key_cachefrom mwmbl.utils import normalize_domain, validate_domainfrom mwmbl import pricing-from mwmbl.models import AgreementType, MwmblUser, DomainSubmission, SearchResultVote, ApiKey, UsageBucket, UserBilling, UserAgreement, MarketingConsent, MarketingSource, generate_username+from mwmbl.background import enrich_domain_submission+from mwmbl.crawler.stats import StatsManager+from mwmbl.models import AgreementType, MwmblUser, DomainEvidence, DomainSubmission, SearchResultVote, ApiKey, UsageBucket, UserBilling, UserAgreement, MarketingConsent, MarketingSource, generate_username+from mwmbl.moderation.suggest import (+ prior_decision_counts, prior_decisions, submitter_record, submitter_records,+ suggestion_for,+)from mwmbl.platform.schemas import (Registration, ConfirmEmail, DomainSubmissionSchema, UpdateDomainSubmission,VoteRequest, VoteRemoveRequest, VoteStatsRequest, VoteResponse, VoteStats, UserVoteHistory,@@ -28,6 +36,7 @@ from mwmbl.platform.schemas import (ForgotPasswordRequest, ResetPasswordRequest,AgreementAcceptRequest, AgreementResponse,MarketingConsentRequest, MarketingConsentResponse, MarketingConsentListResponse,+ BulkDecisionRequest, ModerationQueue, QueueItemSchema, SubmissionDetailSchema,)logger = logging.getLogger(__name__)@@ -239,13 +248,241 @@ def update_submission_status(request, submission_id: int, update_submission: Updif not request.user.has_perm("mwmbl.change_domain_submission_status"):raise InvalidRequest("You do not have permission to update this submission.")- submission.status = update_submission.status- submission.rejection_reason = update_submission.rejection_reason- submission.rejection_detail = update_submission.rejection_detail- submission.save()+ apply_decision(submission, update_submission, request.user)return {"status": "ok", "message": "Submission updated."}+def apply_decision(submission: DomainSubmission, decision, user) -> None:+ """Record a moderator's decision, along with the suggestion they were shown.++ The suggestion fields are an audit trail, not a copy of the live one on DomainEvidence: a+ retrain rewrites that row, and we need to keep what was actually on screen so the effect+ of the suggestions on decisions stays measurable.+ """+ submission.status = decision.status+ submission.rejection_reason = decision.rejection_reason+ submission.rejection_detail = decision.rejection_detail+ submission.status_changed_by = user+ submission.status_changed_on = timezone.now()+ submission.suggested_status = decision.suggested_status or ""+ submission.suggested_reason = decision.suggested_reason or ""+ submission.suggestion_confidence = decision.suggestion_confidence+ submission.suggestion_model_version = decision.suggestion_model_version or ""+ submission.save()+++def check_moderator(request):+ if not request.user.has_perm("mwmbl.change_domain_submission_status"):+ raise InvalidRequest("You do not have permission to moderate domain submissions.",+ status=403)+++ "/domain-submissions/queue",+ auth=JWTAuth(),+ response=ModerationQueue,+ summary="The moderation queue",+ description=(+ "Domain submissions awaiting review, with the suggestion for each one. "+ "Requires the `change_domain_submission_status` permission.\n\n"+ "Suggestions are precomputed when a domain is submitted, so this endpoint runs no "+ "model: filtering, ordering and pagination all happen in the database. A submission "+ "whose domain is still being crawled comes back with `evidence_state` of `PENDING` "+ "and no suggestion, rather than a placeholder.\n\n"+ "`order_by=needs_review` (the default) puts confident rejections first, then rows the "+ "tool is unsure about, then confident approvals, and finally submissions that have "+ "not been crawled yet. `oldest` and `confidence` are also accepted."+ ),+)+def get_moderation_queue(+ request,+ limit: int = 50,+ offset: int = 0,+ order_by: str = "needs_review",+ suggested_action: str = None,+ suggested_reason: str = None,+ submitted_by: int = None,+ min_confidence: float = None,+) -> dict:+ check_moderator(request)++ # DomainEvidence is keyed on the domain name rather than by a foreign key, because domains+ # get resubmitted and the crawl belongs to the domain. A correlated subquery joins them+ # without one, and keeps the filtering, ordering and slicing in SQL - which is the whole+ # reason suggestions are precomputed. Building the list in Python would mean materialising+ # every pending submission (there are ~4,000) on every request.+ evidence = DomainEvidence.objects.filter(domain=OuterRef("name"))+ submissions = (DomainSubmission.objects+ .filter(status="PENDING")+ # Prefixed because DomainSubmission already has suggested_status and+ # suggested_reason columns - the audit of what a moderator was shown -+ # and an annotation may not shadow a real field.+ .annotate(+ evidence_state=Subquery(evidence.values("state")[:1]),+ evidence_action=Subquery(evidence.values("suggested_action")[:1]),+ evidence_reason=Subquery(evidence.values("suggested_reason")[:1]),+ evidence_confidence=Subquery(evidence.values("confidence")[:1]),+ evidence_priority=Subquery(evidence.values("review_priority")[:1]),+ ))++ if submitted_by is not None:+ submissions = submissions.filter(submitted_by_id=submitted_by)+ if suggested_action:+ submissions = submissions.filter(evidence_action=suggested_action)+ if suggested_reason:+ submissions = submissions.filter(evidence_reason=suggested_reason)+ if min_confidence is not None:+ submissions = submissions.filter(evidence_confidence__gte=min_confidence)++ submissions = submissions.order_by(*_queue_ordering(order_by))++ count = submissions.count()+ page = list(submissions[offset:offset + limit])+ return {"items": _queue_items(page), "count": count}+++# Uncrawled rows sort last under every ordering: they are not more urgent than a confident+# rejection, and a moderator can do nothing with one until the crawl lands.+QUEUE_ORDERINGS = {+ "oldest": ("submitted_on",),+ "confidence": (F("evidence_confidence").desc(nulls_last=True), "submitted_on"),+ "needs_review": (F("evidence_priority").desc(nulls_last=True), "submitted_on"),+}+++def _queue_ordering(order_by: str):+ return QUEUE_ORDERINGS.get(order_by, QUEUE_ORDERINGS["needs_review"])+++def _queue_items(submissions: list[DomainSubmission]) -> list[QueueItemSchema]:+ """Build the page's rows, aggregating the live checks across the page rather than per row."""+ evidence_by_domain = {row.domain: row for row in DomainEvidence.objects.filter(+ domain__in=[submission.name for submission in submissions])}+ submitters = submitter_records({submission.submitted_by_id for submission in submissions})+ priors = prior_decision_counts({submission.name for submission in submissions})++ empty = {"approved": 0, "rejected": 0}+ items = []+ for submission in submissions:+ evidence = evidence_by_domain.get(submission.name)+ suggestion = suggestion_for(+ submission, evidence,+ submitter=submitters.get(submission.submitted_by_id, empty),+ prior=priors.get(submission.name, empty))+ items.append(QueueItemSchema(+ id=submission.id,+ name=submission.name,+ submitted_by=submission.submitted_by_id,+ submitted_on=submission.submitted_on,+ status=submission.status,+ evidence_state=evidence.state if evidence else "PENDING",+ suggestion=suggestion.__dict__ if suggestion else None,+ ))+ return items+++ "/domain-submissions/ids/{submission_id}",+ auth=JWTAuth(),+ response=SubmissionDetailSchema,+ summary="Everything needed to decide one submission",+ description=(+ "The submission, the pages crawled from the domain, the evidence behind the "+ "suggestion, the submitter's track record and any earlier decisions on the same "+ "domain. Requires the `change_domain_submission_status` permission."+ ),+)+def get_submission_detail(request, submission_id: int) -> SubmissionDetailSchema:+ check_moderator(request)++ submission = DomainSubmission.objects.filter(id=submission_id).first()+ if submission is None:+ raise InvalidRequest("Submission not found.", status=404)++ evidence = DomainEvidence.objects.filter(domain=submission.name).first()+ suggestion = suggestion_for(submission, evidence)+ return SubmissionDetailSchema(+ id=submission.id,+ name=submission.name,+ submitted_by=submission.submitted_by_id,+ submitted_on=submission.submitted_on,+ status=submission.status,+ rejection_reason=submission.rejection_reason,+ rejection_detail=submission.rejection_detail,+ evidence_state=evidence.state if evidence else "PENDING",+ suggestion=suggestion.__dict__ if suggestion else None,+ pages=evidence.pages if evidence else [],+ signals=evidence.signals if evidence else {},+ submitter_record=submitter_record(submission.submitted_by_id),+ prior_decisions=prior_decisions(submission),+ index_stats=_index_stats(submission.name),+ )+++ "/domain-submissions/decisions",+ auth=JWTAuth(),+ summary="Record several moderation decisions at once",+ description=(+ "Submit a screenful of individually-made decisions in one request. Each entry carries "+ "its own status, so this cannot be used to accept every suggestion in bulk - a "+ "moderator still decides each submission. "+ "Requires the `change_domain_submission_status` permission."+ ),+)+def submit_decisions(request, decisions: BulkDecisionRequest):+ check_email_verified(request)+ check_moderator(request)++ submissions = {submission.id: submission for submission in DomainSubmission.objects.filter(+ id__in=[decision.submission_id for decision in decisions.decisions])}++ updated, missing = 0, []+ for decision in decisions.decisions:+ submission = submissions.get(decision.submission_id)+ if submission is None:+ missing.append(decision.submission_id)+ continue+ apply_decision(submission, decision, request.user)+ updated += 1++ return {"status": "ok", "updated": updated, "not_found": missing}+++ "/domain-submissions/ids/{submission_id}/refetch",+ auth=JWTAuth(),+ summary="Re-crawl a submitted domain",+ description=(+ "Queue a fresh crawl of the domain and recompute its suggestion - for when a site was "+ "simply down when it was first checked. "+ "Requires the `change_domain_submission_status` permission."+ ),+)+def refetch_submission_evidence(request, submission_id: int):+ check_moderator(request)++ submission = DomainSubmission.objects.filter(id=submission_id).first()+ if submission is None:+ raise InvalidRequest("Submission not found.", status=404)++ # Clearing the row is what makes the crawl actually happen: the task skips domains whose+ # evidence is still fresh, which is the behaviour a re-fetch is asking to override.+ DomainEvidence.objects.filter(domain=submission.name).delete()+ enrich_domain_submission(submission.name)+ return {"status": "ok", "message": f"Queued a re-crawl of {submission.name}."}+++def _index_stats(domain: str) -> dict:+ """What the crawler already knows about this domain, when Redis is reachable."""+ try:+ manager = StatsManager(Redis.from_url(settings.REDIS_URL, decode_responses=True))+ return manager.get_stats_for_domain(domain).__dict__+ except Exception:+ logger.warning("Could not read index stats for %s", domain, exc_info=True)+ return {}++@router.post("/search-results/vote",auth=JWTAuth(),diff --git a/mwmbl/platform/schemas.py b/mwmbl/platform/schemas.pyindex c7efcc3..6db74d2 100644--- a/mwmbl/platform/schemas.py+++ b/mwmbl/platform/schemas.py@@ -176,6 +176,106 @@ class UpdateDomainSubmission(ModelSchema):model = DomainSubmissionfields = ["status", "rejection_reason", "rejection_detail"]+ # Echoed back by the client so we record what the moderator was actually looking at.+ # Optional: a client that shows no suggestions simply omits them, and a decision made+ # without a suggestion is stored as exactly that rather than as a suggestion of "".+ suggested_status: Optional[str] = Field(+ default=None, description="The action the tool suggested, as shown to the moderator.")+ suggested_reason: Optional[str] = Field(+ default=None, description="The rejection reason the tool suggested, if any.")+ suggestion_confidence: Optional[float] = Field(+ default=None, description="Confidence of the suggestion that was shown.")+ suggestion_model_version: Optional[str] = Field(+ default=None, description="Version of the model that produced the shown suggestion.")+++class EvidenceItemSchema(Schema):+ """One checkable fact behind a suggestion."""+ kind: str = Field(description="Machine-readable check name, e.g. `http_status`.")+ direction: str = Field(description="`reject`, `approve` or `neutral`.")+ label: str = Field(description="Moderator-facing text, e.g. 'Homepage returns HTTP 404'.")+++class SuggestionSchema(Schema):+ action: str = Field(description="`APPROVE`, `REJECT` or `UNSURE`.")+ confidence: float+ reason: str = Field(default="", description="Rejection reason; empty unless action is REJECT.")+ reason_confidence: float = 0.0+ reason_source: str = Field(+ default="model",+ description=(+ "`rule` when a deterministic check decided it, `model` when the classifier did, "+ "`derived` when the reason class is learned from public blocklists rather than "+ "from moderator decisions and should be treated as a weaker hint."+ ),+ )+ model_version: str = ""+ evidence: list[EvidenceItemSchema] = []+++class CrawledPageSchema(Schema):+ url: str+ status: Optional[int] = None+ title: str = ""+ extract: str = ""+ num_links: int = 0+ error: str = ""+++class QueueItemSchema(Schema):+ """A row of the moderation queue: the submission plus its precomputed suggestion."""+ id: int+ name: str+ submitted_by: int+ submitted_on: datetime+ status: str+ evidence_state: str = Field(+ description="`PENDING` while the domain is still being crawled, then `READY` or `FAILED`.")+ suggestion: Optional[SuggestionSchema] = Field(+ default=None,+ description="Absent until the domain has been crawled. Never a placeholder.")+++class SubmissionDetailSchema(Schema):+ """Everything a moderator needs to decide one submission."""+ id: int+ name: str+ submitted_by: int+ submitted_on: datetime+ status: str+ rejection_reason: str = ""+ rejection_detail: str = ""+ evidence_state: str+ suggestion: Optional[SuggestionSchema] = None+ pages: list[CrawledPageSchema] = []+ signals: dict = {}+ submitter_record: dict = Field(+ default={}, description="Counts of this submitter's previously approved/rejected domains.")+ prior_decisions: dict = Field(+ default={}, description="Counts of earlier decisions on this same domain.")+ index_stats: dict = Field(+ default={}, description="What the crawler already knows about this domain.")+++class BulkDecision(Schema):+ submission_id: int+ status: str+ rejection_reason: str = ""+ rejection_detail: str = ""+ suggested_status: Optional[str] = None+ suggested_reason: Optional[str] = None+ suggestion_confidence: Optional[float] = None+ suggestion_model_version: Optional[str] = None+++class BulkDecisionRequest(Schema):+ """A screenful of individually-made decisions, sent in one request.++ Deliberately not "accept all suggestions": each entry carries its own status, so the+ client can only send choices a moderator actually made.+ """+ decisions: list[BulkDecision]+class VoteRequest(Schema):"""Request schema for voting on search results."""@@ -277,3 +377,10 @@ class UserVoteHistory(Schema):description="When the vote was cast",example="2024-01-15T10:30:00Z")+++class ModerationQueue(Schema):+ """A page of the moderation queue. Shape matches the paginated endpoints the client+ already consumes, so `items`/`count` need no special handling."""+ items: list[QueueItemSchema]+ count: intdiff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.pyindex 41fa02c..b04cd28 100644--- a/mwmbl/settings_common.py+++ b/mwmbl/settings_common.py@@ -351,3 +351,23 @@ EXTERNAL_CACHE_TTL_SECONDS = 26 * 7 * 24 * 60 * 60 # 6 months; the disk cache k# A query a provider has nothing for is worth remembering too, or it is re-fetched forever.# Shorter, because a result appearing is a likelier change than an existing one moving.EXTERNAL_CACHE_NEGATIVE_TTL_SECONDS = 7 * 24 * 60 * 60++# Domain moderation suggestions. The model is loaded only by the background worker that+# enriches submissions - the queue reads the stored suggestion - so a missing artifact+# degrades to the deterministic checks rather than affecting any moderator request.+DOMAIN_MODERATION_MODEL_DIR = os.environ.get(+ "DOMAIN_MODERATION_MODEL_DIR",+ str(Path(__file__).parent / "moderation" / "artifacts"))+MODERATION_PAGES_PER_DOMAIN = 3 # homepage plus two, shown to the moderator and read by the model+# Both measured on held-out decisions rather than picked as round numbers. At 0.75 a suggested+# rejection is right 81% of the time overall and 88% for submitters with no track record; at+# 0.25 a suggested approval is wrong 6% of the time overall. Between the two the suggestion is+# UNSURE, which the queue surfaces as needing a human.+#+# The approve side is *also* withheld entirely for submitters with no track record, where it+# would otherwise be wrong 44% of the time - see mwmbl.moderation.suggest. That, rather than+# these two numbers, is where the asymmetry between approving and rejecting lives.+MODERATION_REJECT_THRESHOLD = 0.75+MODERATION_APPROVE_THRESHOLD = 0.25+MODERATION_EVIDENCE_MAX_AGE_DAYS = 30 # refetch rather than reuse evidence older than this+MODERATION_RETRAIN_INTERVAL_SECONDS = 30 * 24 * 60 * 60 # monthly; the gate guards each publishdiff --git a/mwmbl/signals.py b/mwmbl/signals.pyindex 7980e7a..16a4791 100644--- a/mwmbl/signals.py+++ b/mwmbl/signals.py@@ -1,10 +1,15 @@"""Signal receivers. Connected from MwmblConfig.ready().-Only one so far: approving a domain submission has to reach the blacklist snapshot, because-approved domains are subtracted from the remote lists when the snapshot is built rather than-checked per query (see mwmbl.indexer.blacklist_snapshot). Without this an approval would sit-inert for up to BLACKLIST_SNAPSHOT_REFRESH_SECONDS - six hours - and the moderator would-reasonably conclude it had not worked.+Both of them are about a domain submission reaching work that happens elsewhere:++* Approving one has to reach the blacklist snapshot, because approved domains are subtracted+ from the remote lists when the snapshot is built rather than checked per query (see+ mwmbl.indexer.blacklist_snapshot). Without this an approval would sit inert for up to+ BLACKLIST_SNAPSHOT_REFRESH_SECONDS - six hours - and the moderator would reasonably+ conclude it had not worked.+* Creating one has to reach the moderation crawler, so that by the time a moderator opens the+ queue the domain has already been fetched and scored. Doing that work on their request+ instead would put three page fetches in front of every row."""from datetime import timedeltafrom logging import getLogger@@ -23,6 +28,22 @@ logger = getLogger(__name__)BLACKLIST_SNAPSHOT_TASK = "mwmbl.background.refresh_blacklist_snapshot"+@receiver(post_save, sender=DomainSubmission)+def enrich_new_submission(sender, instance: DomainSubmission, created: bool, **kwargs):+ """Crawl a newly submitted domain so the moderation queue has a suggestion waiting.++ Only on creation: a moderator saving a decision must not trigger a re-crawl. The task+ itself skips domains whose evidence is still fresh, so a resubmitted domain costs nothing.+ """+ if not created:+ return++ from mwmbl.background import enrich_domain_submission++ enrich_domain_submission(instance.name)+ logger.info("Scheduled moderation enrichment for %s", instance.name)++@receiver(post_save, sender=DomainSubmission)def rebuild_blacklist_snapshot_on_approval(sender, instance: DomainSubmission, **kwargs):"""Schedule a snapshot rebuild when a submission is approved.diff --git a/scripts/moderation_eval.py b/scripts/moderation_eval.pynew file mode 100644index 0000000..031479a--- /dev/null+++ b/scripts/moderation_eval.py@@ -0,0 +1,86 @@+#!/usr/bin/env python3+"""Reproduce the domain moderation model's offline numbers without a production database.++The management command trains from DomainSubmission; this trains the same way from the+sanitized judgments export, so the evaluation is reproducible on a laptop and in CI.++ uv run python scripts/moderation_eval.py+ uv run python scripts/moderation_eval.py --derived 2000 # needs network++Reports every metric with a bootstrap interval. That is not decoration: the cold-start slice+has ~80 positives, and the augmentation experiment that motivated the derived-data design+produced a 0.04 PR-AUC "gain" whose interval spanned 0.17.+"""+import argparse+import gzip+import json+import os+import sys+from pathlib import Path++os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mwmbl.settings_dev")++import django++django.setup()++from mwmbl.moderation.train import train # noqa: E402+from mwmbl.moderation.training_data import ( # noqa: E402+ REAL, TrainingRow, is_trainable_domain, derived_rows, seed_rows)++DEFAULT_EXPORT = Path("devdata/judgments_export/domains.jsonl.gz")+++def rows_from_export(path: Path) -> list[TrainingRow]:+ rows = []+ for line in gzip.open(path, "rt"):+ record = json.loads(line)+ if record["status"] not in ("APPROVED", "REJECTED"):+ continue+ if not is_trainable_domain(record["domain"]):+ continue+ rejected = record["status"] == "REJECTED"+ rows.append(TrainingRow(+ domain=record["domain"],+ rejected=rejected,+ reason=record.get("rejection_reason") or "" if rejected else "",+ source=REAL,+ # The export carries no page text: it predates the evidence crawl. So this+ # measures the domain-name-only floor, which is what the model falls back to for+ # any submission whose crawl failed.+ page_texts=[],+ timestamp=record["timestamp"],+ submitter=record.get("user"),+ ))+ return rows+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--export", type=Path, default=DEFAULT_EXPORT)+ parser.add_argument("--derived", type=int, default=0,+ help="Blocklist rows per under-represented reason (0 = skip the fetch)")+ parser.add_argument("--no-seed", action="store_true")+ options = parser.parse_args()++ if not options.export.exists():+ print(f"No export at {options.export}", file=sys.stderr)+ return 1++ rows = rows_from_export(options.export)+ print(f"real rows: {len(rows)} "+ f"({sum(row.rejected for row in rows)} rejected)")++ if not options.no_seed:+ rows += seed_rows()+ if options.derived:+ rows += derived_rows(["OFFENSIVE"], options.derived,+ exclude={row.domain for row in rows})++ _, metrics = train(rows, "offline-eval")+ print(json.dumps(metrics, indent=2))+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/test/test_domain_moderation.py b/test/test_domain_moderation.pynew file mode 100644index 0000000..176693d--- /dev/null+++ b/test/test_domain_moderation.py@@ -0,0 +1,510 @@+"""Tests for the domain moderation suggester and the moderator queue API.++The load-bearing property here is not that the model is accurate - that is measured offline by+the training gate - but that a moderator is never shown something misleading: a suggestion is+either backed by evidence or absent, a deterministic check always beats a probability, and the+queue never runs a model on the request path.+"""+from datetime import timedelta+from unittest import mock++import pytest+from allauth.account.models import EmailAddress+from django.contrib.auth.models import Permission+from django.utils import timezone+from ninja_jwt.tokens import RefreshToken++from mwmbl.models import DomainEvidence, DomainSubmission, MwmblUser+from mwmbl.moderation import rules+from mwmbl.moderation.features import Featuriser, ModerationExample+from mwmbl.moderation.model import Suggestion, suggest+from mwmbl.moderation.suggest import refresh_suggestion, suggestion_for+from mwmbl.moderation.train import passes_gate+from mwmbl.moderation.training_data import TrainingRow, is_trainable_domain++QUEUE_URL = "/api/v1/platform/domain-submissions/queue"+++def submitter(db):+ return MwmblUser.objects.create_user(+ username="submitter", email="[email protected]", password="password")+++def moderator(db):+ user = MwmblUser.objects.create_user(+ username="moderator", email="[email protected]", password="password")+ EmailAddress.objects.create(user=user, email=user.email, verified=True, primary=True)+ user.user_permissions.add(+ Permission.objects.get(codename="change_domain_submission_status"))+ return user+++def token(user):+ return f"Bearer {RefreshToken.for_user(user).access_token}"+++def ready_evidence(domain, **overrides):+ defaults = {+ "state": DomainEvidence.State.READY,+ "fetched_at": timezone.now(),+ "http_status": 200,+ "pages": [{"url": f"https://{domain}/", "status": 200, "title": "A title",+ "extract": "Some body text", "num_links": 12, "error": ""}],+ "signals": {"has_links": True, "num_pages_fetched": 1, "blacklisted": False},+ "suggested_action": "APPROVE",+ "confidence": 0.8,+ "review_priority": 0.2,+ "evidence": [],+ "model_version": "test-model",+ }+ return DomainEvidence.objects.create(domain=domain, **(defaults | overrides))+++# --------------------------------------------------------------------- rules+[email protected]("crawl,expected_kind", [+ ({"http_status": 404, "pages": [{"title": "", "extract": "", "num_links": 0}],+ "signals": {}}, "http_status"),+ ({"http_status": None, "error": "RobotsDenied", "pages": [], "signals": {}}, "robots"),+ ({"http_status": None, "error": "AbortError", "pages": [], "signals": {}}, "unreachable"),+ ({"http_status": 200, "final_domain": "somewhere-else.com", "pages": [],+ "signals": {}}, "redirect"),+ ({"http_status": 200, "pages": [{"title": "t", "extract": "e", "num_links": 1}],+ "signals": {"has_links": True, "blacklisted": True}}, "blocklist"),+])+def test_each_deterministic_check_fires(crawl, expected_kind):+ kinds = {item.kind for item in rules.crawl_evidence("example.com", crawl)}+ assert expected_kind in kinds+++def test_do_not_crawl_list_is_decisive():+ items = rules.crawl_evidence("mwmbl.org", {"http_status": 200, "pages": [], "signals": {}})+ decisive = rules.decisive(items)+ assert decisive.kind == "do_not_crawl"+ assert decisive.implies_action == "REJECT"+++def test_subdomain_redirect_is_not_treated_as_off_domain():+ items = rules.crawl_evidence(+ "example.com",+ {"http_status": 200, "final_domain": "www.example.com", "pages": [], "signals": {}})+ assert "redirect" not in {item.kind for item in items}+++def test_first_time_submitter_is_called_out():+ items = rules.live_evidence({"approved": 0, "rejected": 0}, {})+ assert any("no track record" in item.label for item in items)+++def test_previous_approval_of_the_same_domain_is_decisive():+ items = rules.live_evidence({"approved": 3, "rejected": 0}, {"approved": 1, "rejected": 0})+ assert rules.decisive(items).implies_action == "APPROVE"+++# --------------------------------------------------------------------- suggestions++def test_a_deterministic_check_beats_the_model():+ """A 404 is not a matter of opinion, so no probability may override it."""+ model = mock.Mock()+ model.version = "test"+ model.predict.return_value = [(0.01, "SPAM", 0.9)] # the model says "approve"++ items = rules.crawl_evidence(+ "example.com", {"http_status": 404, "pages": [], "signals": {}})+ suggestion = suggest("example.com", [], items, model=model)++ assert suggestion.action == "REJECT"+ assert suggestion.reason_source == "rule"+ model.predict.assert_not_called()+++def test_missing_model_degrades_to_unsure_not_to_a_default():+ with mock.patch("mwmbl.moderation.model.get_model", return_value=None):+ suggestion = suggest("example.com", ["some text"], [])+ assert suggestion.action == "UNSURE"+ assert suggestion.confidence == 0.0+++def test_offensive_confidence_is_capped_because_it_has_no_real_labels():+ from mwmbl.moderation.model import REASON_CONFIDENCE_CAP+ assert REASON_CONFIDENCE_CAP["OFFENSIVE"] < 1.0+++def test_review_priority_puts_confident_rejects_first_and_approvals_last():+ reject = Suggestion(action="REJECT", confidence=0.95)+ unsure = Suggestion(action="UNSURE", confidence=0.1)+ approve = Suggestion(action="APPROVE", confidence=0.95)+ assert reject.review_priority > unsure.review_priority > approve.review_priority+++# --------------------------------------------------------------------- features++def test_featuriser_produces_the_same_width_for_unseen_input():+ featuriser = Featuriser()+ fitted = featuriser.fit_transform([+ ModerationExample("aianimegenerator.cloud", ["free ai anime generator"]),+ ModerationExample("docs.python.org", ["python language reference"]),+ ModerationExample("seobacklinkhub.org", ["best seo backlinks tool"]),+ ])+ transformed = featuriser.transform([ModerationExample("unseen.example", ["nothing alike"])])+ assert transformed.shape[1] == fitted.shape[1]+ assert len(featuriser.feature_names()) == fitted.shape[1]+++def test_malformed_historic_names_are_excluded_from_training():+ """Migrations 0032/0033 fixed these at the API layer; training on them teaches a+ problem that can no longer occur."""+ assert not is_trainable_domain("null")+ assert not is_trainable_domain("CapCutModsAPK.net")+ assert not is_trainable_domain("")+ assert is_trainable_domain("docs.python.org")+++def test_derived_rows_never_reach_the_test_split():+ from mwmbl.moderation.train import split_by_time++ real = [TrainingRow(f"real{index}.com", index % 2 == 0, "", "real", [], f"2025-01-{index:02d}")+ for index in range(1, 21)]+ derived = [TrainingRow(f"derived{index}.com", True, "OFFENSIVE", "derived", [])+ for index in range(5)]+ seed = [TrainingRow("seed.com", True, "OTHER", "seed", [])]++ train_rows, test_rows = split_by_time(real + derived + seed)+ assert all(row.source == "real" for row in test_rows)+ assert {row.source for row in train_rows} == {"real", "derived", "seed"}+++# --------------------------------------------------------------------- API++def test_queue_requires_the_moderator_permission(client, submitter):+ response = client.get(QUEUE_URL, headers={"Authorization": token(submitter)})+ assert response.status_code == 403+++def test_queue_runs_no_model(client, moderator, submitter):+ """The whole point of precomputing: a moderator's request never waits on inference."""+ submission = DomainSubmission.objects.create(name="example.com", submitted_by=submitter)+ ready_evidence(submission.name)++ with mock.patch("mwmbl.moderation.model.get_model") as get_model:+ response = client.get(QUEUE_URL, headers={"Authorization": token(moderator)})++ assert response.status_code == 200+ get_model.assert_not_called()+++def test_uncrawled_submission_reports_that_rather_than_guessing(client, moderator, submitter):+ DomainSubmission.objects.create(name="not-yet-crawled.com", submitted_by=submitter)++ response = client.get(QUEUE_URL, headers={"Authorization": token(moderator)})+ item = response.json()["items"][0]++ assert item["evidence_state"] == "PENDING"+ assert item["suggestion"] is None+++def test_queue_orders_rows_that_need_a_human_first(client, moderator, submitter):+ for name, action, priority in [("approve-me.com", "APPROVE", 0.1),+ ("reject-me.com", "REJECT", 1.9),+ ("unsure.com", "UNSURE", 1.0)]:+ DomainSubmission.objects.create(name=name, submitted_by=submitter)+ ready_evidence(name, suggested_action=action, review_priority=priority)++ response = client.get(QUEUE_URL, headers={"Authorization": token(moderator)})+ assert [item["name"] for item in response.json()["items"]] == [+ "reject-me.com", "unsure.com", "approve-me.com"]+++def test_queue_filters_on_the_stored_suggestion(client, moderator, submitter):+ for name, action in [("a.com", "APPROVE"), ("b.com", "REJECT")]:+ DomainSubmission.objects.create(name=name, submitted_by=submitter)+ ready_evidence(name, suggested_action=action)++ response = client.get(f"{QUEUE_URL}?suggested_action=REJECT",+ headers={"Authorization": token(moderator)})+ assert [item["name"] for item in response.json()["items"]] == ["b.com"]+++def test_decision_records_the_suggestion_that_was_shown(client, moderator, submitter):+ submission = DomainSubmission.objects.create(name="example.com", submitted_by=submitter)++ response = client.post(+ f"/api/v1/platform/domain-submissions/ids/{submission.id}",+ data={"status": "REJECTED", "rejection_reason": "SPAM", "rejection_detail": "",+ "suggested_status": "APPROVE", "suggested_reason": "",+ "suggestion_confidence": 0.62, "suggestion_model_version": "test-model"},+ content_type="application/json", headers={"Authorization": token(moderator)})+ assert response.status_code == 200++ submission.refresh_from_db()+ assert submission.status == "REJECTED"+ # The moderator disagreed with the tool, and that disagreement is what makes the next+ # retrain able to tell whether the suggestions are helping.+ assert submission.suggested_status == "APPROVE"+ assert submission.suggestion_confidence == pytest.approx(0.62)+ assert submission.status_changed_by == moderator+++def test_bulk_decisions_apply_each_choice_separately(client, moderator, submitter):+ first = DomainSubmission.objects.create(name="a.com", submitted_by=submitter)+ second = DomainSubmission.objects.create(name="b.com", submitted_by=submitter)++ response = client.post(+ "/api/v1/platform/domain-submissions/decisions",+ data={"decisions": [+ {"submission_id": first.id, "status": "APPROVED"},+ {"submission_id": second.id, "status": "REJECTED", "rejection_reason": "SPAM"},+ ]},+ content_type="application/json", headers={"Authorization": token(moderator)})++ assert response.json()["updated"] == 2+ first.refresh_from_db()+ second.refresh_from_db()+ assert (first.status, second.status) == ("APPROVED", "REJECTED")+++def test_refetch_clears_the_evidence_so_the_crawl_actually_reruns(client, moderator, submitter):+ submission = DomainSubmission.objects.create(name="was-down.com", submitted_by=submitter)+ ready_evidence(submission.name)++ with mock.patch("mwmbl.platform.api.enrich_domain_submission") as enrich:+ response = client.post(+ f"/api/v1/platform/domain-submissions/ids/{submission.id}/refetch",+ headers={"Authorization": token(moderator)})++ assert response.status_code == 200+ assert not DomainEvidence.objects.filter(domain="was-down.com").exists()+ enrich.assert_called_once_with("was-down.com")+++# --------------------------------------------------------------------- rescoring++def test_rescore_updates_pending_rows_only(submitter):+ from mwmbl.background import rescore_pending_submissions++ DomainSubmission.objects.create(name="pending.com", submitted_by=submitter, status="PENDING")+ decided = DomainSubmission.objects.create(+ name="decided.com", submitted_by=submitter, status="APPROVED",+ suggested_status="REJECT", suggestion_confidence=0.9)+ ready_evidence("pending.com", model_version="old")+ ready_evidence("decided.com", model_version="old")++ with mock.patch("mwmbl.moderation.model.get_model", return_value=None):+ rescore_pending_submissions.now()++ assert DomainEvidence.objects.get(domain="pending.com").model_version == ""+ assert DomainEvidence.objects.get(domain="decided.com").model_version == "old"+ decided.refresh_from_db()+ # The audit of what was on screen when this was decided must survive a retrain.+ assert decided.suggested_status == "REJECT"+++def test_enrichment_skips_a_domain_whose_evidence_is_still_fresh(submitter):+ from mwmbl.background import enrich_domain_submission++ ready_evidence("fresh.com")+ with mock.patch("mwmbl.background.crawl_domain") as crawl:+ enrich_domain_submission.now("fresh.com")+ crawl.assert_not_called()+++def test_enrichment_recrawls_stale_evidence(submitter):+ from mwmbl.background import enrich_domain_submission++ ready_evidence("stale.com", fetched_at=timezone.now() - timedelta(days=365))+ with mock.patch("mwmbl.background.crawl_domain") as crawl:+ crawl.return_value = {"http_status": 200, "final_domain": "", "error": "",+ "pages": [], "signals": {}}+ enrich_domain_submission.now("stale.com")+ crawl.assert_called_once()+++def test_queue_cost_does_not_grow_with_the_backlog(client, moderator, submitter,+ django_assert_max_num_queries):+ """Ordering, filtering and slicing must happen in SQL.++ The backlog is ~4,000 pending submissions. An implementation that builds the list in+ Python and sorts it there pays for all of them on every request, and issues per-row+ queries for the submitter and prior-decision checks on top. Both are invisible on a small+ test fixture, so this pins the query count instead: it must be flat in the number of rows.+ """+ for index in range(30):+ name = f"site{index}.example"+ DomainSubmission.objects.create(name=name, submitted_by=submitter)+ ready_evidence(name, review_priority=index / 30)++ # Auth, permissions, count, page, evidence, submitter counts, prior-decision counts.+ with django_assert_max_num_queries(12):+ response = client.get(f"{QUEUE_URL}?limit=5",+ headers={"Authorization": token(moderator)})++ body = response.json()+ assert body["count"] == 30+ assert len(body["items"]) == 5+ # ...and the page is the top of the global ordering, not the top of an arbitrary slice.+ assert body["items"][0]["name"] == "site29.example"+++def test_queue_paginates_over_the_whole_ordering(client, moderator, submitter):+ for index in range(10):+ name = f"site{index}.example"+ DomainSubmission.objects.create(name=name, submitted_by=submitter)+ ready_evidence(name, review_priority=index / 10)++ def page(offset):+ response = client.get(f"{QUEUE_URL}?limit=4&offset={offset}",+ headers={"Authorization": token(moderator)})+ return [item["name"] for item in response.json()["items"]]++ assert page(0) + page(4) + page(8) == [f"site{index}.example"+ for index in range(9, -1, -1)]+++def test_robots_denied_is_evidence_not_a_verdict():+ """lobste.rs disallows `User-agent: *` and was approved anyway, and not one of the 76+ distinct rejection details mentions robots.txt. Suggesting a confident rejection here+ would be confidently wrong on a domain moderators actually wanted."""+ items = rules.crawl_evidence(+ "lobste.rs", {"http_status": None, "error": "RobotsDenied", "pages": [{}],+ "signals": {}})+ robots = next(item for item in items if item.kind == "robots")+ assert robots.implies_action is None+ assert rules.decisive(items) is None+++def test_blocklist_membership_is_evidence_not_a_verdict():+ """Overriding a false positive on these lists is exactly what an approval is for -+ mwmbl.curated_domains names pudding.cool and contactmusic.com as examples - so the tool+ must not argue against the mechanism it serves."""+ items = rules.crawl_evidence(+ "pudding.cool",+ {"http_status": 200, "pages": [{"title": "t", "extract": "e", "num_links": 4}],+ "signals": {"has_links": True, "blacklisted": True}})+ blocklist = next(item for item in items if item.kind == "blocklist")+ assert blocklist.direction == rules.REJECT+ assert blocklist.implies_action is None+++def test_a_failed_fetch_reports_one_problem_not_four():+ items = rules.crawl_evidence(+ "gone.example",+ {"http_status": None, "error": "AbortError", "pages": [{"title": "", "extract": "",+ "num_links": 0}],+ "signals": {}})+ kinds = {item.kind for item in items}+ assert kinds == {"unreachable"}+++def test_an_approval_is_not_labelled_with_the_reason_heads_argmax():+ model = mock.Mock()+ model.version = "test"+ model.predict.return_value = [(0.02, "OFFENSIVE", 0.5)] # clearly an approval++ suggestion = suggest("example.com", ["wholesome text"], [], model=model)++ assert suggestion.action == "APPROVE"+ assert suggestion.reason == ""+ assert suggestion.reason_source == "model"+++def test_redirect_check_errs_towards_reporting_nothing():+ """The redirect item is decisive, so it must never fire on a site moving between its own+ subdomains. The cost is missing a genuine cross-site redirect under a multi-part suffix+ like .co.uk, which is a lost evidence line rather than a wrong rejection."""+ assert rules.registrable("www.example.com") == rules.registrable("docs.example.com")+ assert rules.registrable("example.co.uk") == rules.registrable("somewhere-else.co.uk")++ items = rules.crawl_evidence(+ "example.com",+ {"http_status": 200, "final_domain": "elsewhere.net", "pages": [], "signals": {}})+ assert rules.decisive(items).kind == "redirect"+++# --------------------------------------------------------------------- retrain gate++def metrics(pr_auc, low, high):+ return {"cold_start": {"pr_auc": pr_auc, "pr_auc_ci": [low, high]}}+++def test_gate_publishes_when_there_is_no_incumbent():+ allowed, _ = passes_gate(metrics(0.78, 0.69, 0.86), {})+ assert allowed+++def test_gate_blocks_a_model_below_the_incumbents_lower_bound():+ allowed, explanation = passes_gate(metrics(0.60, 0.51, 0.69),+ metrics(0.78, 0.69, 0.86))+ assert not allowed+ assert "0.690" in explanation+++def test_gate_tolerates_movement_inside_the_interval():+ """The measured augmentation experiment moved the point estimate by 0.04 while the+ intervals spanned 0.17. A gate on point estimates would treat that noise as signal in+ both directions - blocking good models and shipping bad ones."""+ allowed, _ = passes_gate(metrics(0.74, 0.65, 0.83), metrics(0.78, 0.69, 0.86))+ assert allowed+++def test_gate_refuses_when_there_is_no_cold_start_slice():+ """Too little held-out data to judge is a reason not to publish, not a free pass."""+ allowed, explanation = passes_gate({"all": {"pr_auc": 0.9}}, {})+ assert not allowed+ assert "cold-start" in explanation+++# --------------------------------------------------------------------- prior shift++def test_no_confident_approval_for_a_submitter_with_no_track_record(submitter):+ """The model is trained on a population that rejects 11% and asked about one that rejects+ 54%, so a low reject score means much less for a first-time submitter - measured at 44%+ wrong. Withhold the approval rather than present it at face value."""+ submission = DomainSubmission.objects.create(name="unknown.example", submitted_by=submitter)+ evidence = ready_evidence("unknown.example", suggested_action="APPROVE", confidence=0.9)++ suggestion = suggestion_for(submission, evidence)++ assert suggestion.action == "UNSURE"+++def test_approval_stands_for_a_submitter_with_a_record(submitter):+ for index in range(3):+ DomainSubmission.objects.create(name=f"past{index}.example", submitted_by=submitter,+ status="APPROVED")+ submission = DomainSubmission.objects.create(name="known.example", submitted_by=submitter)+ evidence = ready_evidence("known.example", suggested_action="APPROVE", confidence=0.9)++ suggestion = suggestion_for(submission, evidence)++ assert suggestion.action == "APPROVE"+ assert suggestion.confidence == pytest.approx(0.9)+++def test_rejections_are_not_withheld_from_first_time_submitters(submitter):+ """Rejection precision is 0.88 on exactly this slice, so only the approve side is held."""+ submission = DomainSubmission.objects.create(name="spammy.example", submitted_by=submitter)+ evidence = ready_evidence("spammy.example", suggested_action="REJECT",+ suggested_reason="SPAM", confidence=0.9)++ suggestion = suggestion_for(submission, evidence)++ assert suggestion.action == "REJECT"+ assert suggestion.reason == "SPAM"