modul-x / tests /test_risk_scorer.py
Z User
v3.1.0: Part B architecture migration — eliminate Hugging Face inference credit dependency
6c516b6
Raw History Blame Contribute Delete
12.9 kB
"""AI Risk Scorer tests (spec §3.4 / Phase 4 / Phase 6 + Part B migration).
Pins the four invariants that make the scoring layer safe:
1. Local-only inference — every score comes from the in-process pipeline or
the heuristic; NO remote endpoint is ever contacted (Part B: the HF
Inference API path was removed by design, not by configuration).
2. Circuit breaker — model-load failures open it permanently; repeated
inference failures open it after the threshold; the heuristic takes over
with fallback_used=True.
3. Feature privacy — the feature string carries domain + SMTP metadata,
never the full address.
4. Burn-rate accounting — every verification is counted; inference vs
heuristic vs cache-hit split is observable against the <5% target.
"""
import unittest
from unittest.mock import AsyncMock, patch
from app.ml import risk_scorer as rs
from app.ml.risk_scorer import (
AIRiskScorer,
AIScore,
BURN_RATE_TARGET,
label_for_score,
score_many_by_domain,
)
from app.config import settings
def _scorer(**kw) -> AIRiskScorer:
"""A scorer with the TTL cache disabled unless a test opts in."""
defaults = dict(model="test/local-model", timeout=5,
fail_threshold=3, cooldown=300)
defaults.update(kw)
s = AIRiskScorer(**defaults)
s._score_cache = None
return s
def _fake_local(mapping=None, exc=None, loaded=True):
"""Build a fake LocalRiskScorer; returns (instance, calls)."""
calls = {"score": 0}
class FakeLocal:
def __init__(self):
self.loaded = loaded
self.last_error = None if loaded else "boom: no torch"
self.model_name = "test/local-model"
def load(self):
return loaded
def score(self, feature_text, labels=None):
calls["score"] += 1
calls["feature_text"] = feature_text
calls["labels"] = labels
if exc:
raise exc
return mapping or {
"label": "high_risk",
"score": 0.7,
"all_scores": {"high_risk": 0.7, "low_risk": 0.2, "medium_risk": 0.1},
}
return FakeLocal(), calls
class FeaturePrivacyTests(unittest.TestCase):
def test_feature_string_never_contains_the_address(self):
features = AIRiskScorer.build_features(
domain="corp.test", mx_host="mx.corp.test", smtp_class="4xx",
catch_all=True, local_part="secret.john.doe",
)
self.assertNotIn("secret.john.doe", features)
self.assertNotIn("@", features)
self.assertIn("domain=corp.test", features)
self.assertIn("smtp=4xx", features)
self.assertIn("catch_all=yes", features)
def test_local_shape_classification(self):
role = AIRiskScorer.build_features(domain="d.test", mx_host=None,
smtp_class="accept", catch_all=False,
local_part="info")
self.assertIn("local=role", role)
entropy = AIRiskScorer.build_features(domain="d.test", mx_host=None,
smtp_class="accept", catch_all=False,
local_part="ab123456")
self.assertIn("local=high_entropy", entropy)
class LocalOnlyArchitectureTests(unittest.TestCase):
"""Part B hard guarantees: the module must contain no remote path at all."""
def test_module_has_no_http_client(self):
# Part C item 4: the migration is not complete if any code path can
# reach an inference endpoint. The module must not even import httpx.
import app.ml.risk_scorer as mod
self.assertIsNone(getattr(mod, "httpx", None))
source = open(mod.__file__).read()
self.assertNotIn("router.huggingface", source)
self.assertNotIn("api-inference", source)
self.assertNotIn("InferenceClient", source)
def test_scorer_has_no_token_attribute(self):
s = _scorer()
self.assertFalse(hasattr(s, "token"))
def test_status_reports_local_backend(self):
s = _scorer()
st = s.status()
self.assertEqual(st["backend"], "local")
self.assertIn("model_loaded", st)
class LabelTests(unittest.TestCase):
def test_label_thresholds(self):
self.assertEqual(label_for_score(0.1), "low_risk")
self.assertEqual(label_for_score(0.5), "medium_risk")
self.assertEqual(label_for_score(0.9), "high_risk")
def test_label_mapping(self):
self.assertAlmostEqual(rs._label_risk("high_risk", 0.9), 0.9)
self.assertAlmostEqual(rs._label_risk("low", 0.9), 0.1)
self.assertIsNone(rs._label_risk("weird_unknown_label", 0.5))
class HeuristicTests(unittest.TestCase):
def test_greylist_scores_medium(self):
s = _scorer()
out = s.heuristic("domain=d.test mx=other smtp=4xx catch_all=yes local=normal dns_consistent=yes")
self.assertTrue(0.4 <= out.score < 0.7)
self.assertEqual(out.source, "heuristic")
self.assertTrue(out.fallback_used)
def test_trusted_platform_catchall_scores_lower(self):
s = _scorer()
trusted = s.heuristic("domain=d.test mx=trusted_platform smtp=accept catch_all=yes local=normal dns_consistent=yes")
other = s.heuristic("domain=d.test mx=other smtp=accept catch_all=yes local=normal dns_consistent=yes")
self.assertLess(trusted.score, other.score)
def test_scores_clamped(self):
s = _scorer()
out = s.heuristic("domain=d.test mx=other smtp=4xx catch_all=yes local=high_entropy dns_consistent=no")
self.assertTrue(0.0 <= out.score <= 1.0)
class LocalInferenceTests(unittest.IsolatedAsyncioTestCase):
async def _score_with(self, s, features, **fake_kw):
fake, calls = _fake_local(**fake_kw)
s._local = fake
s._load_started = True
out = await s.score(features)
return out, calls
async def test_successful_local_inference(self):
s = _scorer()
features = "domain=d.test mx=other smtp=4xx catch_all=yes local=normal dns_consistent=yes"
out, calls = await self._score_with(
s, features,
mapping={
"label": "high_risk",
"score": 0.92,
"all_scores": {"high_risk": 0.92, "low_risk": 0.05, "medium_risk": 0.03},
},
)
self.assertEqual(out.source, "inference")
self.assertFalse(out.fallback_used)
self.assertEqual(out.label, "high_risk")
self.assertIn("local", out.detail)
self.assertEqual(s.metrics.inference_calls, 1)
self.assertEqual(calls["score"], 1)
# Candidate labels ARE the risk taxonomy (zero-shot contract).
self.assertEqual(calls["labels"], ["low_risk", "medium_risk", "high_risk"])
async def test_zero_shot_distribution_weighting(self):
s = _scorer()
features = "domain=d.test mx=other smtp=4xx catch_all=yes local=normal dns_consistent=yes"
out, _ = await self._score_with(
s, features,
mapping={
"label": "high_risk",
"score": 0.7,
"all_scores": {"high_risk": 0.7, "low_risk": 0.2, "medium_risk": 0.1},
},
)
# Probability-weighted expectation over the MAPPED risks:
# high: max(0.7, 0.7)=0.70 · low: min(0.39, 1-0.2)=0.39 · med: 0.40
# (0.70*0.7 + 0.39*0.2 + 0.40*0.1) / 1.0 = 0.608 -> medium_risk bucket
self.assertAlmostEqual(out.score, 0.608, places=3)
self.assertEqual(out.label, "medium_risk")
async def test_unmappable_labels_degrade_to_heuristic(self):
s = _scorer()
out, _ = await self._score_with(
s, "domain=d.test mx=other smtp=4xx catch_all=yes local=normal dns_consistent=yes",
mapping={"label": "gibberish_label", "score": 0.99,
"all_scores": {"gibberish_label": 0.99}},
)
self.assertEqual(out.source, "heuristic")
self.assertTrue(out.fallback_used)
async def test_model_load_failure_opens_circuit_permanently(self):
s = _scorer()
fake, calls = _fake_local(loaded=False)
s._local = fake
s._load_started = False # first score() triggers the load attempt
out = await s.score("domain=d.test mx=other smtp=4xx catch_all=yes local=normal dns_consistent=yes")
self.assertTrue(out.fallback_used)
self.assertEqual(out.source, "heuristic")
self.assertTrue(s.breaker.permanently_open)
# Subsequent calls never attempt inference again.
out2 = await s.score("domain=d.test mx=other smtp=4xx catch_all=yes local=normal dns_consistent=yes")
self.assertEqual(out2.source, "heuristic")
self.assertEqual(s.metrics.circuit_opens, 1)
self.assertIn("load failed", s.breaker.open_reason)
async def test_transient_inference_failures_open_after_threshold(self):
s = _scorer(fail_threshold=2, cooldown=300)
features = "domain=d.test mx=other smtp=4xx catch_all=yes local=normal dns_consistent=yes"
fake, calls = _fake_local(exc=RuntimeError("cpu exploded"))
s._local = fake
s._load_started = True
await s.score(features)
self.assertFalse(s.breaker.is_open)
await s.score(features)
self.assertTrue(s.breaker.is_open)
async def test_disabled_inference_uses_heuristic_without_fallback_penalty(self):
# No model configured: the heuristic IS the primary source.
s = _scorer(model="")
out = await s.score("domain=d.test mx=other smtp=4xx catch_all=yes local=normal dns_consistent=yes")
self.assertEqual(out.source, "heuristic")
# Not counted as a "fallback event" — nothing was configured to fall back FROM.
self.assertEqual(s.metrics.fallback_events, 0)
async def test_master_switch_off_forces_heuristic(self):
s = _scorer()
with patch.object(settings, "ai_scorer_local", False):
out = await s.score("domain=d.test mx=other smtp=4xx catch_all=yes local=normal dns_consistent=yes")
self.assertEqual(out.source, "heuristic")
self.assertEqual(s.metrics.inference_calls, 0)
class ScoreCacheTests(unittest.IsolatedAsyncioTestCase):
"""§2.2: a repeated PII-free feature string never re-invokes the model."""
async def test_repeated_feature_string_hits_cache(self):
s = AIRiskScorer(model="test/local-model")
fake, calls = _fake_local()
s._local = fake
s._load_started = True
features = "domain=d.test mx=other smtp=4xx catch_all=yes local=normal dns_consistent=yes"
first = await s.score(features)
second = await s.score(features)
self.assertEqual(calls["score"], 1) # one inference, two answers
self.assertEqual(first.score, second.score)
self.assertEqual(s.metrics.cache_hits, 1)
self.assertEqual(s.metrics.inference_calls, 1)
async def test_disabled_cache_always_invokes(self):
s = _scorer() # _scorer() disables the cache
fake, calls = _fake_local()
s._local = fake
s._load_started = True
features = "domain=d.test mx=other smtp=4xx catch_all=yes local=normal dns_consistent=yes"
await s.score(features)
await s.score(features)
self.assertEqual(calls["score"], 2)
class BurnRateTests(unittest.IsolatedAsyncioTestCase):
async def test_metrics_track_verification_share(self):
s = _scorer(model="") # heuristic-only
features = "domain=d.test mx=other smtp=4xx catch_all=yes local=normal dns_consistent=yes"
for _ in range(10):
await s.score(features)
m = s.metrics.as_dict()
self.assertEqual(m["verifications_scored"], 10)
self.assertEqual(m["heuristic_calls"], 10)
self.assertEqual(m["inference_calls"], 0)
self.assertEqual(m["burn_rate"], 0.0)
self.assertTrue(m["burn_rate_ok"])
self.assertEqual(m["burn_rate_target"], BURN_RATE_TARGET)
async def test_score_many_by_domain(self):
s = _scorer(model="") # heuristic-only
out = await score_many_by_domain(s, {
"a.test": "domain=a.test mx=other smtp=4xx catch_all=yes local=normal dns_consistent=yes",
"b.test": "domain=b.test mx=other smtp=4xx catch_all=yes local=normal dns_consistent=yes",
})
self.assertEqual(set(out.keys()), {"a.test", "b.test"})
self.assertTrue(all(isinstance(v, AIScore) for v in out.values()))
async def test_status_shape(self):
s = _scorer()
st = s.status()
self.assertTrue(st["enabled"])
self.assertIn("circuit", st)
self.assertIn("metrics", st)
if __name__ == "__main__":
unittest.main()