An open source, non-profit web search engine
Measure the operating point, and make has_text ablatable
Daoud Clarke53a53cf86ee5
diff --git a/mwmbl/management/commands/train_domain_moderation_model.py b/mwmbl/management/commands/train_domain_moderation_model.pyindex 961afe4..16f6cee 100644--- a/mwmbl/management/commands/train_domain_moderation_model.py+++ b/mwmbl/management/commands/train_domain_moderation_model.py@@ -45,11 +45,17 @@ class Command(BaseCommand):help="Publish even if the gate fails")parser.add_argument("--no-text", action="store_true", dest="no_text",- help="Fit on the domain name alone, ignoring crawled page text")+ help="Fit on the domain name alone, ignoring the crawled page text vocabulary")+ parser.add_argument(+ "--no-has-text", action="store_true", dest="no_has_text",+ help=("Drop the was-it-crawled indicator. Evidence is crawled newest-first, so it "+ "doubles as a proxy for recency and can move the score distribution through "+ "the serving threshold; --ablate measures whether it is doing that here"))parser.add_argument("--ablate", action="store_true",- help=("Also train the domain-name-only model and report both, so the contribution "- "of the crawled page text is measured on the same split rather than guessed"))+ help=("Also train without the page-text vocabulary and without the has_text "+ "indicator, and report all three on the same split, so each is measured "+ "rather than guessed"))parser.add_argument("--derived", action="store_true",help=("Add blocklist-derived rows for reason classes short of real data. Off by "@@ -79,7 +85,7 @@ class Command(BaseCommand):# no longer featurise - the gate falls back to the stored metrics and says so.incumbent = load_published_model()model, metrics = train(rows, version, use_text=not options["no_text"],- incumbent=incumbent)+ use_has_text=not options["no_has_text"], incumbent=incumbent)self.stdout.write(json.dumps(metrics, indent=2))if options["ablate"]:@@ -101,30 +107,51 @@ class Command(BaseCommand):rescore_pending_submissions(schedule=0)self.stdout.write("Scheduled a rescore of the pending queue with the new model.")- def _report_ablation(self, rows, version, with_text: dict) -> None:- """Train the same model without the text block and print both cold-start scores.+ def _report_ablation(self, rows, version, full: dict) -> None:+ """Hold out each half of the page-text features in turn, on the same split.- Same rows, same split, same seed, so the difference is the text block and nothing else.- Normalised AP rather than PR-AUC because the two fits see identical prevalence here and- it keeps the number on the same scale as everything else the retrain reports.+ Same rows, same seed, so each line differs from the one above it by one thing. Both+ ranking quality and the *operating point* are reported: a feature can hold the ranking+ while shifting the score distribution through MODERATION_REJECT_THRESHOLD, which is+ what appears to have happened to has_text, and normalised AP alone cannot see it."""- _, without_text = train(rows, f"{version}-no-text", use_text=False)- self.stdout.write("\nAblation - does the crawled page text help?")- for name, metrics in (("with text", with_text), ("domain name only", without_text)):+ _, no_text = train(rows, f"{version}-no-text", use_text=False, use_has_text=False)+ _, no_has_text = train(rows, f"{version}-no-has-text", use_has_text=False)++ self.stdout.write("\nAblation - are the page-text features earning their place?")+ self.stdout.write(f" {'':>22} {'norm AP':>17} {'reject P':>16} "+ f"{'reject R':>16} {'unsure':>7}")+ for name, metrics in (("text + has_text", full),+ ("text, no has_text", no_has_text),+ ("domain name only", no_text)):cold = metrics.get("cold_start")if cold is None:- self.stdout.write(f" {name:>16}: no cold-start slice")+ self.stdout.write(f" {name:>22}: no cold-start slice")continue+ at = cold["at_thresholds"]self.stdout.write(- f" {name:>16}: normalised AP {cold['normalised_ap']:.4f} "- f"[{cold['normalised_ap_ci'][0]:.4f}, {cold['normalised_ap_ci'][1]:.4f}] "- f"(PR-AUC {cold['pr_auc']:.4f}, base rate {cold['base_rate']:.4f})")+ f" {name:>22} {self._with_interval(cold['normalised_ap'], cold['normalised_ap_ci'])} "+ f"{self._with_interval(at['reject_precision'], at['reject_precision_ci'])} "+ f"{self._with_interval(at['reject_recall'], at['reject_recall_ci'])} "+ f"{at['unsure_share']:>7.3f}")++ cold = full.get("cold_start", {})self.stdout.write(- f" {with_text.get('train_rows_with_text', 0)} of "- f"{sum(with_text.get('train_rows_by_source', {}).values())} training rows and "- f"{with_text.get('cold_start', {}).get('rows_with_text', 0)} of "- f"{with_text.get('cold_start', {}).get('rows', 0)} cold-start test rows have text. "- f"A large gap between those two is the skew to fix before reading the ablation.\n")+ f"\n {full.get('train_rows_with_text', 0)} of "+ f"{sum(full.get('train_rows_by_source', {}).values())} training rows and "+ f"{cold.get('rows_with_text', 0)} of {cold.get('rows', 0)} cold-start test rows "+ f"have text.\n A large gap between those two makes has_text a proxy for recency "+ f"rather than for evidence, and the fix is to backfill evidence for the older "+ f"submissions rather than to argue about the feature.\n")++ @staticmethod+ def _with_interval(value, interval) -> str:+ """A point estimate and its interval, or a dash where the threshold selected nothing."""+ if value is None:+ return f"{'-':>16}"+ if interval is None:+ return f"{value:>6.3f} "+ return f"{value:>6.3f} [{interval[0]:.2f},{interval[1]:.2f}]"@staticmethoddef _reasons_needing_data(rows) -> set[str]:diff --git a/mwmbl/moderation/artifacts/README.md b/mwmbl/moderation/artifacts/README.mdindex c6bb5a2..e3740ae 100644--- a/mwmbl/moderation/artifacts/README.md+++ b/mwmbl/moderation/artifacts/README.md@@ -14,8 +14,9 @@ worker replica keeping its own copy.## 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+ uv run manage.py train_domain_moderation_model --dry-run # metrics only+ uv run manage.py train_domain_moderation_model --dry-run --ablate # + feature ablation+ uv run manage.py train_domain_moderation_model # publish if it passesThe gate loads the published model, scores it and the candidate on the *same* held-out rows, andbootstraps the difference; the candidate ships unless it is confidently worse. Raw PR-AUC is never@@ -24,6 +25,14 @@ blocked for a 0.11 "regression" that was entirely a shift in prevalence after mi`mwmbl.moderation.train`. Publishing writes a new artifact row, which every worker picks up withina minute, and schedules `rescore_pending_submissions` to re-score the existing queue.+Every slice also reports `at_thresholds`: precision, recall and the unsure share at+`MODERATION_REJECT_THRESHOLD` and `MODERATION_APPROVE_THRESHOLD`, each with an interval. PR-AUC+summarises every threshold, including ones nothing runs at, so a model can hold its ranking while+its score distribution drifts through the two the server serves — read `reject_precision` and+`approve_error_rate` before believing a retrain is an improvement. `--ablate` holds out the+page-text vocabulary and the `has_text` indicator separately and reports all three fits on the+same split; `--no-text` and `--no-has-text` fit those variants directly.+To reproduce the numbers without a production database, train from the sanitized judgments exportinstead:diff --git a/mwmbl/moderation/artifacts/metrics.json b/mwmbl/moderation/artifacts/metrics.jsonindex 6aa6ca2..a98deda 100644--- a/mwmbl/moderation/artifacts/metrics.json+++ b/mwmbl/moderation/artifacts/metrics.json@@ -14,7 +14,45 @@0.2357,0.4431],- "recall_at_precision_75": 0.2022,+ "at_thresholds": {+ "reject_share": 0.0232,+ "reject_precision": 0.8182,+ "reject_recall": 0.2022,+ "approve_share": 0.8166,+ "approve_error_rate": 0.0645,+ "unsure_share": 0.1602,+ "recall_at_precision_75": 0.2022,+ "reject_share_ci": [+ 0.0137,+ 0.0327+ ],+ "reject_precision_ci": [+ 0.6399,+ 0.96+ ],+ "reject_recall_ci": [+ 0.1264,+ 0.2873+ ],+ "approve_share_ci": [+ 0.7935,+ 0.8409+ ],+ "approve_error_rate_ci": [+ 0.0498,+ 0.0828+ ],+ "unsure_share_ci": [+ 0.138,+ 0.1823+ ],+ "recall_at_precision_75_ci": [+ 0.0941,+ 0.345+ ],+ "reject_threshold": 0.75,+ "approve_threshold": 0.25+ },"rows_with_text": 0},"cold_start": {@@ -32,7 +70,45 @@0.3545,0.6621],- "recall_at_precision_75": 0.4074,+ "at_thresholds": {+ "reject_share": 0.12,+ "reject_precision": 0.8889,+ "reject_recall": 0.1975,+ "approve_share": 0.6733,+ "approve_error_rate": 0.4455,+ "unsure_share": 0.2067,+ "recall_at_precision_75": 0.4074,+ "reject_share_ci": [+ 0.0667,+ 0.18+ ],+ "reject_precision_ci": [+ 0.7055,+ 1.0+ ],+ "reject_recall_ci": [+ 0.1139,+ 0.2973+ ],+ "approve_share_ci": [+ 0.5933,+ 0.7467+ ],+ "approve_error_rate_ci": [+ 0.3535,+ 0.5429+ ],+ "unsure_share_ci": [+ 0.14,+ 0.2733+ ],+ "recall_at_precision_75_ci": [+ 0.3094,+ 0.8541+ ],+ "reject_threshold": 0.75,+ "approve_threshold": 0.25+ },"rows_with_text": 0},"reason_head": {@@ -54,6 +130,7 @@},"train_rows_with_text": 21,"uses_text": true,+ "uses_has_text": true,"suggestion_influence": {"real_rows": 3796,"shown_a_suggestion": 0,diff --git a/mwmbl/moderation/artifacts/model.joblib b/mwmbl/moderation/artifacts/model.joblibindex 5bfa669..69a773f 100644Binary files a/mwmbl/moderation/artifacts/model.joblib and b/mwmbl/moderation/artifacts/model.joblib differdiff --git a/mwmbl/moderation/features.py b/mwmbl/moderation/features.pyindex d2c6edf..ceb7ba8 100644--- a/mwmbl/moderation/features.py+++ b/mwmbl/moderation/features.py@@ -38,8 +38,12 @@ MAX_TEXT_CHARS = 2000# penalty then charges for, and has_text is the one feature that most needs to be heard.SHAPE_SCALE = 40.0COUNT_FEATURE_NAMES = ["len", "labels", "digits", "hyphens", "sld_len", "spamwords", "tld_len"]-INDICATOR_FEATURE_NAMES = ["www", "has_text"]-NUM_SHAPE_FEATURES = len(COUNT_FEATURE_NAMES) + len(INDICATOR_FEATURE_NAMES)+INDICATOR_FEATURE_NAMES = ["www"]+# Held out separately from the text block, because the two can fail independently: the block+# can earn its place while the indicator is a trap. See Featuriser.+OPTIONAL_INDICATOR_FEATURE_NAMES = ["has_text"]+NUM_SHAPE_FEATURES = (len(COUNT_FEATURE_NAMES) + len(INDICATOR_FEATURE_NAMES)+ + len(OPTIONAL_INDICATOR_FEATURE_NAMES))@dataclass@@ -77,19 +81,12 @@ def shape_features(domain: str) -> list[float]:]-def indicator_features(example: "ModerationExample") -> list[float]:- """The unscaled 0/1 features, in INDICATOR_FEATURE_NAMES order.-- ``has_text`` exists because an empty text block and a page whose words are all out of- vocabulary produce the same all-zero TF-IDF row, and they are not the same thing. Evidence- is crawled for recent submissions first, so in a chronological split most training rows- have no text and most test rows do; without this the model cannot tell the two apart, and- the difference is silently absorbed into the intercept it fitted on the training mix.- """- return [- float(example.domain.lower().startswith("www.")),- float(bool(example.text.strip())),- ]+def indicator_features(example: "ModerationExample", use_has_text: bool = True) -> list[float]:+ """The unscaled 0/1 features, in INDICATOR + OPTIONAL_INDICATOR name order."""+ indicators = [float(example.domain.lower().startswith("www."))]+ if use_has_text:+ indicators.append(float(bool(example.text.strip())))+ return indicatorsclass Featuriser:@@ -99,10 +96,27 @@ class Featuriser:training saw rather than rebuilding one from different data."""- def __init__(self, use_text: bool = True):- # Set False to fit the domain-name-only model, so the ablation that answers "is the- # crawled page text helping?" runs through exactly this code rather than a copy of it.+ def __init__(self, use_text: bool = True, use_has_text: bool = True):+ """``use_text`` fits the page-text vocabulary; ``use_has_text`` the "was it crawled at+ all" indicator. Two flags rather than one because the two can fail independently, and+ the August 2026 numbers suggest they did.++ ``has_text`` exists because an empty text block and a page whose words are all out of+ vocabulary produce the same all-zero TF-IDF row, and they are not the same thing. But+ evidence is crawled newest-first, so under a chronological split the indicator is also+ a proxy for *recency* - 46% of training rows against 92% of cold-start test rows in the+ first production run - and recency is when the .ai spam wave happened. A model can+ therefore learn ``has_text -> reject`` from the training mix and then apply it to a test+ set where almost everything has text: the ordering barely moves, so PR-AUC does not+ notice, but the whole score distribution shifts through the serving threshold and+ precision at the head collapses. Recall at 75% precision halved between the two+ production runs, which is the shape of exactly that.++ So it is ablatable, and the honest fix is to even out the coverage by backfilling+ evidence for older submissions rather than to argue about the feature.+ """self.use_text = use_text+ self.use_has_text = use_has_text# 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(@@ -150,10 +164,10 @@ class Featuriser:blocks.append(self._shape_block(examples))return hstack(blocks).tocsr()- @staticmethod- def _shape_block(examples: list[ModerationExample]) -> csr_matrix:+ def _shape_block(self, examples: list[ModerationExample]) -> csr_matrix:counts = np.array([shape_features(example.domain) for example in examples], dtype=float)- indicators = np.array([indicator_features(example) for example in examples], dtype=float)+ indicators = np.array([indicator_features(example, self.use_has_text)+ for example in examples], dtype=float)return csr_matrix(np.hstack([counts / SHAPE_SCALE, indicators]))def feature_names(self) -> np.ndarray:@@ -165,5 +179,7 @@ class Featuriser: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(COUNT_FEATURE_NAMES + INDICATOR_FEATURE_NAMES))+ indicators = INDICATOR_FEATURE_NAMES + (+ OPTIONAL_INDICATOR_FEATURE_NAMES if self.use_has_text else [])+ names.append(np.array(COUNT_FEATURE_NAMES + indicators))return np.concatenate(names)diff --git a/mwmbl/moderation/train.py b/mwmbl/moderation/train.pyindex e537b59..0db78f8 100644--- a/mwmbl/moderation/train.py+++ b/mwmbl/moderation/train.py@@ -32,6 +32,7 @@ from logging import getLoggerfrom typing import Optionalimport numpy as np+from django.conf import settingsfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import average_precision_score, f1_score, precision_recall_curve@@ -53,6 +54,13 @@ MIN_CLASS_ROWS = 5GATE_TOLERANCE = 0.05+# Statistics bootstrapped alongside PR-AUC. Named here rather than inferred from the point+# estimate, so a statistic that is undefined in *every* resample - reject precision on a slice+# where nothing clears the threshold - still reports, as null, rather than vanishing.+OPERATING_POINT_KEYS = ["reject_share", "reject_precision", "reject_recall", "approve_share",+ "approve_error_rate", "unsure_share", "recall_at_precision_75"]++@dataclassclass Evaluation:slice_name: str@@ -63,7 +71,7 @@ class Evaluation:pr_auc_ci: tuple[float, float]normalised_ap: floatnormalised_ap_ci: tuple[float, float]- recall_at_precision_75: float+ operating_point: dictrows_with_text: intdef to_dict(self) -> dict:@@ -79,7 +87,13 @@ class Evaluation:"normalised_ap": round(self.normalised_ap, 4),"normalised_ap_ci": [round(self.normalised_ap_ci[0], 4),round(self.normalised_ap_ci[1], 4)],- "recall_at_precision_75": round(self.recall_at_precision_75, 4),+ # What a moderator actually experiences. PR-AUC is a summary over every threshold,+ # including ones nothing runs at; the server suggests REJECT at+ # MODERATION_REJECT_THRESHOLD and APPROVE at MODERATION_APPROVE_THRESHOLD, and a+ # model can hold its ranking while its score distribution shifts through those and+ # ruins precision at the head. That happened between the first two production runs+ # and only recall_at_precision_75 saw it - the one number with no interval on it.+ "at_thresholds": self.operating_point,# Evidence is crawled newest-first, so this differs sharply between the splits and# is the number to look at before believing anything about the text features."rows_with_text": self.rows_with_text,@@ -106,19 +120,21 @@ def split_by_time(rows: list[TrainingRow]) -> tuple[list[TrainingRow], list[Traidef train(rows: list[TrainingRow], version: str, use_text: bool = True,+ use_has_text: bool = True,incumbent: Optional[ModerationModel] = None) -> tuple[ModerationModel, dict]:"""Fit both heads and evaluate on held-out real rows only.- ``use_text=False`` fits the domain-name-only model, which is the ablation that answers- whether the crawled page text is earning its place. ``incumbent`` is the model currently- being served; when given, the metrics carry a paired comparison against it on these exact- test rows, which is the only comparison that means anything.+ ``use_text`` and ``use_has_text`` are the two halves of the page-text ablation - the+ vocabulary and the was-it-crawled indicator - held out separately because they can fail+ independently. ``incumbent`` is the model currently being served; when given, the metrics+ carry a paired comparison against it on these exact test rows, which is the only comparison+ that means anything."""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(use_text=use_text)+ featuriser = Featuriser(use_text=use_text, use_has_text=use_has_text)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.@@ -170,6 +186,7 @@ def evaluate(model: ModerationModel, train_rows: list[TrainingRow],metrics["train_rows_with_text"] = sum(1 for row in train_rows if row.to_example().text.strip())metrics["uses_text"] = model.featuriser.text is not None+ metrics["uses_has_text"] = model.featuriser.use_has_textmetrics["suggestion_influence"] = _suggestion_influence(train_rows + test_rows)if incumbent is not None:metrics["versus_incumbent"] = compare_models(@@ -244,10 +261,41 @@ def compare_models(candidate: ModerationModel, incumbent: ModerationModel,}+def recall_at_precision(truth: np.ndarray, scores: np.ndarray, target: float = 0.75) -> float:+ precision, recall, _ = precision_recall_curve(truth, scores)+ return max((r for p, r in zip(precision, recall) if p >= target and r > 0), default=0.0)+++def operating_point(truth: np.ndarray, scores: np.ndarray) -> dict:+ """What the thresholds the server actually runs at would do to this slice.++ ``reject_precision`` is how often a REJECT suggestion is right, and ``approve_error_rate``+ how often an APPROVE suggestion is quietly wrong - the more expensive of the two, because a+ moderator who trusts it never looks. ``unsure_share`` is the fraction the tool declines to+ help with at all.++ None where a threshold selects nothing, which is a real answer about the slice rather than+ a zero: no rows suggested REJECT has no precision, and reporting 0.0 would read as a model+ that is wrong every time instead of one that never speaks.+ """+ reject = scores >= settings.MODERATION_REJECT_THRESHOLD+ approve = scores <= settings.MODERATION_APPROVE_THRESHOLD+ return {+ "reject_share": float(reject.mean()),+ "reject_precision": float(truth[reject].mean()) if reject.any() else None,+ "reject_recall": float(truth[reject].sum() / truth.sum()) if truth.sum() else None,+ "approve_share": float(approve.mean()),+ "approve_error_rate": float(truth[approve].mean()) if approve.any() else None,+ "unsure_share": float((~reject & ~approve).mean()),+ "recall_at_precision_75": recall_at_precision(truth, scores),+ }++def _evaluate_slice(name: str, truth: np.ndarray, scores: np.ndarray,has_text: np.ndarray) -> Evaluation:generator = np.random.default_rng(0)samples, normalised = [], []+ points: dict[str, list] = {key: [] for key in OPERATING_POINT_KEYS}for _ in range(BOOTSTRAP_SAMPLES):indices = generator.choice(len(truth), len(truth), replace=True)if not _has_both_classes(truth[indices]):@@ -257,9 +305,18 @@ def _evaluate_slice(name: str, truth: np.ndarray, scores: np.ndarray,# Normalised per resample, against that resample's own base rate: the resampling itself# moves prevalence around, and correcting with the whole-slice rate would leave that in.normalised.append(normalise(average_precision, truth[indices].mean()))+ for key, value in operating_point(truth[indices], scores[indices]).items():+ if value is not None:+ points[key].append(value)- precision, recall, _ = precision_recall_curve(truth, scores)base_rate = float(truth.mean())+ measured = operating_point(truth, scores)+ for key in OPERATING_POINT_KEYS:+ measured[key] = round(measured[key], 4) if measured[key] is not None else None+ measured[f"{key}_ci"] = _interval(points[key])+ measured["reject_threshold"] = settings.MODERATION_REJECT_THRESHOLD+ measured["approve_threshold"] = settings.MODERATION_APPROVE_THRESHOLD+return Evaluation(slice_name=name,rows=len(truth),@@ -271,12 +328,19 @@ def _evaluate_slice(name: str, truth: np.ndarray, scores: np.ndarray,normalised_ap=normalise(float(average_precision_score(truth, scores)), base_rate),normalised_ap_ci=(float(np.percentile(normalised, 2.5)) if normalised else 0.0,float(np.percentile(normalised, 97.5)) if normalised 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),+ operating_point=measured,rows_with_text=int(has_text.sum()),)+def _interval(values: list) -> Optional[list]:+ """A 95% interval, or None when no resample could measure the statistic at all."""+ if not values:+ return None+ return [round(float(np.percentile(values, 2.5)), 4),+ round(float(np.percentile(values, 97.5)), 4)]++def _evaluate_reason_head(predictions, test_rows: list[TrainingRow]) -> dict:"""Per-reason F1 on the real rejections we held out.diff --git a/test/test_domain_moderation.py b/test/test_domain_moderation.pyindex 3147464..27dbb44 100644--- a/test/test_domain_moderation.py+++ b/test/test_domain_moderation.py@@ -13,6 +13,7 @@ from pathlib import Pathfrom unittest import mockimport joblib+import numpy as npimport pytestfrom allauth.account.models import EmailAddressfrom background_task.models import Task@@ -29,7 +30,7 @@ from mwmbl.moderation.features import Featuriser, ModerationExamplefrom mwmbl.moderation.model import (Suggestion, get_model, load_metrics, publish, reset_model_cache, suggest)from mwmbl.moderation.suggest import annotate_queue, refresh_suggestion, suggestion_for-from mwmbl.moderation.train import _suggestion_influence, passes_gate+from mwmbl.moderation.train import _suggestion_influence, operating_point, passes_gatefrom mwmbl.moderation.training_data import TrainingRow, is_trainable_domainQUEUE_URL = "/api/v1/platform/domain-submissions/queue"@@ -245,6 +246,57 @@ def test_judgements_already_on_a_zero_to_one_scale_are_left_alone(tmp_path):assert read_judgements(path) == {"obviously-fine.org": 0.01, "aislopgenerator.xyz": 0.95}+def test_the_operating_point_is_measured_where_the_server_actually_runs():+ """PR-AUC summarises every threshold, including ones nothing runs at. What a moderator sees+ is decided by MODERATION_REJECT_THRESHOLD and MODERATION_APPROVE_THRESHOLD, and a model can+ hold its ranking while its scores drift through those."""+ truth = np.array([1, 1, 1, 0, 0, 0, 0, 0])+ scores = np.array([0.9, 0.8, 0.4, 0.9, 0.5, 0.1, 0.1, 0.1])++ point = operating_point(truth, scores)++ # 0.9, 0.8 and 0.9 clear the 0.75 reject threshold: two of the three are real rejections.+ assert point["reject_share"] == 3 / 8+ assert point["reject_precision"] == pytest.approx(2 / 3)+ assert point["reject_recall"] == pytest.approx(2 / 3)+ # 0.1, 0.1, 0.1 fall under the 0.25 approve threshold, and none of them was rejected.+ assert point["approve_share"] == 3 / 8+ assert point["approve_error_rate"] == 0.0+ assert point["unsure_share"] == 2 / 8+++def test_a_threshold_that_selects_nothing_reports_null_not_zero():+ """A model that never suggests REJECT has no reject precision. Reporting 0.0 would read as+ a model that is wrong every time instead of one that never speaks."""+ truth = np.array([1, 1, 0, 0])+ point = operating_point(truth, np.array([0.5, 0.5, 0.5, 0.5]))++ assert point["reject_share"] == 0.0+ assert point["reject_precision"] is None+ assert point["approve_error_rate"] is None+ assert point["unsure_share"] == 1.0+++def test_has_text_can_be_held_out_independently_of_the_text_block():+ """The two halves of the page-text features can fail independently - the vocabulary can+ earn its place while the indicator is a proxy for recency - so the ablation holds out each+ on its own rather than both together."""+ examples = [ModerationExample("aianimegenerator.cloud", ["free ai anime generator tool"]),+ ModerationExample("docs.python.org", ["python language reference tool"]),+ ModerationExample("seobacklinkhub.org", ["best seo backlinks tool"])]++ both = Featuriser()+ no_indicator = Featuriser(use_has_text=False)+ both.fit_transform(examples)+ no_indicator.fit_transform(examples)++ assert "has_text" in list(both.feature_names())+ assert "has_text" not in list(no_indicator.feature_names())+ assert no_indicator.text is not None # the vocabulary block is still there+ assert (no_indicator.transform(examples).shape[1]+ == both.transform(examples).shape[1] - 1)++def test_malformed_historic_names_are_excluded_from_training():"""Migrations 0032/0033 fixed these at the API layer; training on them teaches aproblem that can no longer occur."""diff --git a/test/test_staan.py b/test/test_staan.pynew file mode 100644index 0000000..0c0d94a--- /dev/null+++ b/test/test_staan.py@@ -0,0 +1,62 @@+"""+Tests for the Staan search adapter.+"""++from unittest.mock import patch, MagicMock++from mwmbl.tinysearchengine.staan import get_staan_results+++def test_get_staan_results_success():+ mock_response = MagicMock()+ mock_response.json.return_value = {+ "web": {+ "results": [+ {"url": "https://example.com", "title": "Example", "snippet": "An example site"},+ {"url": "https://other.com", "title": "Other", "description": "Fallback field"},+ ]+ }+ }++ with patch("mwmbl.tinysearchengine.staan.settings") as mock_settings, \+ patch("mwmbl.tinysearchengine.staan.requests.get", return_value=mock_response) as mock_get:+ mock_settings.STAAN_SEARCH_API_KEY = "test-key"++ results = get_staan_results("open source llms")++ mock_get.assert_called_once()+ args, kwargs = mock_get.call_args+ assert kwargs["params"] == {"q": "open source llms", "market": "en-us"}+ assert kwargs["headers"] == {"Authorization": "Bearer test-key"}++ assert results == [+ {+ "url": "https://example.com",+ "title": [{"value": "Example", "is_bold": False}],+ "extract": [{"value": "An example site", "is_bold": False}],+ "source": "staan",+ },+ {+ "url": "https://other.com",+ "title": [{"value": "Other", "is_bold": False}],+ "extract": [{"value": "Fallback field", "is_bold": False}],+ "source": "staan",+ },+ ]+++def test_get_staan_results_no_api_key():+ with patch("mwmbl.tinysearchengine.staan.settings") as mock_settings:+ mock_settings.STAAN_SEARCH_API_KEY = ""+ results = get_staan_results("open source llms")++ assert results == []+++def test_get_staan_results_request_failure():+ with patch("mwmbl.tinysearchengine.staan.settings") as mock_settings, \+ patch("mwmbl.tinysearchengine.staan.requests.get", side_effect=Exception("boom")):+ mock_settings.STAAN_SEARCH_API_KEY = "test-key"+ results = get_staan_results("open source llms")++ assert results == []