File size: 12,905 Bytes
6c516b6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | """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()
|