eyesee commited on
Commit
4808fa3
·
1 Parent(s): fdd630d

added CORS handeling for Backend wiring and input validation issues

Browse files
.gitignore CHANGED
@@ -1,3 +1,5 @@
1
  .env
2
  __pycache__/
3
- *.pyc
 
 
 
1
  .env
2
  __pycache__/
3
+ *.pyc
4
+ .pytest_cache/
5
+ venv/
extractor.py CHANGED
@@ -17,7 +17,45 @@ Example:
17
  """
18
 
19
  import re
20
- from metrics import find_metric
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  # extract_year(text) — Find the year in a claim
23
  def extract_year(text):
@@ -120,6 +158,9 @@ def _clean_number(raw):
120
 
121
  def extract_all(text):
122
 
 
 
 
123
  # ---- STEP 1: Extract each field independently ----
124
  metric_result = find_metric(text) # Returns {"metric": ..., "confidence": ...}
125
  value = extract_value(text) # Returns float or None
 
17
  """
18
 
19
  import re
20
+ import html
21
+ import unicodedata
22
+ from metrics import find_metric
23
+
24
+
25
+ def preprocess_claim(text: str) -> str:
26
+ """
27
+ Sanitize raw user input before extraction.
28
+ Handles HTML tags, whitespace noise, zero-width Unicode chars, and encoding.
29
+
30
+ Steps:
31
+ 1. HTML-unescape — "&amp;" → "&", "&lt;" → "<"
32
+ 2. Strip HTML tags — <b>foo</b> → foo
33
+ 3. Remove zero-width / BOM chars (\u200b, \u200c, \u200d, \ufeff)
34
+ 4. NFC normalization — unify composed/decomposed Unicode forms
35
+ 5. Collapse whitespace — tabs, newlines, multiple spaces → single space
36
+ 6. Strip leading/trailing whitespace
37
+ """
38
+ # Step 1: HTML unescape (&amp; &lt; &gt; etc.)
39
+ text = html.unescape(text)
40
+
41
+ # Step 2: Strip HTML tags
42
+ text = re.sub(r"<[^>]+>", " ", text)
43
+
44
+ # Step 3: Remove zero-width and BOM characters
45
+ text = re.sub(r"[\u200b\u200c\u200d\ufeff]", "", text)
46
+
47
+ # Step 4: Unicode NFC normalization (e.g. é as one codepoint, not e + combining accent)
48
+ text = unicodedata.normalize("NFC", text)
49
+
50
+ # Step 5 & 6: Collapse whitespace and strip
51
+ text = re.sub(r"[\t\r\n]+", " ", text) # newlines/tabs → space
52
+ text = re.sub(r" {2,}", " ", text) # multiple spaces → one
53
+ text = text.strip()
54
+
55
+ return text
56
+
57
+
58
+
59
 
60
  # extract_year(text) — Find the year in a claim
61
  def extract_year(text):
 
158
 
159
  def extract_all(text):
160
 
161
+ # Sanitize input before anything else runs
162
+ text = preprocess_claim(text)
163
+
164
  # ---- STEP 1: Extract each field independently ----
165
  metric_result = find_metric(text) # Returns {"metric": ..., "confidence": ...}
166
  value = extract_value(text) # Returns float or None
main.py CHANGED
@@ -15,16 +15,28 @@ To run:
15
 
16
  Swagger docs: http://localhost:5001/docs
17
  """
 
 
 
18
 
19
  from fastapi import FastAPI, HTTPException
20
- from fastapi.responses import HTMLResponse
 
 
21
  from pydantic import BaseModel, Field
22
- from extractor import extract_all
23
- from metrics import get_all_metric_names
24
  from claim_detector import split_into_sentences, score_claim_probability
 
 
25
  from swagger_ui import get_swagger_html, tags_metadata
26
  from verifier.tier1_numeric import tier1_numeric_check
27
  from verifier.verdict_router import route_verification, VerificationResult
 
 
 
 
 
 
28
  # =============================================================================
29
  # PYDANTIC MODELS — Request/Response contracts
30
  # =============================================================================
@@ -62,17 +74,25 @@ class ExtractionResponse(BaseModel):
62
 
63
 
64
  class HealthResponse(BaseModel):
65
- """Health check response."""
66
- status: str
67
  service: str
68
  version: str
 
 
 
 
69
 
70
  model_config = {
71
  "json_schema_extra": {
72
  "example": {
73
  "status": "healthy",
74
  "service": "B-ware NLP Service",
75
- "version": "1.0.0"
 
 
 
 
76
  }
77
  }
78
  }
@@ -376,8 +396,22 @@ curl -X POST http://localhost:5001/analyze \\
376
  docs_url=None, # we override /docs below with custom settings
377
  )
378
 
 
 
 
 
 
 
 
 
 
379
 
380
-
 
 
 
 
 
381
 
382
  # ENDPOINTS
383
 
@@ -397,11 +431,33 @@ async def custom_swagger_ui():
397
  response_description="Service status and version info"
398
  )
399
  def health_check():
400
- """Check if the NLP service is running and responsive."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401
  return {
402
- "status": "healthy",
403
  "service": "B-ware NLP Service",
404
- "version": "1.0.0"
 
 
 
 
405
  }
406
 
407
 
@@ -681,7 +737,27 @@ async def verify_full(request: ClaimRequest):
681
  Returns the `tier_used` field so you know which layer produced the verdict.
682
  Use `POST /verify/deep` to force all three tiers regardless of early exit conditions.
683
  """
684
- result: VerificationResult = await route_verification(request.text, force_tier3=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
685
  return FullVerificationResult(
686
  original_text=result.original_text,
687
  tier_used=result.tier_used,
@@ -732,7 +808,27 @@ async def verify_deep(request: ClaimRequest):
732
  **Slower** than `/verify` — expect ~3–8 seconds latency (network + LLM).
733
  Subject to Gemini free-tier rate limits (15 req/min).
734
  """
