Skip to content

AI powered OSINT engine to discover and map 840+ social media identities across the web

feat: ablation harness with bootstrap confidence intervals

arxhr00742f7e1fd1a33
diff --git a/src/aliens_eye/eval/__init__.py b/src/aliens_eye/eval/__init__.py
new file mode 100644
index 0000000..ef2874a
--- /dev/null
+++ b/src/aliens_eye/eval/__init__.py
@@ -0,0 +1,11 @@
+"""Reproducible evaluation over a frozen response corpus.
+
+:mod:`aliens_eye.eval.ablate` scores a corpus under several detector
+configurations at once, so the contribution of each component -- the heuristic
+engine, the ML model, the blend, the structural feature groups -- can be read
+off a single table rather than asserted.
+"""
+
+from .ablate import ABLATIONS, run_ablations
+
+__all__ = ["ABLATIONS", "run_ablations"]
diff --git a/src/aliens_eye/eval/ablate.py b/src/aliens_eye/eval/ablate.py
new file mode 100644
index 0000000..6ef8f20
--- /dev/null
+++ b/src/aliens_eye/eval/ablate.py
@@ -0,0 +1,441 @@
+"""Ablation harness: which parts of the detector actually earn their place.
+
+Every configuration is scored over the *same* frozen corpus, so differences are
+attributable to the configuration and nothing else. Feature extraction runs once
+per response and is shared across configurations -- extracting separately would
+let a change in the harness masquerade as a change in the detector.
+
+Three families of configuration:
+
+* **Baselines** -- what the README implicitly claims to beat. ``status_only``
+ is the naive check (HTTP 200 means the account exists) that most username
+ enumerators still use.
+* **Judges** -- heuristic alone, ML alone, and the shipped blend, to separate
+ each judge's contribution from the blend's.
+* **Feature groups** -- zero out one group of ``FEATURE_SCHEMA`` at a time and
+ re-score, which shows what each family of signals is worth.
+
+Reported per configuration: precision, recall, F1, false-positive rate, and the
+**Maybe rate**. The Maybe rate matters because the detector is tri-state: a
+configuration can flatter its precision by abstaining on everything hard, and
+that shows up here rather than hiding inside the confusion matrix.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import random
+from collections.abc import Callable
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any
+
+from aliens_eye.core.analyzer import FeatureExtractor
+from aliens_eye.core.config import ScannerConfig
+from aliens_eye.core.detector import (
+ FOUND_THRESHOLD,
+ NOT_FOUND_THRESHOLD,
+ Detector,
+)
+from aliens_eye.core.fingerprints import FingerprintStore, build_fingerprint
+from aliens_eye.corpus.replay import ReplayFetcher
+from aliens_eye.selfcheck import _metrics
+
+# Families of signal, for the group ablations. Names must exist in
+# FEATURE_SCHEMA; validated by tests/test_ablate.py.
+FEATURE_GROUPS: dict[str, list[str]] = {
+ "status": ["http_200", "http_3xx", "http_404", "http_4xx", "http_5xx"],
+ "keywords": [
+ "error_keyword_count",
+ "positive_keyword_count",
+ "meta_error_keyword_count",
+ "meta_positive_keyword_count",
+ ],
+ "dom": [
+ "profile_section_count",
+ "error_section_count",
+ "img_count",
+ "input_count",
+ "form_count",
+ "link_count",
+ ],
+ "structured_data": ["og_type_profile", "has_json_ld_person", "username_in_canonical"],
+ "url_shape": ["has_username_in_path", "is_homepage", "has_auth_pattern", "username_in_canonical"],
+ "timing": ["response_time"],
+ "size": ["content_length", "text_length"],
+}
+
+
+@dataclass
+class Observation:
+ """One corpus row, with features extracted once and reused by every config."""
+
+ site: str
+ username: str
+ url: str
+ label: int
+ status_code: int
+ features: dict[str, float]
+ fingerprint: dict[str, str]
+ error: str | None = None
+ #: Raw response body. Kept so external rule engines (aliens_eye.eval.external)
+ #: can be scored on exactly the same responses, rather than on a second fetch.
+ body: str = ""
+ final_url: str = ""
+
+
+@dataclass
+class Ablation:
+ """A detector configuration to score."""
+
+ name: str
+ description: str
+ #: Maps (heuristic_prob, ml_prob, observation) -> probability in [0, 1].
+ combine: Callable[[float, float | None, Observation], float]
+ #: Feature groups zeroed before scoring.
+ drop_groups: tuple[str, ...] = ()
+ #: Tri-state thresholds; None means take them from the loaded model.
+ thresholds: tuple[float, float] | None = None
+ #: Force a hard two-state decision (no Maybe band).
+ binary: bool = False
+ tags: tuple[str, ...] = field(default_factory=tuple)
+
+
+def _blend(weight: float) -> Callable[[float, float | None, Observation], float]:
+ def combine(heuristic_prob: float, ml_prob: float | None, _obs: Observation) -> float:
+ if ml_prob is None:
+ return heuristic_prob
+ return weight * ml_prob + (1.0 - weight) * heuristic_prob
+
+ return combine
+
+
+def _status_only(_h: float, _m: float | None, obs: Observation) -> float:
+ """The naive baseline: HTTP 200 means the profile exists."""
+ return 1.0 if obs.status_code == 200 else 0.0
+
+
+def _status_and_not_404(_h: float, _m: float | None, obs: Observation) -> float:
+ """Slightly less naive: anything that is not an explicit 404 counts."""
+ return 0.0 if obs.status_code in (0, 404, 410) else 1.0
+
+
+def build_ablations(model_weight: float | None) -> list[Ablation]:
+ """The standard configuration set. ``model_weight`` is the shipped blend."""
+ shipped = model_weight if model_weight is not None else 0.4
+ ablations = [
+ Ablation(
+ "status_only",
+ "HTTP 200 means found. The naive check most enumerators use.",
+ _status_only, binary=True, tags=("baseline",),
+ ),
+ Ablation(
+ "status_not_404",
+ "Anything that is not an explicit 404/410 counts as found.",
+ _status_and_not_404, binary=True, tags=("baseline",),
+ ),
+ Ablation(
+ "heuristic_only",
+ "Weighted structural scoring, no ML (equivalent to --no-ml).",
+ _blend(0.0), tags=("judge",),
+ ),
+ Ablation(
+ "ml_only",
+ "Logistic regression alone, heuristic used only as an input feature.",
+ _blend(1.0), tags=("judge",),
+ ),
+ Ablation(
+ "blended_shipped",
+ f"The system as released: {shipped:g} ML + {1 - shipped:g} heuristic.",
+ _blend(shipped), tags=("judge", "shipped"),
+ ),
+ ]
+ for group in sorted(FEATURE_GROUPS):
+ ablations.append(
+ Ablation(
+ f"no_{group}",
+ f"Shipped blend with the {group} feature group zeroed.",
+ _blend(shipped),
+ drop_groups=(group,),
+ tags=("feature_group",),
+ )
+ )
+ return ablations
+
+
+#: Names of the standard set, for CLI validation and docs.
+ABLATIONS = [a.name for a in build_ablations(None)]
+
+
+def _apply_drop(features: dict[str, float], groups: tuple[str, ...]) -> dict[str, float]:
+ if not groups:
+ return features
+ masked = dict(features)
+ for group in groups:
+ for name in FEATURE_GROUPS.get(group, ()):
+ masked[name] = 0.0
+ return masked
+
+
+async def collect_observations(
+ corpus: Path,
+ sites: set[str] | None,
+ logger,
+ use_fingerprints: bool = False,
+) -> list[Observation]:
+ """Extract features once per corpus row, in a fixed order.
+
+ Fingerprints are off by default. A live fingerprint store accumulates
+ signatures during a run and scores each response against whatever came
+ before, so it is order-dependent; here the order is fixed and explicit, which
+ makes the ``fingerprints`` ablation reproducible rather than merely stable.
+ """
+ replay = ReplayFetcher(corpus, strict=True)
+ extractor = FeatureExtractor()
+ jobs = replay.eval_jobs(sites)
+ store = FingerprintStore(Path("unused"), read_only=not use_fingerprints)
+ config = ScannerConfig()
+
+ observations: list[Observation] = []
+ for site, url, username, label in jobs:
+ fetch = await replay(None, url, config, None, logger)
+ if fetch.error:
+ observations.append(
+ Observation(site, username, url, label, fetch.status, {}, {}, fetch.error)
+ )
+ continue
+ try:
+ bundle = extractor.extract(
+ fetch.content, fetch.final_url, username, site,
+ fetch.status, fetch.response_time, fetch.headers, fetch.redirect_count,
+ )
+ except Exception as exc: # noqa: BLE001 - a broken page is a data point, not a crash
+ logger.debug("Extraction failed for %s: %s", url, exc)
+ observations.append(
+ Observation(site, username, url, label, fetch.status, {}, {}, str(exc))
+ )
+ continue
+
+ fingerprint = build_fingerprint(bundle.fingerprint)
+ scored = store.score(site, fingerprint)
+ bundle.features["fingerprint_match_found"] = float(scored["match_found"])
+ bundle.features["fingerprint_match_not_found"] = float(scored["match_not_found"])
+ if use_fingerprints:
+ store.add(site, "found" if label == 1 else "not_found", fingerprint)
+ observations.append(
+ Observation(
+ site, username, url, label, fetch.status, bundle.features, fingerprint,
+ body=fetch.content, final_url=fetch.final_url,
+ )
+ )
+ return observations
+
+
+def score_ablation(
+ ablation: Ablation,
+ observations: list[Observation],
+ detector: Detector,
+) -> dict[str, Any]:
+ """Score one configuration over pre-extracted observations."""
+ if ablation.thresholds is not None:
+ found_thr, not_found_thr = ablation.thresholds
+ elif detector.model is not None:
+ found_thr = detector.model.found_threshold
+ not_found_thr = detector.model.not_found_threshold
+ else:
+ found_thr, not_found_thr = FOUND_THRESHOLD, NOT_FOUND_THRESHOLD
+
+ tp = fp = fn = tn = maybe = scored = 0
+ per_site: dict[str, dict[str, int]] = {}
+ # (label, predicted) per scored row, in a fixed order, so configurations can
+ # be compared row-for-row by a paired bootstrap.
+ predictions: list[tuple[int, int]] = []
+ for obs in observations:
+ if obs.error:
+ continue
+ features = _apply_drop(obs.features, ablation.drop_groups)
+ _, heuristic_prob, ml_prob = detector.judges(features)
+ probability = ablation.combine(heuristic_prob, ml_prob, obs)
+
+ if ablation.binary:
+ status = "Found" if probability >= 0.5 else "Not Found"
+ else:
+ status, _confidence = detector._status_from_probability(
+ probability, found_thr, not_found_thr
+ )
+ if status == "Maybe":
+ maybe += 1
+ # Maybe counts as "not Found", matching how the tool reports a scan:
+ # only Found is an assertion the user acts on.
+ predicted = 1 if status == "Found" else 0
+
+ predictions.append((obs.label, predicted))
+ cell = per_site.setdefault(obs.site, {"tp": 0, "fp": 0, "fn": 0, "tn": 0})
+ if obs.label == 1 and predicted == 1:
+ key = "tp"
+ elif obs.label == 1:
+ key = "fn"
+ elif predicted == 1:
+ key = "fp"
+ else:
+ key = "tn"
+ cell[key] += 1
+ tp += key == "tp"
+ fp += key == "fp"
+ fn += key == "fn"
+ tn += key == "tn"
+ scored += 1
+
+ overall = _metrics(tp, fp, fn, tn)
+ overall["maybe_rate"] = round(maybe / scored, 4) if scored else 0.0
+ return {
+ "name": ablation.name,
+ "description": ablation.description,
+ "tags": list(ablation.tags),
+ "dropped_groups": list(ablation.drop_groups),
+ "samples": scored,
+ "overall": overall,
+ "per_site": {
+ s: _metrics(c["tp"], c["fp"], c["fn"], c["tn"]) for s, c in per_site.items()
+ },
+ "predictions": predictions,
+ }
+
+
+def _f1_from_pairs(pairs: list[tuple[int, int]]) -> float:
+ tp = sum(1 for label, pred in pairs if label == 1 and pred == 1)
+ fp = sum(1 for label, pred in pairs if label == 0 and pred == 1)
+ fn = sum(1 for label, pred in pairs if label == 1 and pred == 0)
+ denominator = 2 * tp + fp + fn
+ return (2 * tp / denominator) if denominator else 0.0
+
+
+def bootstrap_f1(
+ predictions: list[tuple[int, int]],
+ iterations: int = 2000,
+ seed: int = 1234,
+ alpha: float = 0.05,
+) -> dict[str, float]:
+ """Percentile bootstrap CI for F1 over the scored rows.
+
+ With a few dozen rows and a handful of positives, point estimates of F1 are
+ extremely unstable: resampling shows how much of an apparent gap between two
+ configurations is sampling noise rather than signal.
+ """
+ if not predictions:
+ return {"f1": 0.0, "ci_low": 0.0, "ci_high": 0.0, "iterations": 0}
+ rng = random.Random(seed)
+ n = len(predictions)
+ draws = []
+ for _ in range(iterations):
+ sample = [predictions[rng.randrange(n)] for _ in range(n)]
+ draws.append(_f1_from_pairs(sample))
+ draws.sort()
+ low = draws[int((alpha / 2) * iterations)]
+ high = draws[min(iterations - 1, int((1 - alpha / 2) * iterations))]
+ return {
+ "f1": round(_f1_from_pairs(predictions), 4),
+ "ci_low": round(low, 4),
+ "ci_high": round(high, 4),
+ "iterations": iterations,
+ }
+
+
+def paired_delta_f1(
+ baseline: list[tuple[int, int]],
+ candidate: list[tuple[int, int]],
+ iterations: int = 2000,
+ seed: int = 1234,
+ alpha: float = 0.05,
+) -> dict[str, Any]:
+ """Paired bootstrap on the F1 difference (candidate - baseline).
+
+ Paired, because both configurations score the *same* rows: resampling the
+ rows jointly removes the between-row variance that would otherwise swamp the
+ comparison. A CI spanning zero means the corpus cannot distinguish the two.
+ """
+ if not baseline or len(baseline) != len(candidate):
+ return {"delta": 0.0, "ci_low": 0.0, "ci_high": 0.0, "separable": False}
+ rng = random.Random(seed)
+ n = len(baseline)
+ draws = []
+ for _ in range(iterations):
+ idx = [rng.randrange(n) for _ in range(n)]
+ draws.append(
+ _f1_from_pairs([candidate[i] for i in idx])
+ - _f1_from_pairs([baseline[i] for i in idx])
+ )
+ draws.sort()
+ low = draws[int((alpha / 2) * iterations)]
+ high = draws[min(iterations - 1, int((1 - alpha / 2) * iterations))]
+ return {
+ "delta": round(_f1_from_pairs(candidate) - _f1_from_pairs(baseline), 4),
+ "ci_low": round(low, 4),
+ "ci_high": round(high, 4),
+ "separable": bool(low > 0 or high < 0),
+ }
+
+
+async def run_ablations(
+ corpus: Path,
+ detector: Detector,
+ logger,
+ sites: set[str] | None = None,
+ names: list[str] | None = None,
+ use_fingerprints: bool = False,
+ bootstrap_iterations: int = 2000,
+) -> dict[str, Any]:
+ """Score every configuration over one corpus. Returns a result bundle."""
+ observations = await collect_observations(corpus, sites, logger, use_fingerprints)
+ model_weight = getattr(detector.model, "ml_weight", None)
+ ablations = build_ablations(model_weight)
+ if names:
+ wanted = set(names)
+ unknown = wanted - {a.name for a in ablations}
+ if unknown:
+ raise ValueError(
+ f"Unknown ablation(s): {', '.join(sorted(unknown))}. "
+ f"Available: {', '.join(a.name for a in ablations)}"
+ )
+ ablations = [a for a in ablations if a.name in wanted]
+
+ results = [score_ablation(a, observations, detector) for a in ablations]
+
+ # Uncertainty, not just point estimates. On a corpus this small an apparent
+ # F1 gap of a few points is usually indistinguishable from noise, and saying
+ # so is the difference between a finding and an overclaim.
+ reference = next(
+ (r for r in results if "shipped" in r["tags"]),
+ results[0] if results else None,
+ )
+ # Snapshot the reference rows before the loop: the loop drops each row's
+ # per-row predictions once used, and the reference is itself one of the rows.
+ reference_predictions = list(reference["predictions"]) if reference is not None else None
+ for row in results:
+ row["bootstrap"] = bootstrap_f1(row["predictions"], iterations=bootstrap_iterations)
+ if reference_predictions is not None and row is not reference:
+ row["vs_reference"] = paired_delta_f1(
+ reference_predictions, row["predictions"],
+ iterations=bootstrap_iterations,
+ )
+ row.pop("predictions", None)
+
+ usable = sum(1 for o in observations if not o.error)
+ return {
+ "corpus": str(corpus),
+ "sites": sorted({o.site for o in observations}),
+ "rows": len(observations),
+ "usable_rows": usable,
+ "excluded_rows": len(observations) - usable,
+ "positives": sum(1 for o in observations if o.label == 1 and not o.error),
+ "negatives": sum(1 for o in observations if o.label == 0 and not o.error),
+ "fingerprints": use_fingerprints,
+ "model_ml_weight": model_weight,
+ "reference": reference["name"] if reference else None,
+ "bootstrap_iterations": bootstrap_iterations,
+ "results": results,
+ }
+
+
+def run_ablations_sync(*args, **kwargs) -> dict[str, Any]:
+ return asyncio.run(run_ablations(*args, **kwargs))
diff --git a/tests/test_ablate.py b/tests/test_ablate.py
new file mode 100644
index 0000000..153992b
--- /dev/null
+++ b/tests/test_ablate.py
@@ -0,0 +1,219 @@
+"""Ablation harness: configuration correctness and the statistics that keep the
+resulting table from overclaiming."""
+
+import asyncio
+
+import pytest
+from test_corpus import _NullLogger, make_corpus
+
+from aliens_eye.core.detector import Detector
+from aliens_eye.core.features import FEATURE_SCHEMA
+from aliens_eye.eval.ablate import (
+ FEATURE_GROUPS,
+ Observation,
+ _apply_drop,
+ _f1_from_pairs,
+ bootstrap_f1,
+ build_ablations,
+ collect_observations,
+ paired_delta_f1,
+ run_ablations,
+ score_ablation,
+)
+
+# --- configuration wiring -------------------------------------------------
+
+
+def test_feature_groups_reference_real_features():
+ """A typo in FEATURE_GROUPS would silently ablate nothing."""
+ schema = set(FEATURE_SCHEMA)
+ for group, names in FEATURE_GROUPS.items():
+ unknown = [n for n in names if n not in schema]
+ assert not unknown, f"group {group!r} names features not in FEATURE_SCHEMA: {unknown}"
+
+
+def test_every_feature_group_is_non_empty():
+ for group, names in FEATURE_GROUPS.items():
+ assert names, f"group {group!r} is empty"
+
+
+def test_build_ablations_covers_baselines_judges_and_groups():
+ names = {a.name for a in build_ablations(0.6)}
+ assert {"status_only", "status_not_404"} <= names
+ assert {"heuristic_only", "ml_only", "blended_shipped"} <= names
+ assert {f"no_{g}" for g in FEATURE_GROUPS} <= names
+
+
+def test_shipped_blend_uses_the_model_weight():
+ shipped = next(a for a in build_ablations(0.6) if a.name == "blended_shipped")
+ # ml_prob=1.0, heuristic_prob=0.0 -> probability should be the ML weight.
+ obs = Observation("s", "u", "url", 1, 200, {}, {})
+ assert shipped.combine(0.0, 1.0, obs) == pytest.approx(0.6)
+
+
+def test_judge_ablations_isolate_each_judge():
+ ablations = {a.name: a for a in build_ablations(0.6)}
+ obs = Observation("s", "u", "url", 1, 200, {}, {})
+ assert ablations["heuristic_only"].combine(0.25, 1.0, obs) == pytest.approx(0.25)
+ assert ablations["ml_only"].combine(0.25, 1.0, obs) == pytest.approx(1.0)
+
+
+def test_judge_ablations_degrade_gracefully_without_a_model():
+ ablations = {a.name: a for a in build_ablations(None)}
+ obs = Observation("s", "u", "url", 1, 200, {}, {})
+ assert ablations["ml_only"].combine(0.3, None, obs) == pytest.approx(0.3)
+
+
+def test_status_only_is_a_pure_status_check():
+ ablations = {a.name: a for a in build_ablations(0.6)}
+ status_only = ablations["status_only"]
+ # Heuristic and ML both scream "found"; the baseline must ignore them.
+ assert status_only.combine(1.0, 1.0, Observation("s", "u", "x", 1, 404, {}, {})) == 0.0
+ assert status_only.combine(0.0, 0.0, Observation("s", "u", "x", 1, 200, {}, {})) == 1.0
+
+
+def test_apply_drop_zeroes_only_the_named_group():
+ features = {name: 1.0 for name in FEATURE_SCHEMA}
+ masked = _apply_drop(features, ("timing",))
+ assert masked["response_time"] == 0.0
+ assert masked["http_200"] == 1.0
+ # The original must not be mutated: every configuration reads the same rows.
+ assert features["response_time"] == 1.0
+
+
+def test_apply_drop_without_groups_is_identity():
+ features = {"http_200": 1.0}
+ assert _apply_drop(features, ()) is features
+
+
+# --- statistics -----------------------------------------------------------
+
+
+def test_f1_from_pairs_matches_hand_calculation():
+ # 2 tp, 1 fp, 1 fn -> F1 = 2*2 / (2*2 + 1 + 1) = 0.666...
+ pairs = [(1, 1), (1, 1), (0, 1), (1, 0)]
+ assert _f1_from_pairs(pairs) == pytest.approx(2 / 3)
+
+
+def test_f1_is_zero_when_nothing_predicted_positive():
+ assert _f1_from_pairs([(1, 0), (0, 0)]) == 0.0
+
+
+def test_bootstrap_ci_brackets_the_point_estimate():
+ pairs = [(1, 1)] * 20 + [(0, 0)] * 20 + [(1, 0)] * 5 + [(0, 1)] * 5
+ result = bootstrap_f1(pairs, iterations=500)
+ assert result["ci_low"] <= result["f1"] <= result["ci_high"]
+ assert 0.0 <= result["ci_low"] <= 1.0
+
+
+def test_bootstrap_is_seed_reproducible():
+ pairs = [(1, 1)] * 10 + [(0, 1)] * 10
+ assert bootstrap_f1(pairs, iterations=200) == bootstrap_f1(pairs, iterations=200)
+
+
+def test_bootstrap_handles_empty_input():
+ assert bootstrap_f1([])["iterations"] == 0
+
+
+def test_identical_configurations_are_not_separable():
+ pairs = [(1, 1)] * 10 + [(0, 0)] * 10 + [(1, 0)] * 3
+ delta = paired_delta_f1(pairs, pairs, iterations=500)
+ assert delta["delta"] == 0.0
+ assert delta["separable"] is False
+
+
+def test_a_clearly_better_configuration_is_separable():
+ labels = [1] * 40 + [0] * 40
+ bad = [(y, 1) for y in labels] # says Found to everything
+ good = [(y, y) for y in labels] # perfect
+ delta = paired_delta_f1(bad, good, iterations=1000)
+ assert delta["delta"] > 0
+ assert delta["separable"] is True
+
+
+def test_a_tiny_difference_on_few_rows_is_not_separable():
+ """The guard against overclaiming: small corpora cannot resolve small gaps."""
+ labels = [1] * 6 + [0] * 6
+ a = [(y, y) for y in labels]
+ b = list(a)
+ b[0] = (1, 0) # one row worse
+ delta = paired_delta_f1(a, b, iterations=1000)
+ assert delta["separable"] is False
+
+
+def test_paired_delta_rejects_mismatched_lengths():
+ assert paired_delta_f1([(1, 1)], [(1, 1), (0, 0)])["separable"] is False
+
+
+# --- end to end over a corpus --------------------------------------------
+
+
+def _corpus(tmp_path, monkeypatch, found_html, not_found_html):
+ urls = {
+ "https://github.com/torvalds": (200, found_html),
+ "https://github.com/ghost1": (404, not_found_html),
+ "https://github.com/ghost2": (404, not_found_html),
+ "https://www.reddit.com/user/spez": (200, found_html),
+ "https://www.reddit.com/user/ghost3": (404, not_found_html),
+ }
+ jobs = [
+ ("github", "https://github.com/torvalds", "torvalds", 1),
+ ("github", "https://github.com/ghost1", "ghost1", 0),
+ ("github", "https://github.com/ghost2", "ghost2", 0),
+ ("reddit", "https://www.reddit.com/user/spez", "spez", 1),
+ ("reddit", "https://www.reddit.com/user/ghost3", "ghost3", 0),
+ ]
+ root, _ = make_corpus(tmp_path, monkeypatch, urls, jobs)
+ return root
+
+
+def test_run_ablations_over_a_corpus(tmp_path, monkeypatch, found_html, not_found_html, logger):
+ root = _corpus(tmp_path, monkeypatch, found_html, not_found_html)
+ detector = Detector()
+ detector.load_model(logger)
+
+ bundle = asyncio.run(run_ablations(root, detector, logger, bootstrap_iterations=200))
+ assert bundle["usable_rows"] == 5
+ assert bundle["positives"] == 2
+ assert bundle["negatives"] == 3
+ assert bundle["reference"] == "blended_shipped"
+
+ names = [r["name"] for r in bundle["results"]]
+ assert "status_only" in names and "ml_only" in names
+ for row in bundle["results"]:
+ assert "bootstrap" in row
+ assert "predictions" not in row, "per-row predictions must not leak into the report"
+ assert 0.0 <= row["overall"]["maybe_rate"] <= 1.0
+
+
+def test_run_ablations_is_deterministic(tmp_path, monkeypatch, found_html, not_found_html, logger):
+ root = _corpus(tmp_path, monkeypatch, found_html, not_found_html)
+ detector = Detector()
+ detector.load_model(logger)
+ a = asyncio.run(run_ablations(root, detector, logger, bootstrap_iterations=200))
+ b = asyncio.run(run_ablations(root, detector, logger, bootstrap_iterations=200))
+ assert a == b
+
+
+def test_run_ablations_rejects_unknown_names(tmp_path, monkeypatch, found_html, not_found_html, logger):
+ root = _corpus(tmp_path, monkeypatch, found_html, not_found_html)
+ detector = Detector()
+ with pytest.raises(ValueError, match="Unknown ablation"):
+ asyncio.run(run_ablations(root, detector, logger, names=["nope"]))
+
+
+def test_status_only_baseline_never_abstains(tmp_path, monkeypatch, found_html, not_found_html, logger):
+ """A two-state baseline must not get credit for the tri-state abstain band."""
+ root = _corpus(tmp_path, monkeypatch, found_html, not_found_html)
+ detector = Detector()
+ detector.load_model(logger)
+ observations = asyncio.run(collect_observations(root, None, logger))
+ ablations = {a.name: a for a in build_ablations(detector.model.ml_weight)}
+ result = score_ablation(ablations["status_only"], observations, detector)
+ assert result["overall"]["maybe_rate"] == 0.0
+
+
+def test_site_filter_restricts_the_evaluation(tmp_path, monkeypatch, found_html, not_found_html, logger):
+ root = _corpus(tmp_path, monkeypatch, found_html, not_found_html)
+ observations = asyncio.run(collect_observations(root, {"github"}, _NullLogger()))
+ assert {o.site for o in observations} == {"github"}