735
- result: VerificationResult = await route_verification(request.text, force_tier3=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
736
  return FullVerificationResult(
737
  original_text=result.original_text,
738
  tier_used=result.tier_used,
@@ -766,8 +862,8 @@ async def verify_deep(request: ClaimRequest):
766
  # Run the server directly: python main.py
767
  if __name__ == "__main__":
768
  import uvicorn
769
- print("Starting B-ware NLP Service...")
770
- print("API docs available at: http://localhost:5001/docs")
771
  uvicorn.run(
772
  "main:app",
773
  host="0.0.0.0",
 
15
 
16
  Swagger docs: http://localhost:5001/docs
17
  """
18
+ import asyncio
19
+ import logging
20
+ import os
21
 
22
  from fastapi import FastAPI, HTTPException
23
+ from fastapi.exceptions import RequestValidationError
24
+ from fastapi.middleware.cors import CORSMiddleware
25
+ from fastapi.responses import HTMLResponse, JSONResponse
26
  from pydantic import BaseModel, Field
27
+
 
28
  from claim_detector import split_into_sentences, score_claim_probability
29
+ from extractor import extract_all, preprocess_claim
30
+ from metrics import get_all_metric_names
31
  from swagger_ui import get_swagger_html, tags_metadata
32
  from verifier.tier1_numeric import tier1_numeric_check
33
  from verifier.verdict_router import route_verification, VerificationResult
34
+
35
+ logging.basicConfig(
36
+ level=logging.INFO,
37
+ format="%(asctime)s %(name)s %(levelname)s %(message)s",
38
+ )
39
+ logger = logging.getLogger("bware.nlp")
40
  # =============================================================================
41
  # PYDANTIC MODELS — Request/Response contracts
42
  # =============================================================================
 
74
 
75
 
76
  class HealthResponse(BaseModel):
77
+ """Health check response — includes component readiness."""
78
+ status: str # "healthy" | "degraded"
79
  service: str
80
  version: str
81
+ bart_model: str # "loaded" | "not_loaded"
82
+ gemini_key: str # "configured" | "missing"
83
+ newsapi_key: str # "configured" | "missing"
84
+ factcheck_key: str # "configured" | "missing"
85
 
86
  model_config = {
87
  "json_schema_extra": {
88
  "example": {
89
  "status": "healthy",
90
  "service": "B-ware NLP Service",
91
+ "version": "1.0.0",
92
+ "bart_model": "loaded",
93
+ "gemini_key": "configured",
94
+ "newsapi_key": "missing",
95
+ "factcheck_key": "configured"
96
  }
97
  }
98
  }
 
396
  docs_url=None, # we override /docs below with custom settings
397
  )
398
 
399
+ # Configure CORS
400
+ app.add_middleware(
401
+ CORSMiddleware,
402
+ allow_origins=["http://localhost:3000",
403
+ "http://localhost:5000"],
404
+ allow_credentials=True,
405
+ allow_methods=["*"],
406
+ allow_headers=["*"]
407
+ )
408
 
409
+ @app.exception_handler(Exception)
410
+ async def generic_exception_handler(request, exc):
411
+ """Catch-all exception handler to prevent 500 errors from crashing the server."""
412
+ return JSONResponse(status_code=500,
413
+ content={"error": "Internal server error",
414
+ "detail": str(exc)})
415
 
416
  # ENDPOINTS
417
 
 
431
  response_description="Service status and version info"
432
  )
433
  def health_check():
434
+ """
435
+ Check if the NLP service is running and all components are ready.
436
+ Returns component-level status so the Node backend can make informed decisions.
437
+
438
+ - `bart_model: loaded` — BART-MNLI is warm in memory (first /verify/deep call triggers load)
439
+ - `*_key: configured` — the env var is set (non-empty); does not validate the key
440
+ - `status: degraded` — at least one key is missing (Tier 2/3 may fail)
441
+ """
442
+ from verifier.tier2_nli import _load_pipeline # local import to avoid circular
443
+
444
+ bart_status = "loaded" if _load_pipeline.cache_info().currsize > 0 else "not_loaded"
445
+ gemini_key = "configured" if os.getenv("GEMINI_API_KEY") else "missing"
446
+ newsapi_key = "configured" if os.getenv("NEWS_API_KEY") else "missing"
447
+ factcheck = "configured" if os.getenv("GOOGLE_FACT_CHECK_API_KEY") else "missing"
448
+
449
+ # Degrade if any external API key is missing (Tier 2/3 will silently skip them)
450
+ keys_ok = all(k == "configured" for k in [gemini_key, newsapi_key, factcheck])
451
+ overall = "healthy" if keys_ok else "degraded"
452
+
453
  return {
454
+ "status": overall,
455
  "service": "B-ware NLP Service",
456
+ "version": "1.0.0",
457
+ "bart_model": bart_status,
458
+ "gemini_key": gemini_key,
459
+ "newsapi_key": newsapi_key,
460
+ "factcheck_key": factcheck,
461
  }
462
 
463
 
 
737
  Returns the `tier_used` field so you know which layer produced the verdict.
738
  Use `POST /verify/deep` to force all three tiers regardless of early exit conditions.
739
  """
740
+ clean_text = preprocess_claim(request.text)
741
+ try:
742
+ result: VerificationResult = await asyncio.wait_for(
743
+ route_verification(clean_text, force_tier3=False),
744
+ timeout=30.0,
745
+ )
746
+ except asyncio.TimeoutError:
747
+ logger.warning("verify_full timed out for text: %.80s", clean_text)
748
+ return FullVerificationResult(
749
+ original_text=clean_text,
750
+ tier_used="tier1",
751
+ verdict="unverifiable",
752
+ confidence=0.0,
753
+ extracted_metric=None,
754
+ extracted_value=None,
755
+ extracted_year=None,
756
+ extraction_confidence=0.0,
757
+ evidence=[],
758
+ explanation="Verification timed out after 30 seconds.",
759
+ tiers_run=[],
760
+ )
761
  return FullVerificationResult(
762
  original_text=result.original_text,
763
  tier_used=result.tier_used,
 
808
  **Slower** than `/verify` — expect ~3–8 seconds latency (network + LLM).
809
  Subject to Gemini free-tier rate limits (15 req/min).
810
  """
811
+ clean_text = preprocess_claim(request.text)
812
+ try:
813
+ result: VerificationResult = await asyncio.wait_for(
814
+ route_verification(clean_text, force_tier3=True),
815
+ timeout=30.0,
816
+ )
817
+ except asyncio.TimeoutError:
818
+ logger.warning("verify_deep timed out for text: %.80s", clean_text)
819
+ return FullVerificationResult(
820
+ original_text=clean_text,
821
+ tier_used="tier1",
822
+ verdict="unverifiable",
823
+ confidence=0.0,
824
+ extracted_metric=None,
825
+ extracted_value=None,
826
+ extracted_year=None,
827
+ extraction_confidence=0.0,
828
+ evidence=[],
829
+ explanation="Verification timed out after 30 seconds.",
830
+ tiers_run=[],
831
+ )
832
  return FullVerificationResult(
833
  original_text=result.original_text,
834
  tier_used=result.tier_used,
 
862
  # Run the server directly: python main.py
863
  if __name__ == "__main__":
864
  import uvicorn
865
+ logger.info("Starting B-ware NLP Service...")
866
+ logger.info("API docs available at: http://localhost:5001/docs")
867
  uvicorn.run(
868
  "main:app",
869
  host="0.0.0.0",
tests/test_tier2_nli.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ test_tier2_nli.py — Tests for Tier 2: NLI evidence scoring
3
+ ===========================================================
4
+ Run with: pytest tests/test_tier2_nli.py -v
5
+
6
+ WHAT WE'RE TESTING:
7
+ - Label mapping (_map_label): raw HuggingFace labels → our NLI vocabulary
8
+ - Empty/short input handling: graceful degradation when no evidence
9
+ - Aggregation logic: majority voting across multiple snippets
10
+ - Confidence averaging: math correctness
11
+
12
+ WHY WE MOCK:
13
+ The real NLI pipeline downloads a 1.6GB model from HuggingFace.
14
+ In tests, we replace _run_nli_sync with a fake that returns
15
+ predictable results instantly. This way:
16
+ - Tests run in <1 second (not 30+ seconds for model download)
17
+ - Tests work offline (no internet needed)
18
+ - Tests are deterministic (same input → always same output)
19
+
20
+ HOW MOCKING WORKS:
21
+ @patch("verifier.tier2_nli._run_nli_sync")
22
+ def test_something(self, mock_nli):
23
+ mock_nli.return_value = {"labels": [...], "scores": [...]}
24
+
25
+ This says: "Wherever _run_nli_sync is called inside tier2_nli.py,
26
+ don't actually call it — use this fake return value instead."
27
+
28
+ The mock object is passed as the LAST parameter to the test function
29
+ (after self). If you have multiple @patch decorators, they're passed
30
+ in REVERSE order (bottom decorator → first parameter).
31
+ """
32
+
33
+ import sys
34
+ import os
35
+ import asyncio
36
+
37
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
38
+
39
+ from unittest.mock import patch, MagicMock
40
+ from verifier.tier2_nli import run_nli, _map_label, Tier2Result, NliResult
41
+ from verifier.evidence_fetcher import EvidenceSnippet
42
+
43
+
44
+ # =============================================================================
45
+ # HELPER: Create fake evidence snippets for testing
46
+ # =============================================================================
47
+
48
+ def _make_snippet(text: str, source: str = "TestSource") -> EvidenceSnippet:
49
+ """
50
+ Factory function to create EvidenceSnippet objects for tests.
51
+
52
+ WHY A HELPER?
53
+ EvidenceSnippet has 6 fields. Writing them out every time is tedious
54
+ and makes tests harder to read. This helper provides sensible defaults
55
+ so each test only specifies what matters (the text content).
56
+ """
57
+ return EvidenceSnippet(
58
+ source=source,
59
+ title=f"Article about {text[:30]}",
60
+ snippet=text,
61
+ url="https://example.com/article",
62
+ published_date="2024-01-15",
63
+ evidence_type="news",
64
+ )
65
+
66
+
67
+ # =============================================================================
68
+ # LABEL MAPPING TESTS
69
+ # =============================================================================
70
+
71
+ class TestMapLabel:
72
+ """
73
+ _map_label converts HuggingFace's zero-shot labels to our NLI vocabulary.
74
+
75
+ The pipeline returns labels like "supports the claim" but we need
76
+ standard NLI terms: entailment, contradiction, neutral.
77
+ """
78
+
79
+ def test_supports_maps_to_entailment(self):
80
+ """'supports the claim' → 'entailment'"""
81
+ assert _map_label("supports the claim") == "entailment"
82
+
83
+ def test_contradicts_maps_to_contradiction(self):
84
+ """'contradicts the claim' → 'contradiction'"""
85
+ assert _map_label("contradicts the claim") == "contradiction"
86
+
87
+ def test_unrelated_maps_to_neutral(self):
88
+ """'unrelated to the claim' → 'neutral'"""
89
+ assert _map_label("unrelated to the claim") == "neutral"
90
+
91
+ def test_unknown_label_maps_to_neutral(self):
92
+ """Any unrecognized label defaults to 'neutral' (safe fallback)."""
93
+ assert _map_label("something unexpected") == "neutral"
94
+
95
+ def test_case_insensitive(self):
96
+ """Label matching should be case-insensitive."""
97
+ assert _map_label("SUPPORTS the claim") == "entailment"
98
+ assert _map_label("Contradicts The Claim") == "contradiction"
99
+
100
+
101
+ # =============================================================================
102
+ # EMPTY / SHORT INPUT TESTS
103
+ # =============================================================================
104
+
105
+ class TestRunNliEdgeCases:
106
+ """
107
+ Tests for run_nli when input is empty or too short.
108
+ No mocking needed — these paths never reach the NLI model.
109
+ """
110
+
111
+ def test_empty_snippets_returns_insufficient_evidence(self):
112
+ """
113
+ No evidence at all → verdict should be 'insufficient_evidence'.
114
+
115
+ WHY:
116
+ If the evidence fetcher found 0 results (API down, no matches),
117
+ we can't make any NLI judgment. 'insufficient_evidence' tells
118
+ the verdict router to escalate to Tier 3.
119
+ """
120
+ result = asyncio.run(run_nli(claim="GDP grew 7.5%", snippets=[]))
121
+
122
+ assert result.verdict == "insufficient_evidence"
123
+ assert result.confidence == 0.0
124
+ assert result.nli_results == []
125
+ assert result.evidence_count == 0
126
+
127
+ def test_snippets_too_short_are_skipped(self):
128
+ """
129
+ Snippets shorter than 10 characters are skipped.
130
+
131
+ WHY:
132
+ Tiny snippets like "N/A" or "..." would produce garbage NLI scores.
133
+ The 10-char minimum filters them out. If ALL snippets are too short,
134
+ we get insufficient_evidence (same as empty).
135
+ """
136
+ short_snippets = [
137
+ _make_snippet("short"), # 5 chars — skipped
138
+ _make_snippet("tiny"), # 4 chars — skipped
139
+ _make_snippet(""), # 0 chars — skipped
140
+ ]
141
+ result = asyncio.run(run_nli(
142
+ claim="GDP grew 7.5%",
143
+ snippets=short_snippets
144
+ ))
145
+
146
+ assert result.verdict == "insufficient_evidence"
147
+ assert result.evidence_count == 0
148
+
149
+
150
+ # =============================================================================
151
+ # AGGREGATION TESTS (with mocked NLI model)
152
+ # =============================================================================
153
+
154
+ class TestNliAggregation:
155
+ """
156
+ Tests for the majority voting + confidence averaging logic.
157
+
158
+ HOW MAJORITY VOTING WORKS (from tier2_nli.py):
159
+ 1. Each snippet gets an NLI label (entailment/contradiction/neutral)
160
+ 2. We count how many snippets got each label
161
+ 3. The label with the most votes wins
162
+ 4. If tied, the label with the highest total score wins
163
+ 5. Confidence = average score of the winning label's snippets
164
+
165
+ We mock _run_nli_sync to control exactly what the model "returns".
166
+ """
167
+
168
+ @patch("verifier.tier2_nli._run_nli_sync")
169
+ def test_entailment_wins_majority(self, mock_nli):
170
+ """
171
+ 3 out of 5 snippets support the claim → verdict = entailment.
172
+
173
+ WHAT THE MOCK DOES:
174
+ mock_nli.side_effect = [...] means "return these values in order".
175
+ First call returns entailment, second returns entailment, etc.
176
+ """
177
+ # Simulate 5 NLI calls: 3 support, 1 contradicts, 1 neutral
178
+ mock_nli.side_effect = [
179
+ {"labels": ["supports the claim", "contradicts the claim", "unrelated to the claim"],
180
+ "scores": [0.85, 0.10, 0.05]},
181
+ {"labels": ["supports the claim", "unrelated to the claim", "contradicts the claim"],
182
+ "scores": [0.78, 0.15, 0.07]},
183
+ {"labels": ["supports the claim", "contradicts the claim", "unrelated to the claim"],
184
+ "scores": [0.92, 0.05, 0.03]},
185
+ {"labels": ["contradicts the claim", "supports the claim", "unrelated to the claim"],
186
+ "scores": [0.70, 0.20, 0.10]},
187
+ {"labels": ["unrelated to the claim", "supports the claim", "contradicts the claim"],
188
+ "scores": [0.60, 0.25, 0.15]},
189
+ ]
190
+
191
+ snippets = [_make_snippet(f"Evidence snippet number {i} about GDP growth rates in India")
192
+ for i in range(5)]
193
+
194
+ result = asyncio.run(run_nli(claim="India's GDP grew 7.5% in 2024", snippets=snippets))
195
+
196
+ assert result.verdict == "entailment"
197
+ assert result.evidence_count == 5
198
+ # Confidence should be average of the 3 entailment scores: (0.85+0.78+0.92)/3
199
+ expected_conf = round((0.85 + 0.78 + 0.92) / 3, 4)
200
+ assert result.confidence == expected_conf
201
+
202
+ @patch("verifier.tier2_nli._run_nli_sync")
203
+ def test_contradiction_wins_majority(self, mock_nli):
204
+ """
205
+ Majority of snippets contradict the claim → verdict = contradiction.
206
+ """
207
+ mock_nli.side_effect = [
208
+ {"labels": ["contradicts the claim", "supports the claim", "unrelated to the claim"],
209
+ "scores": [0.88, 0.08, 0.04]},
210
+ {"labels": ["contradicts the claim", "unrelated to the claim", "supports the claim"],
211
+ "scores": [0.75, 0.15, 0.10]},
212
+ {"labels": ["supports the claim", "contradicts the claim", "unrelated to the claim"],
213
+ "scores": [0.65, 0.20, 0.15]},
214
+ ]
215
+
216
+ snippets = [_make_snippet(f"Contradicting evidence {i} about inflation rates")
217
+ for i in range(3)]
218
+
219
+ result = asyncio.run(run_nli(claim="Inflation was 4%", snippets=snippets))
220
+
221
+ assert result.verdict == "contradiction"
222
+ assert result.evidence_count == 3
223
+
224
+ @patch("verifier.tier2_nli._run_nli_sync")
225
+ def test_single_snippet(self, mock_nli):
226
+ """
227
+ Only 1 snippet → that snippet's label becomes the verdict.
228
+ No voting needed; confidence = that snippet's score.
229
+ """
230
+ mock_nli.return_value = {
231
+ "labels": ["supports the claim", "contradicts the claim", "unrelated to the claim"],
232
+ "scores": [0.91, 0.06, 0.03],
233
+ }
234
+
235
+ snippets = [_make_snippet("India's GDP growth exceeded expectations reaching 7.4 percent")]
236
+ result = asyncio.run(run_nli(claim="GDP was 7.5%", snippets=snippets))
237
+
238
+ assert result.verdict == "entailment"
239
+ assert result.confidence == 0.91
240
+ assert result.evidence_count == 1
241
+ assert len(result.nli_results) == 1
242
+ assert result.nli_results[0].label == "entailment"
tests/test_tier3_llm.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ test_tier3_llm.py — Tests for Tier 3: LLM reasoning via Gemini
3
+ ===============================================================
4
+ Run with: pytest tests/test_tier3_llm.py -v
5
+
6
+ WHAT WE'RE TESTING:
7
+ - Prompt building: correct structure for all data combinations
8
+ - Response parsing: valid JSON, markdown-wrapped JSON, garbage input
9
+ - Graceful degradation: missing API key, API errors, invalid verdicts
10
+ - End-to-end tier3_llm_check with mocked Gemini responses
11
+
12
+ WHY WE TEST PARSING SO HEAVILY:
13
+ LLMs are unpredictable. Gemini might return:
14
+ - Clean JSON: {"verdict": "accurate", ...}
15
+ - Markdown-wrapped: ```json\n{"verdict": "accurate", ...}\n```
16
+ - With extra text: "Here's my analysis:\n{...}"
17
+ - Complete garbage: "I cannot determine..."
18
+ Our parser must handle ALL of these. Each test covers one scenario.
19
+ """
20
+
21
+ import sys
22
+ import os
23
+ import asyncio
24
+
25
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
26
+
27
+ from unittest.mock import patch, AsyncMock
28
+ from verifier.tier3_llm import (
29
+ _build_prompt,
30
+ _parse_llm_response,
31
+ tier3_llm_check,
32
+ EvidenceSummary,
33
+ Tier3Result,
34
+ )
35
+
36
+
37
+ # =============================================================================
38
+ # PROMPT BUILDING TESTS
39
+ # =============================================================================
40
+
41
+ class TestBuildPrompt:
42
+ """
43
+ _build_prompt constructs the text sent to Gemini.
44
+ It must include ALL available context and handle missing data gracefully.
45
+ """
46
+
47
+ def test_full_numeric_data(self):
48
+ """
49
+ When we have official values from Tier 1, the prompt should include
50
+ both the claimed and official numbers plus the percentage error.
51
+ """
52
+ prompt = _build_prompt(
53
+ claim="India's GDP grew 7.5% in 2024",
54
+ metric="GDP growth rate",
55
+ claimed_value=7.5,
56
+ year=2024,
57
+ official_value=6.49,
58
+ percentage_error=15.56,
59
+ official_source="World Bank",
60
+ evidence_snippets=[],
61
+ )
62
+
63
+ # Check that key numeric data appears in the prompt
64
+ assert "7.5" in prompt # claimed value
65
+ assert "6.49" in prompt # official value
66
+ assert "15.56" in prompt # percentage error
67
+ assert "World Bank" in prompt # source
68
+ assert "2024" in prompt # year
69
+ assert "GDP growth rate" in prompt
70
+
71
+ def test_no_numeric_data(self):
72
+ """
73
+ When extraction failed (no metric/value), the prompt should say so
74
+ rather than crash or show 'None'.
75
+ """
76
+ prompt = _build_prompt(
77
+ claim="The economy is doing great",
78
+ metric=None,
79
+ claimed_value=None,
80
+ year=None,
81
+ official_value=None,
82
+ percentage_error=None,
83
+ official_source=None,
84
+ evidence_snippets=[],
85
+ )
86
+
87
+ assert "No numeric data" in prompt
88
+ assert "None" not in prompt # Should not leak Python's None into the prompt
89
+
90
+ def test_metric_but_no_official_value(self):
91
+ """
92
+ Metric extracted but World Bank has no data.
93
+ Common for metrics like 'fiscal deficit' where data lags.
94
+ """
95
+ prompt = _build_prompt(
96
+ claim="Fiscal deficit was 5.9% in 2025",
97
+ metric="fiscal deficit",
98
+ claimed_value=5.9,
99
+ year=2025,
100
+ official_value=None,
101
+ percentage_error=None,
102
+ official_source=None,
103
+ evidence_snippets=[],
104
+ )
105
+
106
+ assert "No official numeric data available" in prompt
107
+ assert "5.9" in prompt
108
+ assert "2025" in prompt
109
+
110
+ def test_evidence_snippets_included(self):
111
+ """
112
+ When evidence snippets exist, they should appear numbered in the prompt.
113
+ """
114
+ snippets = [
115
+ EvidenceSummary(
116
+ source="Reuters", snippet="India GDP grew 6.5% in 2024",
117
+ url="https://reuters.com/article", evidence_type="news"
118
+ ),
119
+ EvidenceSummary(
120
+ source="AFP Fact Check", snippet="Claim of 7.5% GDP is misleading",
121
+ url="https://factcheck.afp.com/123", evidence_type="fact_check"
122
+ ),
123
+ ]
124
+
125
+ prompt = _build_prompt(
126
+ claim="GDP grew 7.5%", metric="GDP growth rate",
127
+ claimed_value=7.5, year=2024,
128
+ official_value=6.49, percentage_error=15.56,
129
+ official_source="World Bank",
130
+ evidence_snippets=snippets,
131
+ )
132
+
133
+ assert "Reuters" in prompt
134
+ assert "AFP Fact Check" in prompt
135
+ assert "[1]" in prompt # Numbered evidence
136
+ assert "[2]" in prompt
137
+ assert "NEWS" in prompt # evidence_type shown in uppercase
138
+ assert "FACT_CHECK" in prompt
139
+
140
+ def test_prompt_has_verdict_definitions(self):
141
+ """
142
+ The prompt must always include verdict definitions so the LLM
143
+ knows our exact thresholds and vocabulary.
144
+ """
145
+ prompt = _build_prompt(
146
+ claim="test", metric=None, claimed_value=None, year=None,
147
+ official_value=None, percentage_error=None,
148
+ official_source=None, evidence_snippets=[],
149
+ )
150
+
151
+ assert "accurate" in prompt
152
+ assert "misleading" in prompt
153
+ assert "false" in prompt
154
+ assert "unverifiable" in prompt
155
+ assert "RESPOND WITH ONLY VALID JSON" in prompt
156
+
157
+
158
+ # =============================================================================
159
+ # RESPONSE PARSING TESTS
160
+ # =============================================================================
161
+
162
+ class TestParseResponse:
163
+ """
164
+ _parse_llm_response must extract valid JSON from messy LLM output.
165
+
166
+ WHY THIS IS CRITICAL:
167
+ If parsing fails, tier3_llm_check returns "unverifiable" — which means
168
+ we wasted an API call and the user gets no useful answer. Every edge
169
+ case we handle here = fewer false "unverifiable" results.
170
+ """
171
+
172
+ def test_clean_json(self):
173
+ """Perfect JSON — the happy path."""
174
+ raw = '{"verdict": "accurate", "confidence": 0.92, "explanation": "Data matches.", "sources_used": ["World Bank"]}'
175
+ result = _parse_llm_response(raw)
176
+
177
+ assert result is not None
178
+ assert result["verdict"] == "accurate"
179
+ assert result["confidence"] == 0.92
180
+ assert result["explanation"] == "Data matches."
181
+ assert result["sources_used"] == ["World Bank"]
182
+
183
+ def test_markdown_wrapped_json(self):
184
+ """
185
+ LLMs often wrap JSON in ```json ... ``` markdown blocks.
186
+ Our parser strips these wrappers.
187
+ """
188
+ raw = '```json\n{"verdict": "misleading", "confidence": 0.71, "explanation": "Error is 15%.", "sources_used": []}\n```'
189
+ result = _parse_llm_response(raw)
190
+
191
+ assert result is not None
192
+ assert result["verdict"] == "misleading"
193
+
194
+ def test_json_with_extra_text(self):
195
+ """
196
+ LLM adds conversational text before/after the JSON.
197
+ Our regex extracts the {...} block.
198
+ """
199
+ raw = 'Here is my analysis:\n\n{"verdict": "false", "confidence": 0.88, "explanation": "Clearly wrong.", "sources_used": ["Reuters"]}\n\nHope this helps!'
200
+ result = _parse_llm_response(raw)
201
+
202
+ assert result is not None
203
+ assert result["verdict"] == "false"
204
+
205
+ def test_garbage_input_returns_none(self):
206
+ """Completely unparseable text → None."""
207
+ assert _parse_llm_response("I cannot determine the accuracy.") is None
208
+ assert _parse_llm_response("") is None
209
+ assert _parse_llm_response(None) is None
210
+
211
+ def test_invalid_json_returns_none(self):
212
+ """Malformed JSON (missing quotes, trailing commas) → None."""
213
+ raw = '{verdict: accurate, confidence: 0.9}' # missing quotes
214
+ assert _parse_llm_response(raw) is None
215
+
216
+
217
+ # =============================================================================
218
+ # END-TO-END TIER 3 TESTS (with mocked Gemini API)
219
+ # =============================================================================
220
+
221
+ class TestTier3LlmCheck:
222
+ """
223
+ Tests for the full tier3_llm_check function.
224
+
225
+ MOCKING STRATEGY:
226
+ We mock _call_gemini (the HTTP call to Gemini) not the whole function.
227
+ This way we still test:
228
+ - Prompt building
229
+ - Response parsing
230
+ - Verdict normalization
231
+ - Confidence clamping
232
+ Only the actual HTTP call is faked.
233
+
234
+ AsyncMock vs MagicMock:
235
+ _call_gemini is an async function (async def _call_gemini).
236
+ Regular MagicMock doesn't work with `await`. AsyncMock does.
237
+ """
238
+
239
+ @patch("verifier.tier3_llm._call_gemini", new_callable=AsyncMock)
240
+ def test_successful_analysis(self, mock_gemini):
241
+ """Happy path: Gemini returns valid JSON."""
242
+ mock_gemini.return_value = '{"verdict": "accurate", "confidence": 0.95, "explanation": "The claimed GDP growth of 7.5% matches World Bank data.", "sources_used": ["World Bank"]}'
243
+
244
+ result = asyncio.run(tier3_llm_check(
245
+ claim="GDP grew 7.5% in 2024",
246
+ metric="GDP growth rate",
247
+ claimed_value=7.5,
248
+ year=2024,
249
+ official_value=7.48,
250
+ percentage_error=0.27,
251
+ official_source="World Bank",
252
+ ))
253
+
254
+ assert isinstance(result, Tier3Result)
255
+ assert result.verdict == "accurate"
256
+ assert result.confidence == 0.95
257
+ assert "World Bank" in result.sources_used
258
+
259
+ @patch("verifier.tier3_llm._call_gemini", new_callable=AsyncMock)
260
+ def test_no_api_key(self, mock_gemini):
261
+ """
262
+ When GEMINI_API_KEY is not set, _call_gemini returns None.
263
+ tier3_llm_check should return 'unverifiable' gracefully.
264
+
265
+ WHY THIS MATTERS:
266
+ In development, your teammates might not have a Gemini key.
267
+ The system should degrade gracefully, not crash.
268
+ """
269
+ mock_gemini.return_value = None # simulates no API key
270
+
271
+ result = asyncio.run(tier3_llm_check(claim="GDP grew 7.5%"))
272
+
273
+ assert result.verdict == "unverifiable"
274
+ assert result.confidence == 0.0
275
+ assert "unavailable" in result.explanation.lower() or "unparseable" in result.explanation.lower()
276
+
277
+ @patch("verifier.tier3_llm._call_gemini", new_callable=AsyncMock)
278
+ def test_invalid_verdict_normalized(self, mock_gemini):
279
+ """
280
+ If Gemini returns a verdict not in our vocabulary (e.g., "partially true"),
281
+ it should be normalized to 'unverifiable'.
282
+
283
+ WHY:
284
+ The frontend expects exactly 4 verdict strings for color coding.
285
+ Any other string would break the UI.
286
+ """
287
+ mock_gemini.return_value = '{"verdict": "partially true", "confidence": 0.7, "explanation": "Some parts are right.", "sources_used": []}'
288
+
289
+ result = asyncio.run(tier3_llm_check(claim="GDP grew 7.5%"))
290
+
291
+ assert result.verdict == "unverifiable" # normalized from "partially true"
292
+
293
+ @patch("verifier.tier3_llm._call_gemini", new_callable=AsyncMock)
294
+ def test_confidence_clamped_to_range(self, mock_gemini):
295
+ """
296
+ If Gemini returns confidence > 1.0 or < 0.0, it should be clamped.
297
+
298
+ WHY:
299
+ LLMs sometimes return 95 instead of 0.95, or -0.1 for uncertainty.
300
+ Clamping to [0.0, 1.0] prevents UI bugs (progress bars overflowing, etc).
301
+ """
302
+ mock_gemini.return_value = '{"verdict": "accurate", "confidence": 95.0, "explanation": "Sure.", "sources_used": []}'
303
+
304
+ result = asyncio.run(tier3_llm_check(claim="GDP grew 7.5%"))
305
+
306
+ assert result.confidence == 1.0 # clamped from 95.0
307
+
308
+ @patch("verifier.tier3_llm._call_gemini", new_callable=AsyncMock)
309
+ def test_unparseable_response(self, mock_gemini):
310
+ """Gemini returns non-JSON text → graceful degradation."""
311
+ mock_gemini.return_value = "I'm sorry, I cannot verify economic claims."
312
+
313
+ result = asyncio.run(tier3_llm_check(claim="GDP grew 7.5%"))
314
+
315
+ assert result.verdict == "unverifiable"
316
+ assert result.raw_response == "I'm sorry, I cannot verify economic claims."
tests/test_verdict_router.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ test_verdict_router.py — Tests for the RAV engine orchestrator
3
+ ==============================================================
4
+ Run with: pytest tests/test_verdict_router.py -v
5
+
6
+ WHAT WE'RE TESTING:
7
+ - Verdict rule functions: _verdict_from_error, _nli_to_verdict
8
+ - Routing logic: when does Tier 1 short-circuit? When does it escalate?
9
+ - force_tier3: does it bypass all early returns?
10
+
11
+ MOCKING STRATEGY:
12
+ We mock ALL three tier functions + the extractor + evidence fetcher.
13
+ This isolates the ROUTING LOGIC from the actual verification logic.
14
+
15
+ Think of it like testing a traffic signal controller:
16
+ - We don't care if the roads actually have cars
17
+ - We care that the lights change at the right times
18
+ - So we simulate "cars detected" and check which light turns green
19
+
20
+ MOCK HIERARCHY (what calls what):
21
+ route_verification
22
+ ├── extract_all ← mocked (no regex needed)
23
+ ├── tier1_numeric_check ← mocked (no World Bank API call)
24
+ ├── fetch_evidence ← mocked (no NewsAPI/Google call)
25
+ ├── run_nli ← mocked (no BART model)
26
+ └── tier3_llm_check ← mocked (no Gemini call)
27
+ """
28
+
29
+ import sys
30
+ import os
31
+ import asyncio
32
+
33
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
34
+
35
+ from unittest.mock import patch, AsyncMock, MagicMock
36
+ from verifier.verdict_router import (
37
+ _verdict_from_error,
38
+ _nli_to_verdict,
39
+ route_verification,
40
+ VerificationResult,
41
+ TIER1_ERROR_CLEAR_LOW,
42
+ TIER1_ERROR_CLEAR_HIGH,
43
+ TIER2_CONFIDENCE_MIN,
44
+ )
45
+ from verifier.tier1_numeric import WorldBankNumericCheck
46
+ from verifier.tier2_nli import Tier2Result, NliResult
47
+ from verifier.tier3_llm import Tier3Result
48
+ from verifier.evidence_fetcher import EvidenceSnippet
49
+
50
+
51
+ # =============================================================================
52
+ # VERDICT RULE TESTS (pure functions, no mocking needed)
53
+ # =============================================================================
54
+
55
+ class TestVerdictFromError:
56
+ """
57
+ _verdict_from_error maps percentage_error → verdict string.
58
+
59
+ These are the SAME thresholds used in /verify/quick.
60
+ By centralizing them in verdict_router.py, we ensure consistency
61
+ across all endpoints.
62
+ """
63
+
64
+ def test_none_returns_unverifiable(self):
65
+ """No data at all → can't make a judgment."""
66
+ assert _verdict_from_error(None) == "unverifiable"
67
+
68
+ def test_zero_error_is_accurate(self):
69
+ """0% error = exact match = accurate."""
70
+ assert _verdict_from_error(0.0) == "accurate"
71
+
72
+ def test_below_5_is_accurate(self):
73
+ """4.99% error → within tolerance → accurate."""
74
+ assert _verdict_from_error(4.99) == "accurate"
75
+
76
+ def test_exactly_5_is_misleading(self):
77
+ """5.0% is AT the boundary → misleading (not accurate)."""
78
+ assert _verdict_from_error(5.0) == "misleading"
79
+
80
+ def test_between_5_and_20_is_misleading(self):
81
+ """15% error → misleading range."""
82
+ assert _verdict_from_error(15.0) == "misleading"
83
+
84
+ def test_exactly_20_is_false(self):
85
+ """20.0% is AT the boundary → false."""
86
+ assert _verdict_from_error(20.0) == "false"
87
+
88
+ def test_above_20_is_false(self):
89
+ """50% error → clearly false."""
90
+ assert _verdict_from_error(50.0) == "false"
91
+
92
+
93
+ class TestNliToVerdict:
94
+ """
95
+ _nli_to_verdict maps NLI aggregated labels to our verdict vocabulary.
96
+
97
+ WHY THE MAPPING EXISTS:
98
+ NLI models speak in terms of entailment/contradiction/neutral.
99
+ Our API speaks in terms of accurate/false/unverifiable.
100
+ This function is the translation layer.
101
+ """
102
+
103
+ def test_entailment_maps_to_accurate(self):
104
+ assert _nli_to_verdict("entailment") == "accurate"
105
+
106
+ def test_contradiction_maps_to_false(self):
107
+ assert _nli_to_verdict("contradiction") == "false"
108
+
109
+ def test_neutral_maps_to_unverifiable(self):
110
+ assert _nli_to_verdict("neutral") == "unverifiable"
111
+
112
+ def test_insufficient_evidence_maps_to_unverifiable(self):
113
+ assert _nli_to_verdict("insufficient_evidence") == "unverifiable"
114
+
115
+ def test_unknown_maps_to_unverifiable(self):
116
+ """Safety net: any unrecognized label → unverifiable."""
117
+ assert _nli_to_verdict("something_weird") == "unverifiable"
118
+
119
+
120
+ # =============================================================================
121
+ # ROUTING LOGIC TESTS (full mocking)
122
+ # =============================================================================
123
+
124
+ # Helper: create a standard extraction result
125
+ def _fake_extraction(metric="GDP growth rate", value=7.5, year=2024, confidence=0.9):
126
+ return {
127
+ "original_text": f"Claims {metric} was {value} in {year}",
128
+ "metric": metric, "value": value, "year": year,
129
+ "confidence": confidence,
130
+ }
131
+
132
+ # Helper: create a Tier 1 result
133
+ def _fake_t1(official_value=6.49, percentage_error=15.56):
134
+ return WorldBankNumericCheck(
135
+ official_value=official_value, claimed_value=7.5,
136
+ percentage_error=percentage_error, source="World Bank",
137
+ indicator_code="NY.GDP.MKTP.KD.ZG",
138
+ source_url="https://data.worldbank.org/indicator/NY.GDP.MKTP.KD.ZG?locations=IN",
139
+ year=2024,
140
+ )
141
+
142
+
143
+ class TestRoutingLogic:
144
+ """
145
+ Tests for the main route_verification function.
146
+
147
+ IMPORTANT: We patch at the IMPORT PATH, not the definition path.
148
+ verdict_router.py does: from extractor import extract_all
149
+ So we patch "verifier.verdict_router.extract_all" not "extractor.extract_all".
150
+ This is a common pytest gotcha!
151
+ """
152
+
153
+ @patch("verifier.verdict_router.tier1_numeric_check", new_callable=AsyncMock)
154
+ @patch("verifier.verdict_router.extract_all")
155
+ def test_tier1_fast_path_accurate(self, mock_extract, mock_t1):
156
+ """
157
+ SCENARIO: High extraction confidence + low error → Tier 1 alone is enough.
158
+
159
+ Conditions for fast path (all must be true):
160
+ 1. official_value is not None (World Bank returned data)
161
+ 2. percentage_error < 5% OR >= 20% (clear-cut case)
162
+ 3. extraction confidence >= 0.8
163
+ 4. force_tier3 is False
164
+
165
+ Result: Returns immediately with tier_used="tier1", skips Tier 2/3.
166
+ """
167
+ mock_extract.return_value = _fake_extraction(confidence=0.9)
168
+ mock_t1.return_value = _fake_t1(official_value=7.48, percentage_error=0.27)
169
+
170
+ result = asyncio.run(route_verification("GDP grew 7.5% in 2024"))
171
+
172
+ assert result.tier_used == "tier1"
173
+ assert result.verdict == "accurate" # 0.27% error < 5%
174
+ assert result.tiers_run == ["tier1"]
175
+ assert result.evidence == [] # No evidence fetched
176
+
177
+ @patch("verifier.verdict_router.tier1_numeric_check", new_callable=AsyncMock)
178
+ @patch("verifier.verdict_router.extract_all")
179
+ def test_tier1_fast_path_false(self, mock_extract, mock_t1):
180
+ """
181
+ SCENARIO: Clear error >= 20% → Tier 1 says 'false', no escalation.
182
+ """
183
+ mock_extract.return_value = _fake_extraction(confidence=0.9)
184
+ mock_t1.return_value = _fake_t1(official_value=5.0, percentage_error=50.0)
185
+
186
+ result = asyncio.run(route_verification("GDP grew 7.5% in 2024"))
187
+
188
+ assert result.tier_used == "tier1"
189
+ assert result.verdict == "false" # 50% error >= 20%
190
+
191
+ @patch("verifier.verdict_router.run_nli", new_callable=AsyncMock)
192
+ @patch("verifier.verdict_router.fetch_evidence", new_callable=AsyncMock)
193
+ @patch("verifier.verdict_router.tier1_numeric_check", new_callable=AsyncMock)
194
+ @patch("verifier.verdict_router.extract_all")
195
+ def test_escalates_to_tier2_ambiguous_error(self, mock_extract, mock_t1, mock_evidence, mock_nli):
196
+ """
197
+ SCENARIO: Error is 15% (ambiguous zone 5-20%) → escalates to Tier 2.
198
+ Tier 2 is confident (0.72 >= 0.6) → returns merged result.
199
+
200
+ WHY ESCALATION:
201
+ 15% error is in the "misleading" zone, but we're not 100% sure.
202
+ Maybe the World Bank data is outdated, or the metric was misidentified.
203
+ Tier 2 checks news evidence to build more confidence.
204
+ """
205
+ mock_extract.return_value = _fake_extraction(confidence=0.9)
206
+ mock_t1.return_value = _fake_t1(official_value=6.49, percentage_error=15.56)
207
+ mock_evidence.return_value = [
208
+ EvidenceSnippet(source="Reuters", title="GDP Report",
209
+ snippet="India GDP grew at 6.5 percent in fiscal 2024",
210
+ url="https://reuters.com", published_date="2024-06-01",
211
+ evidence_type="news"),
212
+ ]
213
+ mock_nli.return_value = Tier2Result(
214
+ verdict="contradiction", confidence=0.72,
215
+ nli_results=[NliResult(label="contradiction", score=0.72,
216
+ snippet_source="Reuters",
217
+ snippet_text="India GDP grew at 6.5 percent")],
218
+ evidence_count=1,
219
+ )
220
+
221
+ result = asyncio.run(route_verification("GDP grew 7.5% in 2024"))
222
+
223
+ assert result.tier_used == "tier2"
224
+ assert result.tiers_run == ["tier1", "tier2"]
225
+ assert len(result.evidence) == 1
226
+ # Numeric verdict (misleading) overrides NLI because we have official data
227
+ assert result.verdict == "misleading"
228
+
229
+ @patch("verifier.verdict_router.tier3_llm_check", new_callable=AsyncMock)
230
+ @patch("verifier.verdict_router.run_nli", new_callable=AsyncMock)
231
+ @patch("verifier.verdict_router.fetch_evidence", new_callable=AsyncMock)
232
+ @patch("verifier.verdict_router.tier1_numeric_check", new_callable=AsyncMock)
233
+ @patch("verifier.verdict_router.extract_all")
234
+ def test_escalates_to_tier3_low_nli_confidence(
235
+ self, mock_extract, mock_t1, mock_evidence, mock_nli, mock_t3
236
+ ):
237
+ """
238
+ SCENARIO: Tier 2 confidence < 0.6 → escalates to Tier 3.
239
+
240
+ This happens when evidence snippets are mixed or irrelevant,
241
+ so the NLI model can't reach a confident conclusion.
242
+ """
243
+ mock_extract.return_value = _fake_extraction(confidence=0.9)
244
+ mock_t1.return_value = _fake_t1(official_value=6.49, percentage_error=15.56)
245
+ mock_evidence.return_value = []
246
+ mock_nli.return_value = Tier2Result(
247
+ verdict="neutral", confidence=0.35, # <0.6 threshold
248
+ nli_results=[], evidence_count=0,
249
+ )
250
+ mock_t3.return_value = Tier3Result(
251
+ verdict="misleading", confidence=0.82,
252
+ explanation="The claimed 7.5% exceeds the World Bank figure of 6.49%.",
253
+ sources_used=["World Bank"],
254
+ raw_response="...",
255
+ )
256
+
257
+ result = asyncio.run(route_verification("GDP grew 7.5% in 2024"))
258
+
259
+ assert result.tier_used == "tier3"
260
+ assert result.tiers_run == ["tier1", "tier2", "tier3"]
261
+ assert result.verdict == "misleading"
262
+ assert result.confidence == 0.82
263
+
264
+ @patch("verifier.verdict_router.tier3_llm_check", new_callable=AsyncMock)
265
+ @patch("verifier.verdict_router.run_nli", new_callable=AsyncMock)
266
+ @patch("verifier.verdict_router.fetch_evidence", new_callable=AsyncMock)
267
+ @patch("verifier.verdict_router.tier1_numeric_check", new_callable=AsyncMock)
268
+ @patch("verifier.verdict_router.extract_all")
269
+ def test_force_tier3_bypasses_early_returns(
270
+ self, mock_extract, mock_t1, mock_evidence, mock_nli, mock_t3
271
+ ):
272
+ """
273
+ SCENARIO: force_tier3=True (from /verify/deep endpoint).
274
+
275
+ Even though Tier 1 has a decisive result (0.27% error, clearly accurate),
276
+ we force execution through ALL tiers because the user explicitly
277
+ requested deep analysis.
278
+ """
279
+ mock_extract.return_value = _fake_extraction(confidence=0.9)
280
+ # Tier 1 is decisive (would normally short-circuit)
281
+ mock_t1.return_value = _fake_t1(official_value=7.48, percentage_error=0.27)
282
+ mock_evidence.return_value = []
283
+ mock_nli.return_value = Tier2Result(
284
+ verdict="entailment", confidence=0.85,
285
+ nli_results=[], evidence_count=0,
286
+ )
287
+ mock_t3.return_value = Tier3Result(
288
+ verdict="accurate", confidence=0.96,
289
+ explanation="All sources confirm the claim.",
290
+ sources_used=["World Bank"], raw_response="...",
291
+ )
292
+
293
+ result = asyncio.run(route_verification(
294
+ "GDP grew 7.5% in 2024", force_tier3=True
295
+ ))
296
+
297
+ assert result.tier_used == "tier3" # NOT tier1, even though it was decisive
298
+ assert result.tiers_run == ["tier1", "tier2", "tier3"] # ALL tiers ran
299
+
300
+ @patch("verifier.verdict_router.tier1_numeric_check", new_callable=AsyncMock)
301
+ @patch("verifier.verdict_router.extract_all")
302
+ def test_low_extraction_confidence_skips_fast_path(self, mock_extract, mock_t1):
303
+ """
304
+ SCENARIO: extraction confidence = 0.6 (below 0.8 threshold).
305
+
306
+ Even though Tier 1 error is clear (<5%), low extraction confidence
307
+ means we might have the WRONG metric. So we don't trust Tier 1
308
+ alone and escalate to Tier 2 for evidence-based backup.
309
+
310
+ This is controlled by TIER1_STRONG_THRESHOLD = 0.8 in verdict_router.py.
311
+ """
312
+ mock_extract.return_value = _fake_extraction(confidence=0.6) # Below 0.8
313
+ mock_t1.return_value = _fake_t1(official_value=7.48, percentage_error=0.27)
314
+
315
+ # Since this will try to go to Tier 2, we need those mocks too
316
+ with patch("verifier.verdict_router.fetch_evidence", new_callable=AsyncMock) as mock_ev, \
317
+ patch("verifier.verdict_router.run_nli", new_callable=AsyncMock) as mock_nli:
318
+ mock_ev.return_value = []
319
+ mock_nli.return_value = Tier2Result(
320
+ verdict="entailment", confidence=0.75,
321
+ nli_results=[], evidence_count=0,
322
+ )
323
+
324
+ result = asyncio.run(route_verification("GDP grew 7.5% in 2024"))
325
+
326
+ assert result.tier_used != "tier1" # Did NOT take the fast path
327
+ assert "tier2" in result.tiers_run
verifier/__init__.py CHANGED
@@ -13,9 +13,54 @@ from .tier1_numeric import (
13
  tier1_numeric_check,
14
  )
15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  __all__ = [
17
  "METRIC_TO_WORLD_BANK_INDICATOR",
18
  "WorldBankNumericCheck",
19
  "fetch_world_bank_series",
20
  "tier1_numeric_check",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  ]
 
 
 
13
  tier1_numeric_check,
14
  )
15
 
16
+ from .tier2_nli import (
17
+ NliResult,
18
+ Tier2Result,
19
+ run_nli,
20
+ # _run_nli_sync, # Not exported since it's an internal helper for the async wrapper. Leading _ mean it's a private function not intended for external use.
21
+ )
22
+
23
+ from .tier3_llm import (
24
+ EvidenceSummary,
25
+ Tier3Result,
26
+ tier3_llm_check,
27
+ )
28
+
29
+ from .evidence_fetcher import (
30
+ EvidenceSnippet,
31
+ fetch_evidence,
32
+ fetch_google_fact_checks,
33
+ fetch_news_snippets,
34
+ )
35
+
36
+ from .verdict_router import (
37
+ route_verification,
38
+ VerificationResult,
39
+ EvidenceItem,
40
+ )
41
+
42
  __all__ = [
43
  "METRIC_TO_WORLD_BANK_INDICATOR",
44
  "WorldBankNumericCheck",
45
  "fetch_world_bank_series",
46
  "tier1_numeric_check",
47
+ # Tier 2
48
+ "EvidenceSnippet",
49
+ "fetch_evidence",
50
+ "fetch_google_fact_checks",
51
+ "fetch_news_snippets",
52
+ "NliResult",
53
+ "Tier2Result",
54
+ "run_nli",
55
+ # Tier 3
56
+ "EvidenceSummary",
57
+ "Tier3Result",
58
+ "tier3_llm_check",
59
+ # Router
60
+ "VerificationResult",
61
+ "EvidenceItem",
62
+ "route_verification",
63
+
64
  ]
65
+
66
+
verifier/tier2_nli.py CHANGED
@@ -17,11 +17,14 @@ for higher accuracy when needed.
17
  from __future__ import annotations
18
 
19
  import asyncio
 
20
  from dataclasses import dataclass
21
  from functools import lru_cache
22
 
23
  from verifier.evidence_fetcher import EvidenceSnippet
24
 
 
 
25
 
26
  MODEL_NAME = "facebook/bart-large-mnli"
27
  # To upgrade quality later, change to:
@@ -55,13 +58,13 @@ def _load_pipeline():
55
  Downloads the model from HuggingFace on first run (~1.6GB).
56
  """
57
  from transformers import pipeline
58
- print(f"[Tier2 NLI] Loading model: {MODEL_NAME} (first call only)...")
59
  nli_pipeline = pipeline(
60
  "zero-shot-classification",
61
  model=MODEL_NAME,
62
  device=-1, # -1 = CPU; change to 0 for GPU
63
  )
64
- print("[Tier2 NLI] Model loaded and ready.")
65
  return nli_pipeline
66
 
67
 
 
17
  from __future__ import annotations
18
 
19
  import asyncio
20
+ import logging
21
  from dataclasses import dataclass
22
  from functools import lru_cache
23
 
24
  from verifier.evidence_fetcher import EvidenceSnippet
25
 
26
+ logger = logging.getLogger("bware.nlp.tier2")
27
+
28
 
29
  MODEL_NAME = "facebook/bart-large-mnli"
30
  # To upgrade quality later, change to:
 
58
  Downloads the model from HuggingFace on first run (~1.6GB).
59
  """
60
  from transformers import pipeline
61
+ logger.info("Loading NLI model: %s (first call only...)", MODEL_NAME)
62
  nli_pipeline = pipeline(
63
  "zero-shot-classification",
64
  model=MODEL_NAME,
65
  device=-1, # -1 = CPU; change to 0 for GPU
66
  )
67
+ logger.info("NLI model loaded and ready.")
68
  return nli_pipeline
69
 
70