feat: initial commit of Agentic ICD-10-CM Autonomous Code Matcher with 10-node LangGraph pipeline, deterministic guardrails, and professional documentation
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Test suite package for local medical coding system."""
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Pytest shared fixtures and test configuration."""
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from medical_coding.api.app import create_app
|
||||
from medical_coding.config.settings import Settings
|
||||
from medical_coding.dataset.validator import LocalICDCatalog
|
||||
from medical_coding.schemas.clinical import (
|
||||
ClassifiedDiagnosis,
|
||||
ContextualizedDiagnosis,
|
||||
EvidenceSnippet,
|
||||
ExtractedDiagnosis,
|
||||
)
|
||||
from medical_coding.schemas.enums import (
|
||||
Acuity,
|
||||
Certainty,
|
||||
DiagnosisRole,
|
||||
NegationStatus,
|
||||
Temporality,
|
||||
)
|
||||
from medical_coding.schemas.icd import ICDCandidate, ICDCodeRecord, RankedSelection
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_settings() -> Settings:
|
||||
"""Provide isolated in-memory test settings."""
|
||||
return Settings(
|
||||
environment="test",
|
||||
debug=True,
|
||||
offline_mode=True,
|
||||
log_level="DEBUG",
|
||||
max_batch_concurrency=5,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_client(test_settings: Settings) -> TestClient:
|
||||
"""FastAPI test client fixture."""
|
||||
app = create_app(settings=test_settings)
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_catalog() -> LocalICDCatalog:
|
||||
"""Provide an in-memory populated LocalICDCatalog for deterministic testing."""
|
||||
catalog = LocalICDCatalog()
|
||||
# Pre-populate sample verified codes
|
||||
records = [
|
||||
ICDCodeRecord(
|
||||
code="I50.21",
|
||||
unformatted_code="I5021",
|
||||
short_description="Acute systolic heart failure",
|
||||
long_description="Acute systolic (congestive) heart failure",
|
||||
is_valid_billable=True,
|
||||
category="I50",
|
||||
excludes1=["I50.22", "I50.23"],
|
||||
),
|
||||
ICDCodeRecord(
|
||||
code="I50.9",
|
||||
unformatted_code="I509",
|
||||
short_description="Heart failure, unspecified",
|
||||
long_description="Heart failure, unspecified",
|
||||
is_valid_billable=True,
|
||||
category="I50",
|
||||
),
|
||||
ICDCodeRecord(
|
||||
code="I50",
|
||||
unformatted_code="I50",
|
||||
short_description="Heart failure category header",
|
||||
long_description="Heart failure category header (non-billable)",
|
||||
is_valid_billable=False, # Category header, not billable
|
||||
category="I50",
|
||||
),
|
||||
ICDCodeRecord(
|
||||
code="E11.9",
|
||||
unformatted_code="E119",
|
||||
short_description="Type 2 diabetes mellitus without complications",
|
||||
long_description="Type 2 diabetes mellitus without complications",
|
||||
is_valid_billable=True,
|
||||
category="E11",
|
||||
),
|
||||
]
|
||||
for r in records:
|
||||
catalog._records_by_clean[r.unformatted_code] = r
|
||||
catalog._records_by_formatted[r.code] = r
|
||||
catalog._initialized = True
|
||||
return catalog
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_classified_primary() -> ClassifiedDiagnosis:
|
||||
"""Sample primary active condition fixture."""
|
||||
evidence = EvidenceSnippet(
|
||||
quote="Patient admitted for acute exacerbation of systolic heart failure.",
|
||||
source_section="Discharge Diagnosis",
|
||||
)
|
||||
extracted = ExtractedDiagnosis(
|
||||
diagnosis_id="diag-001",
|
||||
raw_term="acute systolic heart failure",
|
||||
evidence=evidence,
|
||||
extraction_confidence=0.98,
|
||||
)
|
||||
context = ContextualizedDiagnosis(
|
||||
diagnosis_id=extracted.diagnosis_id,
|
||||
raw_term=extracted.raw_term,
|
||||
evidence=evidence,
|
||||
extraction_confidence=0.98,
|
||||
negation=NegationStatus.AFFIRMATIVE,
|
||||
temporality=Temporality.CURRENT,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
acuity=Acuity.ACUTE,
|
||||
clinical_justification="Patient required immediate diuresis during stay.",
|
||||
)
|
||||
return ClassifiedDiagnosis(
|
||||
diagnosis_id=extracted.diagnosis_id,
|
||||
raw_term=extracted.raw_term,
|
||||
context=context,
|
||||
role=DiagnosisRole.PRIMARY,
|
||||
is_billable_candidate=True,
|
||||
classification_reason="Chief complaint occasioning hospital admission.",
|
||||
primary_justification="Chief clinical condition treated throughout hospitalization.",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_ranked_selection() -> RankedSelection:
|
||||
"""Sample ranked candidate selection fixture."""
|
||||
candidate = ICDCandidate(
|
||||
code="I50.21",
|
||||
description="Acute systolic (congestive) heart failure",
|
||||
retrieval_score=0.95,
|
||||
retrieval_method="hybrid",
|
||||
is_valid_billable=True,
|
||||
)
|
||||
return RankedSelection(
|
||||
diagnosis_id="diag-001",
|
||||
raw_term="acute systolic heart failure",
|
||||
selected_candidate=candidate,
|
||||
ranking_score=0.95,
|
||||
selection_justification="Matches clinical acuity and cardiac chamber specification.",
|
||||
candidate_pool=[candidate],
|
||||
decision="ACCEPTED",
|
||||
)
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Unit tests for FastAPI endpoints."""
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
def test_health_check_endpoint(test_client: TestClient) -> None:
|
||||
response = test_client.get("/health")
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["status"] == "healthy"
|
||||
assert data["offline_mode"] is True
|
||||
assert "llm_model" in data
|
||||
|
||||
|
||||
def test_code_text_endpoint(test_client: TestClient) -> None:
|
||||
payload = {
|
||||
"document_id": "test-doc-001",
|
||||
"text": "Patient was admitted with acute chest pain and diagnosed with acute systolic heart failure.",
|
||||
"metadata": {"unit": "ICU"},
|
||||
}
|
||||
response = test_client.post("/api/v1/code/text", json=payload)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["document_id"] == "test-doc-001"
|
||||
assert "status" in data
|
||||
assert "abstentions" in data
|
||||
|
||||
|
||||
def test_code_pdf_rejects_non_pdf(test_client: TestClient) -> None:
|
||||
response = test_client.post(
|
||||
"/api/v1/code/pdf",
|
||||
files={"file": ("notes.txt", b"plain text data", "text/plain")},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert "PDF document" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_code_pdf_success_endpoint(test_client: TestClient) -> None:
|
||||
import io
|
||||
|
||||
import pymupdf
|
||||
|
||||
doc = pymupdf.open()
|
||||
page = doc.new_page()
|
||||
page.insert_text(
|
||||
(50, 72),
|
||||
"DISCHARGE SUMMARY\nPatient admitted with acute systolic heart failure.",
|
||||
fontsize=10,
|
||||
)
|
||||
pdf_bytes = doc.write()
|
||||
doc.close()
|
||||
|
||||
response = test_client.post(
|
||||
"/api/v1/code/pdf",
|
||||
files={"file": ("discharge_summary.pdf", io.BytesIO(pdf_bytes), "application/pdf")},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "document_id" in data
|
||||
assert data["status"] in ("SUCCESS", "PARTIAL_SUCCESS")
|
||||
assert data["primary_diagnosis"] is not None
|
||||
assert data["primary_diagnosis"]["code"] == "I50.21"
|
||||
@@ -0,0 +1,645 @@
|
||||
"""Comprehensive unit and integration tests for the ICD Candidate Ranking Component."""
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from medical_coding.agents.ranker import CandidateRankingAgent
|
||||
from medical_coding.dataset.validator import LocalICDCatalog
|
||||
from medical_coding.models.base import BaseLocalLLM
|
||||
from medical_coding.schemas.clinical import (
|
||||
ClassifiedDiagnosis,
|
||||
ConditionClassification,
|
||||
ContextualizedDiagnosis,
|
||||
EvidenceSnippet,
|
||||
)
|
||||
from medical_coding.schemas.enums import (
|
||||
Acuity,
|
||||
Certainty,
|
||||
DiagnosisRole,
|
||||
Temporality,
|
||||
)
|
||||
from medical_coding.schemas.icd import ICDCandidate, ICDCodeRecord
|
||||
from medical_coding.validation.deterministic import (
|
||||
CandidateRankingDeterministicValidator,
|
||||
)
|
||||
|
||||
|
||||
class MockLLM(BaseLocalLLM):
|
||||
"""Configurable mock LLM for testing candidate ranking agent behaviors."""
|
||||
|
||||
def __init__(self, response_text: str = "") -> None:
|
||||
self.response_text = response_text
|
||||
self.call_count = 0
|
||||
self.last_prompt = ""
|
||||
|
||||
def generate(
|
||||
self,
|
||||
prompt: str,
|
||||
max_tokens: int | None = None,
|
||||
temperature: float | None = None,
|
||||
stop_sequences: list[str] | None = None,
|
||||
) -> str:
|
||||
self.call_count += 1
|
||||
self.last_prompt = prompt
|
||||
return self.response_text
|
||||
|
||||
def get_model_info(self) -> dict[str, Any]:
|
||||
return {"model_name": "mock-ranking-llm", "offline_only": True}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ranking_test_catalog() -> LocalICDCatalog:
|
||||
"""Authoritative local catalog containing verified test codes."""
|
||||
catalog = LocalICDCatalog()
|
||||
records = [
|
||||
ICDCodeRecord(
|
||||
code="I50.21",
|
||||
unformatted_code="I5021",
|
||||
description="Acute systolic heart failure",
|
||||
is_valid_billable=True,
|
||||
category="I50",
|
||||
synonyms=["acute systolic HF", "HFrEF acute"],
|
||||
),
|
||||
ICDCodeRecord(
|
||||
code="I50.22",
|
||||
unformatted_code="I5022",
|
||||
description="Chronic systolic heart failure",
|
||||
is_valid_billable=True,
|
||||
category="I50",
|
||||
synonyms=["chronic systolic HF", "compensated systolic heart failure"],
|
||||
),
|
||||
ICDCodeRecord(
|
||||
code="I50.31",
|
||||
unformatted_code="I5031",
|
||||
description="Acute diastolic heart failure",
|
||||
is_valid_billable=True,
|
||||
category="I50",
|
||||
),
|
||||
ICDCodeRecord(
|
||||
code="I50.9",
|
||||
unformatted_code="I509",
|
||||
description="Heart failure, unspecified",
|
||||
is_valid_billable=True,
|
||||
category="I50",
|
||||
synonyms=["HF", "CHF", "heart failure"],
|
||||
),
|
||||
ICDCodeRecord(
|
||||
code="I10",
|
||||
unformatted_code="I10",
|
||||
description="Essential primary hypertension",
|
||||
is_valid_billable=True,
|
||||
category="I10",
|
||||
synonyms=["HTN", "high blood pressure"],
|
||||
),
|
||||
ICDCodeRecord(
|
||||
code="E11.9",
|
||||
unformatted_code="E119",
|
||||
description="Type 2 diabetes mellitus without complications",
|
||||
is_valid_billable=True,
|
||||
category="E11",
|
||||
synonyms=["T2DM", "type 2 diabetes"],
|
||||
),
|
||||
ICDCodeRecord(
|
||||
code="E11.21",
|
||||
unformatted_code="E1121",
|
||||
description="Type 2 diabetes mellitus with diabetic nephropathy",
|
||||
is_valid_billable=True,
|
||||
category="E11",
|
||||
synonyms=["T2DM nephropathy", "diabetic kidney disease"],
|
||||
),
|
||||
]
|
||||
for r in records:
|
||||
catalog.add_record(r)
|
||||
catalog._initialized = True
|
||||
return catalog
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def heart_failure_candidates() -> list[ICDCandidate]:
|
||||
"""Sample candidate pool retrieved from local dataset for heart failure."""
|
||||
return [
|
||||
ICDCandidate(
|
||||
code="I50.21",
|
||||
description="Acute systolic heart failure",
|
||||
retrieval_score=0.91,
|
||||
retrieval_method="hybrid",
|
||||
is_valid_billable=True,
|
||||
category="I50",
|
||||
),
|
||||
ICDCandidate(
|
||||
code="I50.22",
|
||||
description="Chronic systolic heart failure",
|
||||
retrieval_score=0.78,
|
||||
retrieval_method="hybrid",
|
||||
is_valid_billable=True,
|
||||
category="I50",
|
||||
),
|
||||
ICDCandidate(
|
||||
code="I50.9",
|
||||
description="Heart failure, unspecified",
|
||||
retrieval_score=0.82,
|
||||
retrieval_method="hybrid",
|
||||
is_valid_billable=True,
|
||||
category="I50",
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 1. CLEAR CANDIDATE TEST
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_clear_candidate_selection(
|
||||
ranking_test_catalog: LocalICDCatalog,
|
||||
heart_failure_candidates: list[ICDCandidate],
|
||||
) -> None:
|
||||
"""Clear evidence with specific diagnostic terms must select the matching candidate."""
|
||||
evidence = "Patient admitted for acute exacerbation of systolic congestive heart failure. Echo showed EF 20%."
|
||||
condition = ClassifiedDiagnosis(
|
||||
diagnosis_id="diag-hf-clear",
|
||||
raw_term="acute systolic heart failure",
|
||||
context=ContextualizedDiagnosis(
|
||||
diagnosis_id="diag-hf-clear",
|
||||
raw_term="acute systolic heart failure",
|
||||
evidence=EvidenceSnippet(quote=evidence, source_section="Discharge Diagnosis"),
|
||||
extraction_confidence=1.0,
|
||||
acuity=Acuity.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
clinical_justification="Acute decompensated systolic heart failure actively treated.",
|
||||
),
|
||||
role=DiagnosisRole.PRIMARY,
|
||||
is_billable_candidate=True,
|
||||
classification_reason="Reason for admission requiring IV diuretics.",
|
||||
)
|
||||
|
||||
validator = CandidateRankingDeterministicValidator(catalog=ranking_test_catalog)
|
||||
# LLM confirms the clear candidate
|
||||
llm_response = json.dumps(
|
||||
{
|
||||
"selected_code": "I50.21",
|
||||
"selected_description": "Acute systolic heart failure",
|
||||
"ranking_reason": "Documentation explicitly states acute systolic heart failure with EF 20%.",
|
||||
"supporting_evidence": evidence,
|
||||
"confidence": 0.95,
|
||||
"decision": "ACCEPTED",
|
||||
}
|
||||
)
|
||||
agent = CandidateRankingAgent(llm=MockLLM(llm_response), validator=validator)
|
||||
|
||||
selection = agent.rank_candidates(condition, heart_failure_candidates)
|
||||
|
||||
assert selection.selected_code == "I50.21"
|
||||
assert selection.selected_description == "Acute systolic heart failure"
|
||||
assert selection.decision == "ACCEPTED"
|
||||
assert selection.confidence >= 0.85
|
||||
assert selection.abstention_reason is None
|
||||
assert selection.selected_candidate is not None
|
||||
assert selection.selected_candidate.code == "I50.21"
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 2. AMBIGUOUS CANDIDATES TEST
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_ambiguous_candidates_evaluates_best_supported_level(
|
||||
ranking_test_catalog: LocalICDCatalog,
|
||||
heart_failure_candidates: list[ICDCandidate],
|
||||
) -> None:
|
||||
"""When documentation mentions general condition, agent must differentiate and pick best supported level."""
|
||||
evidence = "Past medical history significant for congestive heart failure and hypertension, clinically compensated."
|
||||
condition = ClassifiedDiagnosis(
|
||||
diagnosis_id="diag-hf-ambig",
|
||||
raw_term="congestive heart failure",
|
||||
context=ContextualizedDiagnosis(
|
||||
diagnosis_id="diag-hf-ambig",
|
||||
raw_term="congestive heart failure",
|
||||
evidence=EvidenceSnippet(quote=evidence, source_section="Past Medical History"),
|
||||
extraction_confidence=0.90,
|
||||
acuity=Acuity.CHRONIC,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
clinical_justification="Monitored on home regimen.",
|
||||
),
|
||||
role=DiagnosisRole.SECONDARY,
|
||||
is_billable_candidate=True,
|
||||
classification_reason="Monitored secondary condition.",
|
||||
)
|
||||
|
||||
validator = CandidateRankingDeterministicValidator(catalog=ranking_test_catalog)
|
||||
# Agent evaluates candidates deterministically or via LLM selecting unspecified
|
||||
agent = CandidateRankingAgent(llm=None, validator=validator)
|
||||
|
||||
selection = agent.rank_candidates(condition, heart_failure_candidates)
|
||||
|
||||
# Neither systolic nor acute was documented in the evidence; must NOT select I50.21 (acute systolic)
|
||||
assert selection.selected_code != "I50.21"
|
||||
# Should select either unspecified (I50.9) or chronic systolic if supported, or unspecified I50.9
|
||||
assert selection.selected_code in ["I50.9", "I50.22"]
|
||||
assert selection.decision == "ACCEPTED"
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 3. UNSUPPORTED SPECIFICITY TEST
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_unsupported_specificity_realigned_to_unspecified(
|
||||
ranking_test_catalog: LocalICDCatalog,
|
||||
heart_failure_candidates: list[ICDCandidate],
|
||||
) -> None:
|
||||
"""If documentation only supports general condition, LLM cannot force acute systolic code."""
|
||||
evidence = "Discharge Diagnosis: Heart failure. Patient stabilized on furosemide."
|
||||
condition = ConditionClassification(
|
||||
diagnosis_id="diag-hf-general",
|
||||
diagnosis="Heart failure",
|
||||
role=DiagnosisRole.PRIMARY,
|
||||
is_billable_candidate=True,
|
||||
classification_reason="Primary reason for admission.",
|
||||
evidence_quote=evidence,
|
||||
)
|
||||
|
||||
validator = CandidateRankingDeterministicValidator(catalog=ranking_test_catalog)
|
||||
# Model erroneously tries to pick highly specific code I50.21 despite lack of systolic proof
|
||||
hallucinated_specificity = json.dumps(
|
||||
{
|
||||
"selected_code": "I50.21",
|
||||
"selected_description": "Acute systolic heart failure",
|
||||
"ranking_reason": "Heart failure mention sounds severe so picking acute systolic.",
|
||||
"supporting_evidence": evidence,
|
||||
"confidence": 0.88,
|
||||
"decision": "ACCEPTED",
|
||||
}
|
||||
)
|
||||
agent = CandidateRankingAgent(llm=MockLLM(hallucinated_specificity), validator=validator)
|
||||
|
||||
selection = agent.rank_candidates(condition, heart_failure_candidates)
|
||||
|
||||
# Deterministic validation catches unsupported systolic specificity and realigns to I50.9 (unspecified)!
|
||||
assert selection.selected_code == "I50.9"
|
||||
assert "systolic specificity" in selection.ranking_reason.lower()
|
||||
assert selection.decision == "ACCEPTED"
|
||||
|
||||
|
||||
def test_unsupported_specificity_abstains_when_no_general_code_present(
|
||||
ranking_test_catalog: LocalICDCatalog,
|
||||
) -> None:
|
||||
"""If only specific candidates exist and documentation is general, agent must abstain."""
|
||||
evidence = "Diagnosis: Heart failure NOS."
|
||||
condition = ConditionClassification(
|
||||
diagnosis_id="diag-hf-only-specific",
|
||||
diagnosis="Heart failure",
|
||||
role=DiagnosisRole.SECONDARY,
|
||||
is_billable_candidate=True,
|
||||
classification_reason="Monitored condition.",
|
||||
evidence_quote=evidence,
|
||||
)
|
||||
# Candidate pool contains ONLY specific codes (no I50.9)
|
||||
specific_only_candidates = [
|
||||
ICDCandidate(
|
||||
code="I50.21",
|
||||
description="Acute systolic heart failure",
|
||||
retrieval_score=0.75,
|
||||
retrieval_method="faiss",
|
||||
is_valid_billable=True,
|
||||
),
|
||||
ICDCandidate(
|
||||
code="I50.31",
|
||||
description="Acute diastolic heart failure",
|
||||
retrieval_score=0.70,
|
||||
retrieval_method="faiss",
|
||||
is_valid_billable=True,
|
||||
),
|
||||
]
|
||||
|
||||
validator = CandidateRankingDeterministicValidator(catalog=ranking_test_catalog)
|
||||
llm_resp = json.dumps(
|
||||
{
|
||||
"selected_code": "I50.21",
|
||||
"selected_description": "Acute systolic heart failure",
|
||||
"ranking_reason": "Forcing systolic.",
|
||||
"supporting_evidence": evidence,
|
||||
"confidence": 0.75,
|
||||
"decision": "ACCEPTED",
|
||||
}
|
||||
)
|
||||
agent = CandidateRankingAgent(llm=MockLLM(llm_resp), validator=validator)
|
||||
|
||||
selection = agent.rank_candidates(condition, specific_only_candidates)
|
||||
|
||||
# Must abstain because evidence does NOT support systolic or diastolic, and no general code exists in pool
|
||||
assert selection.selected_code is None
|
||||
assert selection.decision == "ABSTAINED"
|
||||
assert selection.abstention_reason == "UNSUPPORTED_SPECIFICITY"
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 4. CANDIDATE NOT SELECTED TEST
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_candidate_not_selected_unrelated_condition(
|
||||
ranking_test_catalog: LocalICDCatalog,
|
||||
heart_failure_candidates: list[ICDCandidate],
|
||||
) -> None:
|
||||
"""When candidates have zero clinical support in evidence, no candidate should be selected."""
|
||||
evidence = "Patient underwent skin biopsy for suspected dermatological rash on forearm."
|
||||
condition = ConditionClassification(
|
||||
diagnosis_id="diag-rash",
|
||||
diagnosis="Eczematous dermatitis",
|
||||
role=DiagnosisRole.SECONDARY,
|
||||
is_billable_candidate=True,
|
||||
classification_reason="Skin examination finding.",
|
||||
evidence_quote=evidence,
|
||||
)
|
||||
|
||||
validator = CandidateRankingDeterministicValidator(catalog=ranking_test_catalog)
|
||||
# LLM correctly abstains
|
||||
llm_resp = json.dumps(
|
||||
{
|
||||
"selected_code": None,
|
||||
"selected_description": None,
|
||||
"ranking_reason": "None of the heart failure candidates match the dermatological evidence.",
|
||||
"supporting_evidence": evidence,
|
||||
"confidence": 0.0,
|
||||
"decision": "ABSTAINED",
|
||||
"abstention_reason": "NO_MATCHING_CANDIDATE",
|
||||
}
|
||||
)
|
||||
agent = CandidateRankingAgent(llm=MockLLM(llm_resp), validator=validator)
|
||||
|
||||
selection = agent.rank_candidates(condition, heart_failure_candidates)
|
||||
|
||||
assert selection.selected_code is None
|
||||
assert selection.decision == "ABSTAINED"
|
||||
assert selection.abstention_reason in ["NO_MATCHING_CANDIDATE", "CONFIDENCE_BELOW_THRESHOLD"]
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 5. HARD CONSTRAINT: INVALID LLM CODE REJECTION
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_invalid_llm_code_deterministic_rejection(
|
||||
ranking_test_catalog: LocalICDCatalog,
|
||||
heart_failure_candidates: list[ICDCandidate],
|
||||
) -> None:
|
||||
"""CRITICAL HARD CONSTRAINT: If LLM hallucinates a code not in candidate list, it MUST be rejected."""
|
||||
evidence = "Patient has severe acute systolic heart failure."
|
||||
condition = ConditionClassification(
|
||||
diagnosis_id="diag-hf",
|
||||
diagnosis="acute systolic heart failure",
|
||||
role=DiagnosisRole.PRIMARY,
|
||||
is_billable_candidate=True,
|
||||
classification_reason="Primary admission reason.",
|
||||
evidence_quote=evidence,
|
||||
)
|
||||
|
||||
validator = CandidateRankingDeterministicValidator(catalog=ranking_test_catalog)
|
||||
# LLM hallucinates a code 'I42.0' (Dilated cardiomyopathy) which is NOT in candidates list [I50.21, I50.22, I50.9]!
|
||||
hallucinated_code_response = json.dumps(
|
||||
{
|
||||
"selected_code": "I42.0", # NOT in candidates!
|
||||
"selected_description": "Dilated cardiomyopathy",
|
||||
"ranking_reason": "I think patient also has dilated cardiomyopathy.",
|
||||
"supporting_evidence": evidence,
|
||||
"confidence": 0.99,
|
||||
"decision": "ACCEPTED",
|
||||
}
|
||||
)
|
||||
agent = CandidateRankingAgent(
|
||||
llm=MockLLM(hallucinated_code_response),
|
||||
validator=validator,
|
||||
allow_rerun=False,
|
||||
)
|
||||
|
||||
selection = agent.rank_candidates(condition, heart_failure_candidates)
|
||||
|
||||
# MUST REJECT! The code does NOT exist in candidate list
|
||||
assert selection.selected_code is None
|
||||
assert selection.decision == "REJECTED_MISMATCH"
|
||||
assert selection.abstention_reason == "INVALID_LLM_CODE_NOT_IN_CANDIDATE_POOL"
|
||||
assert selection.confidence == 0.0
|
||||
assert "Deterministic rejection" in selection.ranking_reason
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 6. INSUFFICIENT EVIDENCE TEST
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_insufficient_evidence_triggers_clean_abstention(
|
||||
ranking_test_catalog: LocalICDCatalog,
|
||||
heart_failure_candidates: list[ICDCandidate],
|
||||
) -> None:
|
||||
"""Missing or empty evidence quote must immediately abstain without assigning a code."""
|
||||
condition = ConditionClassification(
|
||||
diagnosis_id="diag-no-ev",
|
||||
diagnosis="Essential hypertension",
|
||||
role=DiagnosisRole.SECONDARY,
|
||||
is_billable_candidate=True,
|
||||
classification_reason="Listed without note.",
|
||||
evidence_quote="", # Empty evidence!
|
||||
)
|
||||
|
||||
validator = CandidateRankingDeterministicValidator(catalog=ranking_test_catalog)
|
||||
mock_llm = MockLLM()
|
||||
agent = CandidateRankingAgent(llm=mock_llm, validator=validator)
|
||||
|
||||
selection = agent.rank_candidates(condition, heart_failure_candidates)
|
||||
|
||||
assert selection.selected_code is None
|
||||
assert selection.decision == "ABSTAINED"
|
||||
assert selection.abstention_reason == "INSUFFICIENT_EVIDENCE"
|
||||
# Guaranteed: No LLM calls made when evidence is missing!
|
||||
assert mock_llm.call_count == 0
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 7. NO CANDIDATES TEST
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_no_candidates_pool_triggers_immediate_abstention(
|
||||
ranking_test_catalog: LocalICDCatalog,
|
||||
) -> None:
|
||||
"""When candidate pool is empty, agent must cleanly abstain with zero LLM inference."""
|
||||
condition = ConditionClassification(
|
||||
diagnosis_id="diag-empty-pool",
|
||||
diagnosis="Rare metabolic disease",
|
||||
role=DiagnosisRole.SECONDARY,
|
||||
is_billable_candidate=True,
|
||||
classification_reason="Evaluated.",
|
||||
evidence_quote="Metabolic workup documented.",
|
||||
)
|
||||
|
||||
validator = CandidateRankingDeterministicValidator(catalog=ranking_test_catalog)
|
||||
mock_llm = MockLLM()
|
||||
agent = CandidateRankingAgent(llm=mock_llm, validator=validator)
|
||||
|
||||
selection = agent.rank_candidates(condition, candidates=[]) # Empty candidates list!
|
||||
|
||||
assert selection.selected_code is None
|
||||
assert selection.decision == "ABSTAINED"
|
||||
assert selection.abstention_reason == "NO_CANDIDATES"
|
||||
assert selection.candidate_pool == []
|
||||
# Zero LLM inference calls
|
||||
assert mock_llm.call_count == 0
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 8. CANDIDATE-RANKING EVALUATION FIXTURE
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def candidate_ranking_evaluation_fixture(ranking_test_catalog: LocalICDCatalog):
|
||||
"""Reusable evaluation fixture executing a benchmark suite across clinical scenarios."""
|
||||
|
||||
class CandidateRankingEvaluationHarness:
|
||||
def __init__(self) -> None:
|
||||
self.catalog = ranking_test_catalog
|
||||
self.validator = CandidateRankingDeterministicValidator(catalog=self.catalog)
|
||||
self.agent = CandidateRankingAgent(llm=None, validator=self.validator)
|
||||
|
||||
def run_benchmark(self) -> dict[str, Any]:
|
||||
test_cases = [
|
||||
{
|
||||
"name": "Exact Acute Systolic HF",
|
||||
"term": "Acute systolic heart failure",
|
||||
"evidence": "Admitted with acute systolic congestive heart failure exacerbation.",
|
||||
"candidates": [
|
||||
ICDCandidate(
|
||||
code="I50.21",
|
||||
description="Acute systolic heart failure",
|
||||
retrieval_score=0.95,
|
||||
retrieval_method="hybrid",
|
||||
is_valid_billable=True,
|
||||
),
|
||||
ICDCandidate(
|
||||
code="I50.9",
|
||||
description="Heart failure, unspecified",
|
||||
retrieval_score=0.80,
|
||||
retrieval_method="hybrid",
|
||||
is_valid_billable=True,
|
||||
),
|
||||
],
|
||||
"expected_code": "I50.21",
|
||||
"expected_decision": "ACCEPTED",
|
||||
},
|
||||
{
|
||||
"name": "General HF without Subtype",
|
||||
"term": "Congestive heart failure",
|
||||
"evidence": "Patient with congestive heart failure on maintenance oral diuretic.",
|
||||
"candidates": [
|
||||
ICDCandidate(
|
||||
code="I50.21",
|
||||
description="Acute systolic heart failure",
|
||||
retrieval_score=0.88,
|
||||
retrieval_method="hybrid",
|
||||
is_valid_billable=True,
|
||||
),
|
||||
ICDCandidate(
|
||||
code="I50.9",
|
||||
description="Heart failure, unspecified",
|
||||
retrieval_score=0.84,
|
||||
retrieval_method="hybrid",
|
||||
is_valid_billable=True,
|
||||
),
|
||||
],
|
||||
"expected_code": "I50.9",
|
||||
"expected_decision": "ACCEPTED",
|
||||
},
|
||||
{
|
||||
"name": "Uncomplicated Type 2 Diabetes",
|
||||
"term": "Type 2 diabetes mellitus",
|
||||
"evidence": "Blood glucose was monitored; patient has type 2 diabetes on metformin.",
|
||||
"candidates": [
|
||||
ICDCandidate(
|
||||
code="E11.9",
|
||||
description="Type 2 diabetes mellitus without complications",
|
||||
retrieval_score=0.90,
|
||||
retrieval_method="hybrid",
|
||||
is_valid_billable=True,
|
||||
),
|
||||
ICDCandidate(
|
||||
code="E11.21",
|
||||
description="Type 2 diabetes mellitus with diabetic nephropathy",
|
||||
retrieval_score=0.85,
|
||||
retrieval_method="hybrid",
|
||||
is_valid_billable=True,
|
||||
),
|
||||
],
|
||||
"expected_code": "E11.9",
|
||||
"expected_decision": "ACCEPTED",
|
||||
},
|
||||
{
|
||||
"name": "Alien Disease No Match",
|
||||
"term": "Extraterrestrial pulmonary syndrome",
|
||||
"evidence": "Patient reports alien infection.",
|
||||
"candidates": [
|
||||
ICDCandidate(
|
||||
code="I50.9",
|
||||
description="Heart failure, unspecified",
|
||||
retrieval_score=0.20,
|
||||
retrieval_method="hybrid",
|
||||
is_valid_billable=True,
|
||||
),
|
||||
],
|
||||
"expected_code": None,
|
||||
"expected_decision": "ABSTAINED",
|
||||
},
|
||||
]
|
||||
|
||||
results = []
|
||||
for case in test_cases:
|
||||
cond = ConditionClassification(
|
||||
diagnosis_id=f"bench-{case['name']}",
|
||||
diagnosis=case["term"],
|
||||
role=DiagnosisRole.PRIMARY,
|
||||
is_billable_candidate=True,
|
||||
classification_reason="Benchmark evaluation",
|
||||
evidence_quote=case["evidence"],
|
||||
)
|
||||
sel = self.agent.rank_candidates(cond, case["candidates"])
|
||||
passed = (sel.selected_code == case["expected_code"]) and (
|
||||
sel.decision == case["expected_decision"]
|
||||
)
|
||||
results.append(
|
||||
{
|
||||
"case_name": case["name"],
|
||||
"passed": passed,
|
||||
"selected_code": sel.selected_code,
|
||||
"decision": sel.decision,
|
||||
"confidence": sel.confidence,
|
||||
"reason": sel.ranking_reason,
|
||||
}
|
||||
)
|
||||
|
||||
total = len(results)
|
||||
passed_count = sum(1 for r in results if r["passed"])
|
||||
return {
|
||||
"total_cases": total,
|
||||
"passed_count": passed_count,
|
||||
"accuracy": passed_count / total if total > 0 else 0.0,
|
||||
"results": results,
|
||||
}
|
||||
|
||||
return CandidateRankingEvaluationHarness()
|
||||
|
||||
|
||||
def test_candidate_ranking_evaluation_fixture_execution(
|
||||
candidate_ranking_evaluation_fixture: Any,
|
||||
) -> None:
|
||||
"""Execute the candidate-ranking evaluation fixture and verify benchmark metrics."""
|
||||
metrics = candidate_ranking_evaluation_fixture.run_benchmark()
|
||||
|
||||
assert metrics["total_cases"] == 4
|
||||
assert metrics["passed_count"] == 4
|
||||
assert metrics["accuracy"] == 1.0
|
||||
for r in metrics["results"]:
|
||||
assert r["passed"] is True
|
||||
@@ -0,0 +1,515 @@
|
||||
"""Unit tests for the Primary / Secondary Classification component and deterministic validator."""
|
||||
|
||||
import json
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from medical_coding.agents.classifier import PrimarySecondaryClassifier
|
||||
from medical_coding.schemas.clinical import (
|
||||
ConditionClassification,
|
||||
ContextAssessment,
|
||||
EncounterClassificationResult,
|
||||
)
|
||||
from medical_coding.schemas.enums import (
|
||||
AbstentionReason,
|
||||
Certainty,
|
||||
ConditionStatus,
|
||||
DiagnosisRole,
|
||||
NegationStatus,
|
||||
PipelineStage,
|
||||
Temporality,
|
||||
)
|
||||
from medical_coding.schemas.state import PipelineGraphState
|
||||
from medical_coding.validation.deterministic import (
|
||||
MultiplePrimaryDiagnosesError,
|
||||
PrimarySecondaryClassificationValidator,
|
||||
)
|
||||
|
||||
# ============================================================================
|
||||
# Test Cases 1 - 6: Required Clinical Scenarios
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def test_scenario_1_clear_single_primary() -> None:
|
||||
"""Requirement 1: Clear single primary diagnosis.
|
||||
|
||||
Patient admitted for acute appendicitis, underwent laparoscopic appendectomy.
|
||||
"""
|
||||
mock_llm = MagicMock()
|
||||
classifier = PrimarySecondaryClassifier(mock_llm)
|
||||
|
||||
assessment = ContextAssessment(
|
||||
condition_id="app-01",
|
||||
diagnosis="Acute appendicitis",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence="Patient presented with acute right lower quadrant pain, admitted for acute appendicitis. Laparoscopic appendectomy performed.",
|
||||
reason="Acute condition occasioning admission treated with operative intervention.",
|
||||
treated_or_managed=True,
|
||||
monitored=True,
|
||||
affected_clinical_management=True,
|
||||
influenced_treatment=True,
|
||||
treatment_evidence="Laparoscopic appendectomy performed",
|
||||
)
|
||||
|
||||
result, abstentions = classifier.classify_conditions([assessment])
|
||||
|
||||
assert result.has_unique_primary is True
|
||||
assert result.primary_diagnosis is not None
|
||||
assert result.primary_diagnosis.diagnosis == "Acute appendicitis"
|
||||
assert result.primary_diagnosis.role == DiagnosisRole.PRIMARY
|
||||
assert result.primary_diagnosis.is_billable_candidate is True
|
||||
assert len(result.secondary_diagnoses) == 0
|
||||
assert len(result.excluded_conditions) == 0
|
||||
assert result.is_ambiguous_primary is False
|
||||
assert len(abstentions) == 0
|
||||
|
||||
|
||||
def test_scenario_2_multiple_diagnoses_not_first_mentioned() -> None:
|
||||
"""Requirement 2: Multiple diagnoses, ensuring the first-mentioned condition is NOT automatically primary.
|
||||
|
||||
Document mentions Essential hypertension first under PMH, but patient was admitted for
|
||||
Acute NSTEMI with coronary catheterization and stent placement, and also had Type 2 diabetes managed.
|
||||
"""
|
||||
mock_llm = MagicMock()
|
||||
classifier = PrimarySecondaryClassifier(mock_llm)
|
||||
|
||||
htn = ContextAssessment(
|
||||
condition_id="htn-01",
|
||||
diagnosis="Essential hypertension",
|
||||
current_relevance=False,
|
||||
coding_candidate=False,
|
||||
status=ConditionStatus.HISTORICAL,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.HISTORICAL,
|
||||
evidence="PAST MEDICAL HISTORY: Essential hypertension for 10 years.",
|
||||
reason="Historical PMH condition without active inpatient care.",
|
||||
)
|
||||
|
||||
nstemi = ContextAssessment(
|
||||
condition_id="nstemi-01",
|
||||
diagnosis="Acute non-ST elevation myocardial infarction",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence="CHIEF COMPLAINT: Admitted for acute NSTEMI with peak troponin 5.2 ng/mL. Emergent coronary catheterization with drug-eluting stent placed.",
|
||||
reason="Acute cardiac infarction occasioning admission and catheterization with stenting.",
|
||||
treated_or_managed=True,
|
||||
monitored=True,
|
||||
affected_clinical_management=True,
|
||||
influenced_treatment=True,
|
||||
treatment_evidence="Coronary catheterization with drug-eluting stent placed",
|
||||
)
|
||||
|
||||
dm = ContextAssessment(
|
||||
condition_id="dm-01",
|
||||
diagnosis="Type 2 diabetes mellitus",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.CHRONIC,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence="Type 2 diabetes monitored with blood glucose checks, insulin sliding scale adjusted.",
|
||||
reason="Pre-existing condition actively monitored and managed during stay.",
|
||||
treated_or_managed=True,
|
||||
monitored=True,
|
||||
treatment_evidence="insulin sliding scale adjusted",
|
||||
)
|
||||
|
||||
# Note: HTN is listed first in document order
|
||||
result, _ = classifier.classify_conditions([htn, nstemi, dm])
|
||||
|
||||
assert result.has_unique_primary is True
|
||||
assert result.primary_diagnosis is not None
|
||||
# Must NOT select HTN (the first mentioned)!
|
||||
assert result.primary_diagnosis.diagnosis == "Acute non-ST elevation myocardial infarction"
|
||||
assert result.primary_diagnosis.role == DiagnosisRole.PRIMARY
|
||||
|
||||
# DM is secondary
|
||||
sec_names = [s.diagnosis for s in result.secondary_diagnoses]
|
||||
assert "Type 2 diabetes mellitus" in sec_names
|
||||
|
||||
# HTN is excluded
|
||||
excl_names = [e.diagnosis for e in result.excluded_conditions]
|
||||
assert "Essential hypertension" in excl_names
|
||||
|
||||
|
||||
def test_scenario_3_historical_condition_excluded() -> None:
|
||||
"""Requirement 3: Historical-only conditions without current relevance must be excluded from billing."""
|
||||
mock_llm = MagicMock()
|
||||
classifier = PrimarySecondaryClassifier(mock_llm)
|
||||
|
||||
gerd = ContextAssessment(
|
||||
condition_id="gerd-01",
|
||||
diagnosis="Gastroesophageal reflux disease",
|
||||
current_relevance=False,
|
||||
coding_candidate=False,
|
||||
status=ConditionStatus.HISTORICAL,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.HISTORICAL,
|
||||
evidence="Past history of GERD diagnosed 8 years ago, no active symptoms.",
|
||||
reason="Historical condition without active evaluation or therapy.",
|
||||
)
|
||||
|
||||
result, abstentions = classifier.classify_conditions([gerd])
|
||||
|
||||
assert result.primary_diagnosis is None
|
||||
assert len(result.secondary_diagnoses) == 0
|
||||
assert len(result.excluded_conditions) == 1
|
||||
assert result.excluded_conditions[0].diagnosis == "Gastroesophageal reflux disease"
|
||||
assert result.excluded_conditions[0].role == DiagnosisRole.EXCLUDED
|
||||
assert result.excluded_conditions[0].is_billable_candidate is False
|
||||
|
||||
|
||||
def test_scenario_4_two_plausible_primary_conditions_abstains() -> None:
|
||||
"""Requirement 4: Two plausible primary conditions where documentation does not distinguish which occasioned admission.
|
||||
|
||||
Patient presented with simultaneous Acute myocardial infarction AND Acute ischemic stroke,
|
||||
both listed as reasons for admission, both receiving emergent acute interventions.
|
||||
The agent must NOT arbitrarily choose one, and must return an ambiguity/abstention state.
|
||||
"""
|
||||
mock_llm = MagicMock()
|
||||
classifier = PrimarySecondaryClassifier(mock_llm)
|
||||
|
||||
ami = ContextAssessment(
|
||||
condition_id="ami-01",
|
||||
diagnosis="Acute myocardial infarction",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence="Reason for admission: Acute myocardial infarction, emergent catheterization and stent placed.",
|
||||
reason="Acute condition occasioning emergent admission.",
|
||||
treated_or_managed=True,
|
||||
monitored=True,
|
||||
affected_clinical_management=True,
|
||||
treatment_evidence="emergent catheterization and stent placed",
|
||||
)
|
||||
|
||||
stroke = ContextAssessment(
|
||||
condition_id="cva-01",
|
||||
diagnosis="Acute ischemic stroke",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence="Reason for admission: Acute ischemic stroke, emergent mechanical thrombectomy performed.",
|
||||
reason="Acute condition occasioning emergent admission.",
|
||||
treated_or_managed=True,
|
||||
monitored=True,
|
||||
affected_clinical_management=True,
|
||||
treatment_evidence="emergent mechanical thrombectomy performed",
|
||||
)
|
||||
|
||||
result, abstentions = classifier.classify_conditions([ami, stroke])
|
||||
|
||||
# Must NOT arbitrarily choose one!
|
||||
assert result.has_unique_primary is False
|
||||
assert result.primary_diagnosis is None
|
||||
assert result.is_ambiguous_primary is True
|
||||
assert result.abstention_recommended is True
|
||||
assert result.abstention_reason == AbstentionReason.MULTIPLE_AMBIGUOUS_PRIMARY
|
||||
|
||||
# Check abstention record was emitted
|
||||
assert len(abstentions) > 0
|
||||
assert any(a.reason == AbstentionReason.MULTIPLE_AMBIGUOUS_PRIMARY for a in abstentions)
|
||||
|
||||
|
||||
def test_scenario_5_no_defensible_primary() -> None:
|
||||
"""Requirement 5: No defensible primary diagnosis.
|
||||
|
||||
All conditions in record are historical or ruled out; no condition qualifies as reason for admission.
|
||||
Agent must not force a primary diagnosis.
|
||||
"""
|
||||
mock_llm = MagicMock()
|
||||
classifier = PrimarySecondaryClassifier(mock_llm)
|
||||
|
||||
ruled_out_pe = ContextAssessment(
|
||||
condition_id="pe-01",
|
||||
diagnosis="Pulmonary embolism",
|
||||
current_relevance=False,
|
||||
coding_candidate=False,
|
||||
status=ConditionStatus.RESOLVED,
|
||||
certainty=Certainty.RULED_OUT,
|
||||
temporality=Temporality.CURRENT,
|
||||
negation=NegationStatus.NEGATED,
|
||||
evidence="Suspected pulmonary embolism ruled out by negative CT angiogram.",
|
||||
reason="Definitively ruled out by diagnostic imaging.",
|
||||
)
|
||||
|
||||
hist_lipid = ContextAssessment(
|
||||
condition_id="lipid-01",
|
||||
diagnosis="Hyperlipidemia",
|
||||
current_relevance=False,
|
||||
coding_candidate=False,
|
||||
status=ConditionStatus.HISTORICAL,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.HISTORICAL,
|
||||
evidence="Past history of hyperlipidemia.",
|
||||
reason="Historical condition without active management.",
|
||||
)
|
||||
|
||||
result, _ = classifier.classify_conditions([ruled_out_pe, hist_lipid])
|
||||
|
||||
assert result.primary_diagnosis is None
|
||||
assert result.has_unique_primary is False
|
||||
assert len(result.secondary_diagnoses) == 0
|
||||
assert len(result.excluded_conditions) == 2
|
||||
|
||||
|
||||
def test_scenario_6_primary_plus_secondary_conditions() -> None:
|
||||
"""Requirement 6: Primary diagnosis plus secondary conditions.
|
||||
|
||||
Acute diverticulitis with perforation (primary occasioning admission) plus
|
||||
Acute kidney injury (secondary condition treated with IV fluids).
|
||||
"""
|
||||
mock_llm = MagicMock()
|
||||
classifier = PrimarySecondaryClassifier(mock_llm)
|
||||
|
||||
diverticulitis = ContextAssessment(
|
||||
condition_id="div-01",
|
||||
diagnosis="Acute perforated diverticulitis",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence="Admitted for acute perforated diverticulitis; emergency sigmoid resection performed.",
|
||||
reason="Acute condition occasioning urgent admission and surgical intervention.",
|
||||
treated_or_managed=True,
|
||||
monitored=True,
|
||||
affected_clinical_management=True,
|
||||
treatment_evidence="emergency sigmoid resection performed",
|
||||
)
|
||||
|
||||
aki = ContextAssessment(
|
||||
condition_id="aki-01",
|
||||
diagnosis="Acute kidney injury",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence="Acute kidney injury secondary to dehydration, treated with IV fluids.",
|
||||
reason="Co-existing acute condition treated and monitored during admission.",
|
||||
treated_or_managed=True,
|
||||
monitored=True,
|
||||
treatment_evidence="treated with IV fluids",
|
||||
)
|
||||
|
||||
result, _ = classifier.classify_conditions([diverticulitis, aki])
|
||||
|
||||
assert result.has_unique_primary is True
|
||||
assert result.primary_diagnosis is not None
|
||||
assert result.primary_diagnosis.diagnosis == "Acute perforated diverticulitis"
|
||||
assert len(result.secondary_diagnoses) == 1
|
||||
assert result.secondary_diagnoses[0].diagnosis == "Acute kidney injury"
|
||||
assert result.secondary_diagnoses[0].role == DiagnosisRole.SECONDARY
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Deterministic Validator Tests & Rejection of Multiple Primaries
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def test_deterministic_validator_rejects_llm_multiple_primaries() -> None:
|
||||
"""Requirement: The deterministic validator must strictly reject multiple primary diagnoses from an LLM.
|
||||
|
||||
Demonstrates that even if an LLM erroneously assigns role='PRIMARY' to multiple conditions,
|
||||
the deterministic layer catches the violation, demotes them, and emits MULTIPLE_AMBIGUOUS_PRIMARY.
|
||||
"""
|
||||
validator = PrimarySecondaryClassificationValidator()
|
||||
|
||||
# LLM erroneously marked TWO diagnoses as PRIMARY
|
||||
invalid_llm_output = [
|
||||
ConditionClassification(
|
||||
diagnosis_id="diag-01",
|
||||
diagnosis="Sepsis",
|
||||
role=DiagnosisRole.PRIMARY, # PRIMARY 1
|
||||
is_billable_candidate=True,
|
||||
classification_reason="Severe infection.",
|
||||
),
|
||||
ConditionClassification(
|
||||
diagnosis_id="diag-02",
|
||||
diagnosis="Bacterial pneumonia",
|
||||
role=DiagnosisRole.PRIMARY, # PRIMARY 2 (VIOLATION)
|
||||
is_billable_candidate=True,
|
||||
classification_reason="Lung infection.",
|
||||
),
|
||||
ConditionClassification(
|
||||
diagnosis_id="diag-03",
|
||||
diagnosis="Atrial fibrillation",
|
||||
role=DiagnosisRole.SECONDARY,
|
||||
is_billable_candidate=True,
|
||||
classification_reason="Rate controlled with metoprolol.",
|
||||
),
|
||||
]
|
||||
|
||||
# Validate classification
|
||||
result, abstentions = validator.validate_classification(invalid_llm_output)
|
||||
|
||||
# Deterministic layer MUST strip the multiple primaries to prevent invalid billing!
|
||||
assert result.primary_diagnosis is None
|
||||
assert result.has_unique_primary is False
|
||||
assert result.is_ambiguous_primary is True
|
||||
assert result.abstention_recommended is True
|
||||
assert result.abstention_reason == AbstentionReason.MULTIPLE_AMBIGUOUS_PRIMARY
|
||||
|
||||
# Check abstention records
|
||||
assert len(abstentions) >= 2
|
||||
for abst in abstentions:
|
||||
assert abst.reason == AbstentionReason.MULTIPLE_AMBIGUOUS_PRIMARY
|
||||
assert (
|
||||
"Multiple conflicting primary diagnoses" in abst.detail or "Conflicting" in abst.detail
|
||||
)
|
||||
|
||||
# Check strict exception mode
|
||||
with pytest.raises(MultiplePrimaryDiagnosesError, match="Multiple primary diagnoses detected"):
|
||||
validator.validate_or_raise(invalid_llm_output)
|
||||
|
||||
|
||||
def test_deterministic_validator_demotes_historical_primary() -> None:
|
||||
"""Requirement: Deterministic validator demotes a historical-only condition if mistakenly marked as primary."""
|
||||
validator = PrimarySecondaryClassificationValidator()
|
||||
|
||||
ctx = ContextAssessment(
|
||||
condition_id="diag-old",
|
||||
diagnosis="Old healed myocardial infarction",
|
||||
current_relevance=False,
|
||||
coding_candidate=False,
|
||||
status=ConditionStatus.HISTORICAL,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.HISTORICAL,
|
||||
evidence="MI occurred in 2012, no current intervention.",
|
||||
reason="Historical condition.",
|
||||
)
|
||||
|
||||
invalid_output = [
|
||||
ConditionClassification(
|
||||
diagnosis_id="diag-old",
|
||||
diagnosis="Old healed myocardial infarction",
|
||||
role=DiagnosisRole.PRIMARY, # INVALID FOR HISTORICAL
|
||||
is_billable_candidate=True,
|
||||
classification_reason="Historical MI.",
|
||||
)
|
||||
]
|
||||
|
||||
result, abstentions = validator.validate_classification(invalid_output, [ctx])
|
||||
|
||||
assert result.primary_diagnosis is None
|
||||
assert len(result.excluded_conditions) == 1
|
||||
assert result.excluded_conditions[0].role == DiagnosisRole.EXCLUDED
|
||||
assert result.excluded_conditions[0].is_billable_candidate is False
|
||||
assert any(a.reason == AbstentionReason.EXCLUDED_BY_TEMPORALITY for a in abstentions)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# LangGraph Node Execution Tests
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def test_langgraph_classify_diagnoses_node_execution() -> None:
|
||||
"""Requirement: LangGraph node execution updating graph state with classified diagnoses."""
|
||||
assessment_1 = ContextAssessment(
|
||||
condition_id="c-01",
|
||||
diagnosis="Acute cholecystitis",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence="Admitted for acute cholecystitis, underwent laparoscopic cholecystectomy.",
|
||||
reason="Operative admission condition.",
|
||||
treated_or_managed=True,
|
||||
treatment_evidence="laparoscopic cholecystectomy",
|
||||
)
|
||||
assessment_2 = ContextAssessment(
|
||||
condition_id="c-02",
|
||||
diagnosis="Hypertension",
|
||||
current_relevance=False,
|
||||
coding_candidate=False,
|
||||
status=ConditionStatus.HISTORICAL,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.HISTORICAL,
|
||||
evidence="Past history: hypertension.",
|
||||
reason="Historical condition.",
|
||||
)
|
||||
|
||||
state: PipelineGraphState = {
|
||||
"document_id": "doc-test-123",
|
||||
"raw_text": "Sample clinical summary text.",
|
||||
"context_assessments": [assessment_1, assessment_2],
|
||||
}
|
||||
|
||||
mock_llm = MagicMock()
|
||||
classifier = PrimarySecondaryClassifier(mock_llm)
|
||||
res_state = classifier.run_node(state)
|
||||
|
||||
assert "classified_diagnoses" in res_state
|
||||
assert "classification_result" in res_state
|
||||
assert res_state["current_stage"] == PipelineStage.CLASSIFICATION
|
||||
|
||||
enc_res: EncounterClassificationResult = res_state["classification_result"]
|
||||
assert enc_res.has_unique_primary is True
|
||||
assert enc_res.primary_diagnosis is not None
|
||||
assert enc_res.primary_diagnosis.diagnosis == "Acute cholecystitis"
|
||||
|
||||
classified = res_state["classified_diagnoses"]
|
||||
assert len(classified) == 2
|
||||
primary = next(c for c in classified if c.role == DiagnosisRole.PRIMARY)
|
||||
assert primary.raw_term == "Acute cholecystitis"
|
||||
assert primary.is_billable_candidate is True
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_classification_execution() -> None:
|
||||
"""Test asynchronous execution of classify_conditions_async."""
|
||||
mock_llm = MagicMock()
|
||||
mock_llm.ainvoke = AsyncMock(
|
||||
return_value=json.dumps(
|
||||
{
|
||||
"has_unique_primary": True,
|
||||
"classifications": [
|
||||
{
|
||||
"diagnosis_id": "cond-afib",
|
||||
"diagnosis": "Atrial fibrillation with RVR",
|
||||
"role": "PRIMARY",
|
||||
"is_billable_candidate": True,
|
||||
"classification_reason": "Admitted for RVR treated with diltiazem drip.",
|
||||
"primary_justification": "Chief condition occasioning admission.",
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
classifier = PrimarySecondaryClassifier(mock_llm)
|
||||
assessment = ContextAssessment(
|
||||
condition_id="cond-afib",
|
||||
diagnosis="Atrial fibrillation with RVR",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence="Admitted for RVR treated with diltiazem drip.",
|
||||
reason="Primary admitting condition.",
|
||||
treated_or_managed=True,
|
||||
)
|
||||
|
||||
result, _ = await classifier.classify_conditions_async(
|
||||
[assessment], "Admitted for RVR treated with diltiazem drip."
|
||||
)
|
||||
|
||||
assert result.has_unique_primary is True
|
||||
assert result.primary_diagnosis is not None
|
||||
assert result.primary_diagnosis.diagnosis == "Atrial fibrillation with RVR"
|
||||
assert result.primary_diagnosis.role == DiagnosisRole.PRIMARY
|
||||
@@ -0,0 +1,411 @@
|
||||
"""Unit tests and clinical case fixtures for the Clinical Information Extraction Agent."""
|
||||
|
||||
import json
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from medical_coding.agents.extractor import ClinicalExtractionAgent
|
||||
from medical_coding.agents.parser import ExtractionParser
|
||||
from medical_coding.schemas.enums import (
|
||||
Certainty,
|
||||
ConditionStatus,
|
||||
NegationStatus,
|
||||
Temporality,
|
||||
)
|
||||
|
||||
# ============================================================================
|
||||
# Clinical Case Fixtures
|
||||
# ============================================================================
|
||||
|
||||
CLINICAL_NOTE_CURRENT_UTI = """DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Dysuria, fever, and urinary frequency.
|
||||
HOSPITAL COURSE: Patient diagnosed with acute urinary tract infection (UTI), urine culture positive for Escherichia coli. Treated with 5 days of IV ceftriaxone with complete resolution of dysuria and fever.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Acute urinary tract infection.
|
||||
"""
|
||||
|
||||
CLINICAL_NOTE_HISTORICAL_DIABETES = """DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Right ankle inversion sprain while jogging.
|
||||
PAST MEDICAL HISTORY:
|
||||
1. Type 2 diabetes mellitus diagnosed 15 years ago, managed on metformin.
|
||||
2. Essential hypertension.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Grade 2 right ankle sprain.
|
||||
"""
|
||||
|
||||
CLINICAL_NOTE_SUSPECTED_PNEUMONIA_RULED_OUT = """DISCHARGE SUMMARY
|
||||
HISTORY OF PRESENT ILLNESS: Patient presented with cough, pleuritic chest pain, and low-grade fever, admitted for suspected bacterial pneumonia.
|
||||
HOSPITAL COURSE: Chest CT demonstrated clear lung fields with no consolidation or infiltrate. Sputum cultures were negative. Viral PCR was positive for rhinovirus. Bacterial pneumonia was definitively ruled out.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Acute viral upper respiratory infection.
|
||||
"""
|
||||
|
||||
CLINICAL_NOTE_MULTIPLE_DIAGNOSES = """DISCHARGE SUMMARY
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Acute systolic heart failure.
|
||||
2. Chronic obstructive pulmonary disease exacerbation.
|
||||
3. Essential hypertension.
|
||||
4. Acute kidney injury secondary to volume depletion.
|
||||
HOSPITAL COURSE: Patient received IV furosemide for heart failure and nebulized bronchodilators for COPD. Creatinine improved with hydration.
|
||||
"""
|
||||
|
||||
CLINICAL_NOTE_PMH_ONLY = """DISCHARGE SUMMARY
|
||||
HOSPITAL COURSE: Patient underwent elective laparoscopic cholecystectomy for symptomatic cholelithiasis.
|
||||
PAST MEDICAL HISTORY:
|
||||
1. Longstanding gastroesophageal reflux disease (GERD).
|
||||
2. Hyperlipidemia.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Symptomatic cholelithiasis.
|
||||
"""
|
||||
|
||||
CLINICAL_NOTE_FINAL_DISCHARGE_DIAGNOSIS = """DISCHARGE SUMMARY
|
||||
HISTORY OF PRESENT ILLNESS: 72-year-old female admitted with crushing substernal chest pressure.
|
||||
HOSPITAL COURSE: Troponins peaked at 4.2 ng/mL. Diagnostic coronary catheterization revealed 90% occlusion of the left anterior descending artery. Stent was successfully placed.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Acute non-ST-elevation myocardial infarction (NSTEMI).
|
||||
2. Coronary artery disease.
|
||||
"""
|
||||
|
||||
CLINICAL_NOTE_CONTRADICTORY_MENTIONS = """DISCHARGE SUMMARY
|
||||
HISTORY OF PRESENT ILLNESS: Patient presented with acute shortness of breath and tachypnea, admitted for suspected acute pulmonary embolism.
|
||||
HOSPITAL COURSE: CT pulmonary angiography was completely negative for pulmonary embolism; no filling defects observed. Pulmonary embolism was definitively excluded. D-dimer was mildly elevated due to acute pleurisy.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Acute viral pleurisy.
|
||||
"""
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Unit Tests: Parser and Grounding Rules
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def test_parser_strips_markdown_and_repairs_syntax() -> None:
|
||||
"""Verify that parser extracts JSON from markdown fences and repairs single quotes/trailing commas."""
|
||||
parser = ExtractionParser()
|
||||
doc_text = "Patient was admitted for acute appendicitis. Appendectomy performed."
|
||||
|
||||
# Raw LLM output with conversational preamble, markdown fence, single quotes, and trailing comma
|
||||
noisy_llm_output = """Here is the extracted condition:
|
||||
```json
|
||||
[
|
||||
{
|
||||
'original_mention': 'acute appendicitis',
|
||||
'normalized_description': 'Acute appendicitis',
|
||||
'evidence_text': 'Patient was admitted for acute appendicitis.',
|
||||
'certainty': 'confirmed',
|
||||
'temporality': 'current',
|
||||
'status': 'acute',
|
||||
'section': 'DISCHARGE_DIAGNOSES',
|
||||
},
|
||||
]
|
||||
```
|
||||
Hope this helps!"""
|
||||
|
||||
conditions, notes, repaired = parser.parse_and_validate(noisy_llm_output, doc_text)
|
||||
|
||||
assert len(conditions) == 1
|
||||
assert repaired is True
|
||||
cond = conditions[0]
|
||||
assert cond.original_mention == "acute appendicitis"
|
||||
assert cond.certainty == Certainty.CONFIRMED
|
||||
assert cond.temporality == Temporality.CURRENT
|
||||
assert cond.status == ConditionStatus.ACUTE
|
||||
assert cond.evidence_text == "Patient was admitted for acute appendicitis."
|
||||
|
||||
|
||||
def test_parser_drops_hallucinated_evidence_without_proof() -> None:
|
||||
"""Requirement: Every diagnosis must have evidence. Drop items where evidence is fabricated."""
|
||||
parser = ExtractionParser()
|
||||
doc_text = "Patient presented with a simple rash on right arm."
|
||||
|
||||
# LLM hallucinates diabetes with a fake quote that does not exist in doc_text
|
||||
hallucinated_llm_output = json.dumps(
|
||||
[
|
||||
{
|
||||
"original_mention": "Type 2 diabetes",
|
||||
"normalized_description": "Type 2 diabetes",
|
||||
"evidence_text": "Patient has severe uncontrolled diabetes.", # NOT IN DOC
|
||||
"certainty": "CONFIRMED",
|
||||
"temporality": "CURRENT",
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
conditions, notes, _ = parser.parse_and_validate(hallucinated_llm_output, doc_text)
|
||||
|
||||
# Condition MUST be discarded because evidence quote is not in document
|
||||
assert len(conditions) == 0
|
||||
assert any("discarded: evidence quote" in note for note in notes)
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Test Cases 1 - 7: Specific Clinical Scenarios
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def test_scenario_1_current_uti() -> None:
|
||||
"""Test 1: Current UTI is extracted with CURRENT temporality, CONFIRMED certainty, and treatment."""
|
||||
mock_llm = MagicMock()
|
||||
mock_llm.invoke.return_value = json.dumps(
|
||||
[
|
||||
{
|
||||
"original_mention": "acute urinary tract infection (UTI)",
|
||||
"normalized_description": "Acute urinary tract infection",
|
||||
"entity_type": "DIAGNOSIS",
|
||||
"evidence_text": "Patient diagnosed with acute urinary tract infection (UTI), urine culture positive for Escherichia coli.",
|
||||
"status": "ACTIVE",
|
||||
"certainty": "CONFIRMED",
|
||||
"temporality": "CURRENT",
|
||||
"negation": "AFFIRMATIVE",
|
||||
"anatomical_site": "urinary tract",
|
||||
"section": "HOSPITAL_COURSE",
|
||||
"treatment_evidence": "Treated with 5 days of IV ceftriaxone",
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
agent = ClinicalExtractionAgent(llm=mock_llm)
|
||||
result = agent.extract_clinical_conditions(CLINICAL_NOTE_CURRENT_UTI)
|
||||
|
||||
assert len(result.conditions) == 1
|
||||
uti = result.conditions[0]
|
||||
assert uti.normalized_description == "Acute urinary tract infection"
|
||||
assert uti.temporality == Temporality.CURRENT
|
||||
assert uti.certainty == Certainty.CONFIRMED
|
||||
assert uti.negation == NegationStatus.AFFIRMATIVE
|
||||
assert uti.treatment_evidence == "Treated with 5 days of IV ceftriaxone"
|
||||
|
||||
|
||||
def test_scenario_2_historical_diabetes() -> None:
|
||||
"""Test 2: Historical diabetes in PMH must have HISTORICAL temporality and not current acute status."""
|
||||
mock_llm = MagicMock()
|
||||
mock_llm.invoke.return_value = json.dumps(
|
||||
[
|
||||
{
|
||||
"original_mention": "Type 2 diabetes mellitus",
|
||||
"normalized_description": "Type 2 diabetes mellitus",
|
||||
"entity_type": "DIAGNOSIS",
|
||||
"evidence_text": "Type 2 diabetes mellitus diagnosed 15 years ago, managed on metformin.",
|
||||
"status": "HISTORICAL",
|
||||
"certainty": "CONFIRMED",
|
||||
"temporality": "HISTORICAL",
|
||||
"negation": "AFFIRMATIVE",
|
||||
"section": "PAST_MEDICAL_HISTORY",
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
agent = ClinicalExtractionAgent(llm=mock_llm)
|
||||
result = agent.extract_clinical_conditions(CLINICAL_NOTE_HISTORICAL_DIABETES)
|
||||
|
||||
assert len(result.conditions) == 1
|
||||
dm = result.conditions[0]
|
||||
assert dm.temporality == Temporality.HISTORICAL
|
||||
assert dm.status in (ConditionStatus.HISTORICAL, ConditionStatus.CHRONIC)
|
||||
assert dm.section == "PAST_MEDICAL_HISTORY"
|
||||
|
||||
|
||||
def test_scenario_3_suspected_pneumonia_ruled_out() -> None:
|
||||
"""Test 3: Suspected pneumonia later definitively excluded must be classified as RULED_OUT."""
|
||||
mock_llm = MagicMock()
|
||||
mock_llm.invoke.return_value = json.dumps(
|
||||
[
|
||||
{
|
||||
"original_mention": "bacterial pneumonia",
|
||||
"normalized_description": "Bacterial pneumonia",
|
||||
"entity_type": "DIAGNOSIS",
|
||||
"evidence_text": "Bacterial pneumonia was definitively ruled out.",
|
||||
"status": "RESOLVED",
|
||||
"certainty": "RULED_OUT",
|
||||
"temporality": "CURRENT",
|
||||
"negation": "NEGATED",
|
||||
"section": "HOSPITAL_COURSE",
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
agent = ClinicalExtractionAgent(llm=mock_llm)
|
||||
result = agent.extract_clinical_conditions(CLINICAL_NOTE_SUSPECTED_PNEUMONIA_RULED_OUT)
|
||||
|
||||
assert len(result.conditions) == 1
|
||||
pna = result.conditions[0]
|
||||
assert pna.certainty == Certainty.RULED_OUT
|
||||
assert pna.negation == NegationStatus.NEGATED
|
||||
|
||||
|
||||
def test_scenario_4_multiple_diagnoses() -> None:
|
||||
"""Test 4: Multiple distinct active diagnoses extracted with separate evidence grounding."""
|
||||
mock_llm = MagicMock()
|
||||
mock_llm.invoke.return_value = json.dumps(
|
||||
[
|
||||
{
|
||||
"original_mention": "Acute systolic heart failure",
|
||||
"normalized_description": "Acute systolic heart failure",
|
||||
"evidence_text": "1. Acute systolic heart failure.",
|
||||
"status": "ACTIVE",
|
||||
"certainty": "CONFIRMED",
|
||||
"temporality": "CURRENT",
|
||||
"section": "DISCHARGE_DIAGNOSES",
|
||||
},
|
||||
{
|
||||
"original_mention": "Chronic obstructive pulmonary disease exacerbation",
|
||||
"normalized_description": "COPD exacerbation",
|
||||
"evidence_text": "2. Chronic obstructive pulmonary disease exacerbation.",
|
||||
"status": "ACTIVE",
|
||||
"certainty": "CONFIRMED",
|
||||
"temporality": "CURRENT",
|
||||
"section": "DISCHARGE_DIAGNOSES",
|
||||
},
|
||||
{
|
||||
"original_mention": "Essential hypertension",
|
||||
"normalized_description": "Essential hypertension",
|
||||
"evidence_text": "3. Essential hypertension.",
|
||||
"status": "CHRONIC",
|
||||
"certainty": "CONFIRMED",
|
||||
"temporality": "CURRENT",
|
||||
"section": "DISCHARGE_DIAGNOSES",
|
||||
},
|
||||
{
|
||||
"original_mention": "Acute kidney injury",
|
||||
"normalized_description": "Acute kidney injury",
|
||||
"evidence_text": "4. Acute kidney injury secondary to volume depletion.",
|
||||
"status": "ACTIVE",
|
||||
"certainty": "CONFIRMED",
|
||||
"temporality": "CURRENT",
|
||||
"section": "DISCHARGE_DIAGNOSES",
|
||||
},
|
||||
]
|
||||
)
|
||||
|
||||
agent = ClinicalExtractionAgent(llm=mock_llm)
|
||||
result = agent.extract_clinical_conditions(CLINICAL_NOTE_MULTIPLE_DIAGNOSES)
|
||||
|
||||
assert len(result.conditions) == 4
|
||||
descriptions = {c.normalized_description for c in result.conditions}
|
||||
assert "Acute systolic heart failure" in descriptions
|
||||
assert "Acute kidney injury" in descriptions
|
||||
|
||||
|
||||
def test_scenario_5_diagnosis_in_past_medical_history_only() -> None:
|
||||
"""Test 5: Condition appearing in past medical history only must be assigned HISTORICAL temporality."""
|
||||
mock_llm = MagicMock()
|
||||
mock_llm.invoke.return_value = json.dumps(
|
||||
[
|
||||
{
|
||||
"original_mention": "gastroesophageal reflux disease (GERD)",
|
||||
"normalized_description": "GERD",
|
||||
"evidence_text": "1. Longstanding gastroesophageal reflux disease (GERD).",
|
||||
"status": "CHRONIC",
|
||||
"certainty": "CONFIRMED",
|
||||
"temporality": "CURRENT", # Even if LLM naively claimed CURRENT, PMH rule reconciles it to HISTORICAL
|
||||
"section": "PAST_MEDICAL_HISTORY",
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
agent = ClinicalExtractionAgent(llm=mock_llm)
|
||||
result = agent.extract_clinical_conditions(CLINICAL_NOTE_PMH_ONLY)
|
||||
|
||||
assert len(result.conditions) == 1
|
||||
gerd = result.conditions[0]
|
||||
# Agent reconciliation must enforce HISTORICAL temporality for PMH-only conditions
|
||||
assert gerd.temporality == Temporality.HISTORICAL
|
||||
|
||||
|
||||
def test_scenario_6_diagnosis_in_final_discharge_diagnosis() -> None:
|
||||
"""Test 6: Diagnosis in final discharge diagnoses has DISCHARGE_DIAGNOSES section and CONFIRMED certainty."""
|
||||
mock_llm = MagicMock()
|
||||
mock_llm.invoke.return_value = json.dumps(
|
||||
[
|
||||
{
|
||||
"original_mention": "Acute non-ST-elevation myocardial infarction (NSTEMI)",
|
||||
"normalized_description": "NSTEMI",
|
||||
"evidence_text": "1. Acute non-ST-elevation myocardial infarction (NSTEMI).",
|
||||
"status": "ACUTE",
|
||||
"certainty": "CONFIRMED",
|
||||
"temporality": "CURRENT",
|
||||
"section": "DISCHARGE_DIAGNOSES",
|
||||
"treatment_evidence": "Stent was successfully placed",
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
agent = ClinicalExtractionAgent(llm=mock_llm)
|
||||
result = agent.extract_clinical_conditions(CLINICAL_NOTE_FINAL_DISCHARGE_DIAGNOSIS)
|
||||
|
||||
assert len(result.conditions) == 1
|
||||
nstemi = result.conditions[0]
|
||||
assert nstemi.certainty == Certainty.CONFIRMED
|
||||
assert nstemi.temporality == Temporality.CURRENT
|
||||
assert nstemi.section == "DISCHARGE_DIAGNOSES"
|
||||
assert nstemi.treatment_evidence == "Stent was successfully placed"
|
||||
|
||||
|
||||
def test_scenario_7_contradictory_mentions_reconciled() -> None:
|
||||
"""Test 7: Mentioned as suspected initially in HPI but later ruled out in Hospital Course.
|
||||
|
||||
Reconciliation must favor the definitive RULED_OUT certainty.
|
||||
"""
|
||||
mock_llm = MagicMock()
|
||||
mock_llm.invoke.return_value = json.dumps(
|
||||
[
|
||||
{
|
||||
"original_mention": "acute pulmonary embolism",
|
||||
"normalized_description": "Pulmonary embolism",
|
||||
"evidence_text": "Patient presented with acute shortness of breath and tachypnea, admitted for suspected acute pulmonary embolism.",
|
||||
"status": "ACTIVE",
|
||||
"certainty": "SUSPECTED",
|
||||
"temporality": "CURRENT",
|
||||
"negation": "AFFIRMATIVE",
|
||||
"section": "HISTORY_OF_PRESENT_ILLNESS",
|
||||
},
|
||||
{
|
||||
"original_mention": "pulmonary embolism",
|
||||
"normalized_description": "Pulmonary embolism",
|
||||
"evidence_text": "Pulmonary embolism was definitively excluded.",
|
||||
"status": "RESOLVED",
|
||||
"certainty": "RULED_OUT",
|
||||
"temporality": "CURRENT",
|
||||
"negation": "NEGATED",
|
||||
"section": "HOSPITAL_COURSE",
|
||||
},
|
||||
]
|
||||
)
|
||||
|
||||
agent = ClinicalExtractionAgent(llm=mock_llm)
|
||||
result = agent.extract_clinical_conditions(CLINICAL_NOTE_CONTRADICTORY_MENTIONS)
|
||||
|
||||
# Reconciled into a single concept where RULED_OUT overrides SUSPECTED
|
||||
assert len(result.conditions) == 1
|
||||
pe = result.conditions[0]
|
||||
assert pe.certainty == Certainty.RULED_OUT
|
||||
assert pe.negation == NegationStatus.NEGATED
|
||||
assert pe.status == ConditionStatus.RESOLVED
|
||||
|
||||
|
||||
def test_agent_retry_policy_on_malformed_first_response() -> None:
|
||||
"""Verify that agent retries when first generation is malformed and succeeds on retry."""
|
||||
mock_llm = MagicMock()
|
||||
# First response is malformed / empty, second response succeeds
|
||||
mock_llm.invoke.side_effect = [
|
||||
"Sorry, I cannot produce valid JSON right now.",
|
||||
json.dumps(
|
||||
[
|
||||
{
|
||||
"original_mention": "Grade 2 right ankle sprain",
|
||||
"normalized_description": "Right ankle sprain",
|
||||
"evidence_text": "1. Grade 2 right ankle sprain.",
|
||||
"status": "ACUTE",
|
||||
"certainty": "CONFIRMED",
|
||||
"temporality": "CURRENT",
|
||||
"section": "DISCHARGE_DIAGNOSES",
|
||||
}
|
||||
]
|
||||
),
|
||||
]
|
||||
|
||||
agent = ClinicalExtractionAgent(llm=mock_llm, max_retries=2)
|
||||
result = agent.extract_clinical_conditions(CLINICAL_NOTE_HISTORICAL_DIABETES)
|
||||
|
||||
assert mock_llm.invoke.call_count == 2
|
||||
assert len(result.conditions) == 1
|
||||
assert result.conditions[0].normalized_description == "Right ankle sprain"
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Unit tests for configuration management."""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from medical_coding.config.settings import Settings, get_settings
|
||||
|
||||
|
||||
def test_default_settings() -> None:
|
||||
"""Verify sensible offline defaults."""
|
||||
settings = Settings()
|
||||
assert settings.offline_mode is True
|
||||
assert settings.environment == "development"
|
||||
assert settings.llm_n_threads >= 1
|
||||
assert settings.llm_temperature == 0.0
|
||||
assert isinstance(settings.llm_model_path, Path)
|
||||
assert settings.max_batch_concurrency >= 10
|
||||
|
||||
|
||||
def test_environment_override(monkeypatch) -> None:
|
||||
"""Verify settings pick up env variables."""
|
||||
monkeypatch.setenv("ENVIRONMENT", "production")
|
||||
monkeypatch.setenv("LLM_N_THREADS", "8")
|
||||
monkeypatch.setenv("LOG_LEVEL", "warning")
|
||||
monkeypatch.setenv("MAX_BATCH_CONCURRENCY", "20")
|
||||
|
||||
settings = Settings()
|
||||
assert settings.environment == "production"
|
||||
assert settings.llm_n_threads == 8
|
||||
assert settings.log_level == "WARNING"
|
||||
assert settings.max_batch_concurrency == 20
|
||||
|
||||
|
||||
def test_get_settings_singleton() -> None:
|
||||
"""Verify cached singleton behavior."""
|
||||
get_settings.cache_clear()
|
||||
s1 = get_settings()
|
||||
s2 = get_settings()
|
||||
assert s1 is s2
|
||||
get_settings.cache_clear()
|
||||
@@ -0,0 +1,517 @@
|
||||
"""Unit tests for the Context and Clinical Relevance Agent."""
|
||||
|
||||
import json
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from medical_coding.agents.classifier import ContextAndRelevanceAgent
|
||||
from medical_coding.schemas.clinical import (
|
||||
ContextAssessment,
|
||||
EvidenceLocation,
|
||||
ExtractedClinicalCondition,
|
||||
)
|
||||
from medical_coding.schemas.enums import (
|
||||
AbstentionReason,
|
||||
Certainty,
|
||||
ConditionStatus,
|
||||
NegationStatus,
|
||||
PipelineStage,
|
||||
Temporality,
|
||||
)
|
||||
from medical_coding.schemas.state import PipelineGraphState
|
||||
|
||||
# ============================================================================
|
||||
# Test Cases 1 - 7: Specific Clinical Scenarios
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def test_scenario_pmh_alone_not_coding_candidate() -> None:
|
||||
"""Requirement: Past Medical History alone must NOT automatically qualify as a secondary diagnosis.
|
||||
|
||||
Example: "Past history: diabetes mellitus." without active management.
|
||||
"""
|
||||
mock_llm = MagicMock()
|
||||
agent = ContextAndRelevanceAgent(mock_llm)
|
||||
|
||||
condition = ExtractedClinicalCondition(
|
||||
condition_id="pmh-dm-01",
|
||||
original_mention="diabetes mellitus",
|
||||
normalized_description="Type 2 diabetes mellitus",
|
||||
evidence_text="Past medical history: diabetes mellitus for 10 years.",
|
||||
evidence_location=EvidenceLocation(section="PAST_MEDICAL_HISTORY", page_number=1),
|
||||
section="PAST_MEDICAL_HISTORY",
|
||||
status=ConditionStatus.HISTORICAL,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.HISTORICAL,
|
||||
treatment_evidence=None,
|
||||
)
|
||||
|
||||
assessments = agent._fallback_rule_assessment([condition])
|
||||
|
||||
assert len(assessments) == 1
|
||||
asm = assessments[0]
|
||||
assert asm.diagnosis == "Type 2 diabetes mellitus"
|
||||
assert asm.coding_candidate is False
|
||||
assert asm.current_relevance is False
|
||||
assert asm.status == ConditionStatus.HISTORICAL
|
||||
assert asm.temporality == Temporality.HISTORICAL
|
||||
assert "Past Medical History alone" in asm.reason
|
||||
assert asm.treated_or_managed is False
|
||||
assert asm.monitored is False
|
||||
|
||||
|
||||
def test_scenario_pmh_with_monitoring_and_treatment_is_coding_candidate() -> None:
|
||||
"""Requirement: PMH with active monitoring and medication adjustment during admission qualifies.
|
||||
|
||||
Example: "Diabetes mellitus was monitored and insulin was adjusted during admission."
|
||||
"""
|
||||
mock_llm = MagicMock()
|
||||
agent = ContextAndRelevanceAgent(mock_llm)
|
||||
|
||||
condition = ExtractedClinicalCondition(
|
||||
condition_id="pmh-dm-active-02",
|
||||
original_mention="Diabetes mellitus",
|
||||
normalized_description="Type 2 diabetes mellitus",
|
||||
evidence_text="Diabetes mellitus was monitored and insulin was adjusted during admission.",
|
||||
evidence_location=EvidenceLocation(section="HOSPITAL_COURSE", page_number=1),
|
||||
section="HOSPITAL_COURSE",
|
||||
status=ConditionStatus.CHRONIC,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
treatment_evidence="insulin was adjusted",
|
||||
)
|
||||
|
||||
assessments = agent._fallback_rule_assessment([condition])
|
||||
|
||||
assert len(assessments) == 1
|
||||
asm = assessments[0]
|
||||
assert asm.diagnosis == "Type 2 diabetes mellitus"
|
||||
assert asm.coding_candidate is True
|
||||
assert asm.current_relevance is True
|
||||
assert asm.status == ConditionStatus.CHRONIC
|
||||
assert asm.temporality == Temporality.CURRENT
|
||||
assert asm.treated_or_managed is True
|
||||
assert asm.monitored is True
|
||||
assert asm.affected_clinical_management is True
|
||||
|
||||
|
||||
def test_scenario_current_active_acute_condition() -> None:
|
||||
"""Requirement: Current acute condition treated during stay is clinically relevant and a coding candidate."""
|
||||
mock_llm = MagicMock()
|
||||
agent = ContextAndRelevanceAgent(mock_llm)
|
||||
|
||||
condition = ExtractedClinicalCondition(
|
||||
condition_id="uti-01",
|
||||
original_mention="acute urinary tract infection",
|
||||
normalized_description="Acute urinary tract infection",
|
||||
evidence_text="Patient diagnosed with acute urinary tract infection, treated with 5 days of IV ceftriaxone.",
|
||||
evidence_location=EvidenceLocation(section="HOSPITAL_COURSE", page_number=1),
|
||||
section="HOSPITAL_COURSE",
|
||||
status=ConditionStatus.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
treatment_evidence="treated with 5 days of IV ceftriaxone",
|
||||
)
|
||||
|
||||
assessments = agent._fallback_rule_assessment([condition])
|
||||
|
||||
assert len(assessments) == 1
|
||||
asm = assessments[0]
|
||||
assert asm.diagnosis == "Acute urinary tract infection"
|
||||
assert asm.coding_candidate is True
|
||||
assert asm.current_relevance is True
|
||||
assert asm.status == ConditionStatus.ACUTE
|
||||
assert asm.certainty == Certainty.CONFIRMED
|
||||
assert asm.treated_or_managed is True
|
||||
assert asm.influenced_treatment is True
|
||||
|
||||
|
||||
def test_scenario_ruled_out_pneumonia_not_confirmed() -> None:
|
||||
"""Requirement: Suspected condition ruled out by imaging/workup must NOT become confirmed.
|
||||
|
||||
Example: "Possible pneumonia was suspected initially but imaging showed no evidence of pneumonia."
|
||||
"""
|
||||
mock_llm = MagicMock()
|
||||
agent = ContextAndRelevanceAgent(mock_llm)
|
||||
|
||||
condition = ExtractedClinicalCondition(
|
||||
condition_id="pna-ruled-out-01",
|
||||
original_mention="possible pneumonia",
|
||||
normalized_description="Bacterial pneumonia",
|
||||
evidence_text="Possible pneumonia was suspected initially but imaging showed no evidence of pneumonia.",
|
||||
evidence_location=EvidenceLocation(section="HOSPITAL_COURSE", page_number=1),
|
||||
section="HOSPITAL_COURSE",
|
||||
status=ConditionStatus.RESOLVED,
|
||||
certainty=Certainty.RULED_OUT,
|
||||
temporality=Temporality.CURRENT,
|
||||
negation=NegationStatus.NEGATED,
|
||||
treatment_evidence=None,
|
||||
)
|
||||
|
||||
assessments = agent._fallback_rule_assessment([condition])
|
||||
|
||||
assert len(assessments) == 1
|
||||
asm = assessments[0]
|
||||
assert asm.diagnosis == "Bacterial pneumonia"
|
||||
assert asm.coding_candidate is False
|
||||
assert asm.current_relevance is False
|
||||
assert asm.certainty == Certainty.RULED_OUT
|
||||
assert asm.negation == NegationStatus.NEGATED
|
||||
assert "ruled out" in asm.reason.lower()
|
||||
|
||||
|
||||
def test_scenario_suspected_condition_preserves_uncertainty() -> None:
|
||||
"""Requirement: Suspected/uncertain condition must NOT be converted to CONFIRMED.
|
||||
|
||||
Under inpatient coding guidelines, suspected conditions at discharge evaluated/treated
|
||||
may be coded, but certainty must remain SUSPECTED.
|
||||
"""
|
||||
mock_llm = MagicMock()
|
||||
agent = ContextAndRelevanceAgent(mock_llm)
|
||||
|
||||
condition = ExtractedClinicalCondition(
|
||||
condition_id="pna-suspected-02",
|
||||
original_mention="suspected bacterial pneumonia",
|
||||
normalized_description="Bacterial pneumonia",
|
||||
evidence_text="Suspected bacterial pneumonia treated with empiric levofloxacin, culture pending at discharge.",
|
||||
evidence_location=EvidenceLocation(section="DISCHARGE_DIAGNOSIS", page_number=1),
|
||||
section="DISCHARGE_DIAGNOSIS",
|
||||
status=ConditionStatus.ACTIVE,
|
||||
certainty=Certainty.SUSPECTED,
|
||||
temporality=Temporality.CURRENT,
|
||||
treatment_evidence="treated with empiric levofloxacin",
|
||||
)
|
||||
|
||||
assessments = agent._fallback_rule_assessment([condition])
|
||||
|
||||
assert len(assessments) == 1
|
||||
asm = assessments[0]
|
||||
assert asm.diagnosis == "Bacterial pneumonia"
|
||||
assert asm.coding_candidate is True
|
||||
assert asm.current_relevance is True
|
||||
# MUST retain SUSPECTED, never converted to CONFIRMED
|
||||
assert asm.certainty == Certainty.SUSPECTED
|
||||
assert asm.treated_or_managed is True
|
||||
|
||||
|
||||
def test_scenario_resolved_condition_during_stay() -> None:
|
||||
"""Requirement: Acute condition that resolved during stay following active treatment qualifies as coding candidate."""
|
||||
mock_llm = MagicMock()
|
||||
agent = ContextAndRelevanceAgent(mock_llm)
|
||||
|
||||
condition = ExtractedClinicalCondition(
|
||||
condition_id="hypok-01",
|
||||
original_mention="acute hypokalemia",
|
||||
normalized_description="Hypokalemia",
|
||||
evidence_text="Acute hypokalemia, resolved following IV potassium replacement.",
|
||||
evidence_location=EvidenceLocation(section="HOSPITAL_COURSE", page_number=1),
|
||||
section="HOSPITAL_COURSE",
|
||||
status=ConditionStatus.RESOLVED,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
treatment_evidence="IV potassium replacement",
|
||||
)
|
||||
|
||||
assessments = agent._fallback_rule_assessment([condition])
|
||||
|
||||
assert len(assessments) == 1
|
||||
asm = assessments[0]
|
||||
assert asm.diagnosis == "Hypokalemia"
|
||||
assert asm.coding_candidate is True
|
||||
assert asm.current_relevance is True
|
||||
assert asm.status == ConditionStatus.RESOLVED
|
||||
assert asm.treated_or_managed is True
|
||||
assert "resolved" in asm.reason.lower()
|
||||
|
||||
|
||||
def test_scenario_ambiguous_contradictory_triggers_abstention() -> None:
|
||||
"""Requirement: Contradictory clinical documentation must trigger explicit abstention rather than forced classification."""
|
||||
mock_llm = MagicMock()
|
||||
agent = ContextAndRelevanceAgent(mock_llm)
|
||||
|
||||
condition = ExtractedClinicalCondition(
|
||||
condition_id="sepsis-ambig-01",
|
||||
original_mention="sepsis vs non-infectious SIRS",
|
||||
normalized_description="Sepsis",
|
||||
evidence_text="Contradictory notes: ED diagnosed severe sepsis, but ID consult definitively concluded no sepsis criteria met.",
|
||||
evidence_location=EvidenceLocation(section="CONSULTATION_NOTE", page_number=2),
|
||||
section="CONSULTATION_NOTE",
|
||||
status=ConditionStatus.UNKNOWN,
|
||||
certainty=Certainty.SUSPECTED,
|
||||
temporality=Temporality.CURRENT,
|
||||
treatment_evidence=None,
|
||||
)
|
||||
|
||||
assessments = agent._fallback_rule_assessment([condition])
|
||||
|
||||
assert len(assessments) == 1
|
||||
asm = assessments[0]
|
||||
assert asm.diagnosis == "Sepsis"
|
||||
assert asm.abstain_recommended is True
|
||||
assert asm.abstention_reason == AbstentionReason.CONTRADICTORY_DOCUMENTATION
|
||||
assert asm.coding_candidate is False
|
||||
assert "abstention" in asm.reason.lower() or "contradictory" in asm.reason.lower()
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Deterministic Guardrails & LLM Override Tests
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def test_guardrail_overrides_llm_hallucinated_pmh_eligibility() -> None:
|
||||
"""Requirement: Even if LLM hallucinates coding_candidate=True for PMH alone, deterministic guardrails override it."""
|
||||
mock_llm = MagicMock()
|
||||
# LLM improperly marks PMH condition as coding_candidate = true
|
||||
mock_llm.invoke.return_value = json.dumps(
|
||||
[
|
||||
{
|
||||
"diagnosis": "Essential hypertension",
|
||||
"current_relevance": True,
|
||||
"coding_candidate": True, # HALLUCINATED TRUE FOR UNMANAGED PMH
|
||||
"status": "ACTIVE",
|
||||
"certainty": "CONFIRMED",
|
||||
"temporality": "CURRENT",
|
||||
"evidence": "Past medical history: hypertension for 5 years.",
|
||||
"reason": "Common condition.",
|
||||
"treated_or_managed": False,
|
||||
"monitored": False,
|
||||
"affected_clinical_management": False,
|
||||
"influenced_treatment": False,
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
agent = ContextAndRelevanceAgent(mock_llm)
|
||||
condition = ExtractedClinicalCondition(
|
||||
condition_id="htn-01",
|
||||
original_mention="hypertension",
|
||||
normalized_description="Essential hypertension",
|
||||
evidence_text="Past medical history: hypertension for 5 years.",
|
||||
evidence_location=EvidenceLocation(section="PAST_MEDICAL_HISTORY", page_number=1),
|
||||
section="PAST_MEDICAL_HISTORY",
|
||||
status=ConditionStatus.HISTORICAL,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.HISTORICAL,
|
||||
)
|
||||
|
||||
assessments = agent.assess_conditions(
|
||||
[condition], "Past medical history: hypertension for 5 years."
|
||||
)
|
||||
|
||||
assert len(assessments) == 1
|
||||
asm = assessments[0]
|
||||
# Guardrail must strictly set coding_candidate to False!
|
||||
assert asm.coding_candidate is False
|
||||
assert asm.current_relevance is False
|
||||
assert asm.status == ConditionStatus.HISTORICAL
|
||||
assert asm.temporality == Temporality.HISTORICAL
|
||||
|
||||
|
||||
def test_guardrail_overrides_llm_confirming_ruled_out_condition() -> None:
|
||||
"""Requirement: Even if LLM erroneously marks a ruled-out condition as confirmed, guardrail enforces RULED_OUT."""
|
||||
mock_llm = MagicMock()
|
||||
mock_llm.invoke.return_value = json.dumps(
|
||||
[
|
||||
{
|
||||
"diagnosis": "Pneumonia",
|
||||
"current_relevance": True,
|
||||
"coding_candidate": True,
|
||||
"status": "ACTIVE",
|
||||
"certainty": "CONFIRMED", # ERRONEOUS
|
||||
"evidence": "Chest CT showed clear lung fields; pneumonia ruled out.",
|
||||
"reason": "Evaluated during stay.",
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
agent = ContextAndRelevanceAgent(mock_llm)
|
||||
condition = ExtractedClinicalCondition(
|
||||
condition_id="pna-03",
|
||||
original_mention="pneumonia",
|
||||
normalized_description="Pneumonia",
|
||||
evidence_text="Chest CT showed clear lung fields; pneumonia ruled out.",
|
||||
evidence_location=EvidenceLocation(section="HOSPITAL_COURSE", page_number=1),
|
||||
section="HOSPITAL_COURSE",
|
||||
)
|
||||
|
||||
assessments = agent.assess_conditions(
|
||||
[condition], "Chest CT showed clear lung fields; pneumonia ruled out."
|
||||
)
|
||||
|
||||
assert len(assessments) == 1
|
||||
asm = assessments[0]
|
||||
assert asm.coding_candidate is False
|
||||
assert asm.current_relevance is False
|
||||
assert asm.certainty == Certainty.RULED_OUT
|
||||
assert asm.negation == NegationStatus.NEGATED
|
||||
|
||||
|
||||
def test_guardrail_preserves_suspected_certainty_when_llm_promotes_to_confirmed() -> None:
|
||||
"""Requirement: If extracted condition is SUSPECTED and LLM outputs CONFIRMED, guardrail restores SUSPECTED."""
|
||||
mock_llm = MagicMock()
|
||||
mock_llm.invoke.return_value = json.dumps(
|
||||
[
|
||||
{
|
||||
"diagnosis": "Aspiration pneumonia",
|
||||
"current_relevance": True,
|
||||
"coding_candidate": True,
|
||||
"status": "ACTIVE",
|
||||
"certainty": "CONFIRMED", # LLM erroneously promoted to confirmed
|
||||
"evidence": "Suspected aspiration pneumonia treated with empiric ampicillin-sulbactam.",
|
||||
"reason": "Treated with antibiotics.",
|
||||
"treated_or_managed": True,
|
||||
}
|
||||
]
|
||||
)
|
||||
|
||||
agent = ContextAndRelevanceAgent(mock_llm)
|
||||
condition = ExtractedClinicalCondition(
|
||||
condition_id="asp-pna-01",
|
||||
original_mention="suspected aspiration pneumonia",
|
||||
normalized_description="Aspiration pneumonia",
|
||||
evidence_text="Suspected aspiration pneumonia treated with empiric ampicillin-sulbactam.",
|
||||
evidence_location=EvidenceLocation(section="DISCHARGE_DIAGNOSES", page_number=1),
|
||||
section="DISCHARGE_DIAGNOSES",
|
||||
certainty=Certainty.SUSPECTED, # Originally suspected
|
||||
status=ConditionStatus.ACTIVE,
|
||||
treatment_evidence="treated with empiric ampicillin-sulbactam",
|
||||
)
|
||||
|
||||
assessments = agent.assess_conditions(
|
||||
[condition], "Suspected aspiration pneumonia treated with empiric ampicillin-sulbactam."
|
||||
)
|
||||
|
||||
assert len(assessments) == 1
|
||||
asm = assessments[0]
|
||||
assert asm.coding_candidate is True
|
||||
# Certainty must be preserved as SUSPECTED
|
||||
assert asm.certainty == Certainty.SUSPECTED
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# BaseAgent & LangGraph Node Compatibility Tests
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def test_base_agent_run_contract() -> None:
|
||||
"""Requirement: ContextAndRelevanceAgent conforms to BaseAgent interface and implements run()."""
|
||||
mock_llm = MagicMock()
|
||||
agent = ContextAndRelevanceAgent(mock_llm)
|
||||
|
||||
condition = ExtractedClinicalCondition(
|
||||
condition_id="chole-01",
|
||||
original_mention="acute cholecystitis",
|
||||
normalized_description="Acute cholecystitis",
|
||||
evidence_text="Laparoscopic cholecystectomy performed for acute cholecystitis.",
|
||||
evidence_location=EvidenceLocation(section="OPERATIVE_REPORT", page_number=1),
|
||||
section="OPERATIVE_REPORT",
|
||||
treatment_evidence="Laparoscopic cholecystectomy performed",
|
||||
)
|
||||
|
||||
results = agent.run(
|
||||
conditions=[condition],
|
||||
clinical_text="Laparoscopic cholecystectomy performed for acute cholecystitis.",
|
||||
)
|
||||
assert isinstance(results, list)
|
||||
assert len(results) == 1
|
||||
assert isinstance(results[0], ContextAssessment)
|
||||
assert results[0].coding_candidate is True
|
||||
|
||||
|
||||
def test_langgraph_run_node_execution() -> None:
|
||||
"""Requirement: Implement this as a LangChain component compatible with the LangGraph state."""
|
||||
mock_llm = MagicMock()
|
||||
agent = ContextAndRelevanceAgent(mock_llm)
|
||||
|
||||
condition = ExtractedClinicalCondition(
|
||||
condition_id="aki-01",
|
||||
original_mention="acute kidney injury",
|
||||
normalized_description="Acute kidney injury",
|
||||
evidence_text="Acute kidney injury secondary to dehydration, creatinine resolved with IV normal saline.",
|
||||
evidence_location=EvidenceLocation(section="HOSPITAL_COURSE", page_number=1),
|
||||
section="HOSPITAL_COURSE",
|
||||
treatment_evidence="resolved with IV normal saline",
|
||||
)
|
||||
|
||||
ambig_condition = ExtractedClinicalCondition(
|
||||
condition_id="ambig-01",
|
||||
original_mention="pulmonary embolism vs anxiety",
|
||||
normalized_description="Pulmonary embolism",
|
||||
evidence_text="Conflicting documentation regarding pulmonary embolism, CTA equivocal and unconfirmed.",
|
||||
evidence_location=EvidenceLocation(section="HOSPITAL_COURSE", page_number=2),
|
||||
section="HOSPITAL_COURSE",
|
||||
)
|
||||
|
||||
state: PipelineGraphState = {
|
||||
"raw_text": "Sample discharge text.",
|
||||
"extracted_conditions": [condition, ambig_condition],
|
||||
}
|
||||
|
||||
result_state = agent.run_node(state)
|
||||
|
||||
assert "context_assessments" in result_state
|
||||
assert "contextualized_diagnoses" in result_state
|
||||
assert "abstentions" in result_state
|
||||
assert result_state["current_stage"] == PipelineStage.CONTEXT_ANALYSIS
|
||||
|
||||
assessments = result_state["context_assessments"]
|
||||
assert len(assessments) == 2
|
||||
|
||||
aki_asm = next(a for a in assessments if a.diagnosis == "Acute kidney injury")
|
||||
assert aki_asm.coding_candidate is True
|
||||
assert aki_asm.current_relevance is True
|
||||
|
||||
pe_asm = next(a for a in assessments if a.diagnosis == "Pulmonary embolism")
|
||||
assert pe_asm.abstain_recommended is True
|
||||
assert pe_asm.coding_candidate is False
|
||||
|
||||
# Check abstention record in state
|
||||
abstentions = result_state["abstentions"]
|
||||
assert len(abstentions) == 1
|
||||
assert abstentions[0].diagnosis_id == "ambig-01"
|
||||
assert abstentions[0].reason == AbstentionReason.CONTRADICTORY_DOCUMENTATION
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_async_context_assessment() -> None:
|
||||
"""Test asynchronous execution of assess_conditions_async."""
|
||||
mock_llm = MagicMock()
|
||||
mock_llm.ainvoke = AsyncMock(
|
||||
return_value=json.dumps(
|
||||
[
|
||||
{
|
||||
"diagnosis": "Atrial fibrillation",
|
||||
"current_relevance": True,
|
||||
"coding_candidate": True,
|
||||
"status": "ACTIVE",
|
||||
"certainty": "CONFIRMED",
|
||||
"temporality": "CURRENT",
|
||||
"evidence": "Rapid ventricular response controlled with IV diltiazem.",
|
||||
"reason": "Treated with IV diltiazem during admission.",
|
||||
"treated_or_managed": True,
|
||||
"monitored": True,
|
||||
}
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
agent = ContextAndRelevanceAgent(mock_llm)
|
||||
condition = ExtractedClinicalCondition(
|
||||
condition_id="afib-01",
|
||||
original_mention="atrial fibrillation with RVR",
|
||||
normalized_description="Atrial fibrillation",
|
||||
evidence_text="Rapid ventricular response controlled with IV diltiazem.",
|
||||
evidence_location=EvidenceLocation(section="HOSPITAL_COURSE", page_number=1),
|
||||
section="HOSPITAL_COURSE",
|
||||
treatment_evidence="IV diltiazem",
|
||||
)
|
||||
|
||||
results = await agent.assess_conditions_async(
|
||||
[condition], "Rapid ventricular response controlled with IV diltiazem."
|
||||
)
|
||||
|
||||
assert len(results) == 1
|
||||
assert results[0].diagnosis == "Atrial fibrillation"
|
||||
assert results[0].coding_candidate is True
|
||||
assert results[0].treated_or_managed is True
|
||||
@@ -0,0 +1,266 @@
|
||||
"""Unit tests for SQLAlchemy database models, connection, and repository operations."""
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from medical_coding.database.models import Base
|
||||
from medical_coding.database.repository import MedicalCodingRepository
|
||||
from medical_coding.schemas.enums import (
|
||||
AbstentionReason,
|
||||
Acuity,
|
||||
Certainty,
|
||||
DiagnosisRole,
|
||||
ExecutionStatus,
|
||||
PipelineStage,
|
||||
)
|
||||
from medical_coding.schemas.response import CodedDiagnosisResponse, CodingResult
|
||||
from medical_coding.schemas.validation import AbstentionRecord
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repo(monkeypatch: pytest.MonkeyPatch, tmp_path: pytest.TempPathFactory) -> MedicalCodingRepository:
|
||||
"""Create an isolated SQLite database repository for testing."""
|
||||
test_db = tmp_path / "test_medical_coding.db"
|
||||
test_db_url = f"sqlite:///{test_db.as_posix()}"
|
||||
|
||||
# Override get_engine to use our temporary sqlite db
|
||||
test_engine = create_engine(test_db_url, connect_args={"check_same_thread": False})
|
||||
Base.metadata.create_all(bind=test_engine)
|
||||
test_session_factory = sessionmaker(bind=test_engine, expire_on_commit=False)
|
||||
|
||||
monkeypatch.setattr("medical_coding.database.connection._ENGINE", test_engine)
|
||||
monkeypatch.setattr("medical_coding.database.connection._SESSION_FACTORY", test_session_factory)
|
||||
|
||||
return MedicalCodingRepository()
|
||||
|
||||
|
||||
def test_save_and_retrieve_document(repo: MedicalCodingRepository) -> None:
|
||||
"""Test saving a full CodingResult with primary, secondary, and abstention records."""
|
||||
result = CodingResult(
|
||||
document_id="ENC-TEST-001",
|
||||
status=ExecutionStatus.SUCCESS,
|
||||
primary_diagnosis=CodedDiagnosisResponse(
|
||||
code="I50.21",
|
||||
description="Acute systolic heart failure",
|
||||
role=DiagnosisRole.PRIMARY,
|
||||
acuity=Acuity.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
evidence_quote="admitted with acute systolic heart failure",
|
||||
confidence_score=0.95,
|
||||
is_terminal_billable=True,
|
||||
),
|
||||
secondary_diagnoses=[
|
||||
CodedDiagnosisResponse(
|
||||
code="I10",
|
||||
description="Essential primary hypertension",
|
||||
role=DiagnosisRole.SECONDARY,
|
||||
acuity=Acuity.CHRONIC,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
evidence_quote="history of essential hypertension",
|
||||
confidence_score=0.88,
|
||||
is_terminal_billable=True,
|
||||
)
|
||||
],
|
||||
abstentions=[
|
||||
AbstentionRecord(
|
||||
raw_term="chest pain",
|
||||
reason=AbstentionReason.EXCLUDED_BY_NEGATION,
|
||||
detail="Patient explicitly denies chest pain.",
|
||||
stage=PipelineStage.CONTEXT_ANALYSIS,
|
||||
)
|
||||
],
|
||||
processing_time_ms=142.5,
|
||||
models_used={"llm": "mock", "retriever": "hybrid"},
|
||||
)
|
||||
|
||||
raw_text = "Patient was admitted with acute systolic heart failure. History of essential hypertension. Denies chest pain."
|
||||
saved = repo.save_coding_result(
|
||||
result=result,
|
||||
raw_text=raw_text,
|
||||
filename="discharge_summary.pdf",
|
||||
source_type="pdf",
|
||||
page_count=2,
|
||||
file_size_bytes=4096,
|
||||
metadata={"department": "Cardiology"},
|
||||
)
|
||||
|
||||
assert saved["document_id"] == "ENC-TEST-001"
|
||||
assert saved["status"] == "SUCCESS"
|
||||
assert saved["primary_code"] == "I50.21"
|
||||
assert saved["secondary_count"] == 1
|
||||
assert saved["abstention_count"] == 1
|
||||
assert saved["page_count"] == 2
|
||||
assert saved["metadata"]["department"] == "Cardiology"
|
||||
|
||||
# Query back by ID
|
||||
retrieved = repo.get_document_by_id("ENC-TEST-001")
|
||||
assert retrieved is not None
|
||||
assert retrieved["document_id"] == "ENC-TEST-001"
|
||||
assert len(retrieved["diagnoses"]) == 2
|
||||
assert len(retrieved["abstentions"]) == 1
|
||||
assert retrieved["diagnoses"][0]["code"] == "I50.21"
|
||||
assert retrieved["diagnoses"][0]["role"] == "PRIMARY"
|
||||
assert retrieved["diagnoses"][1]["code"] == "I10"
|
||||
assert retrieved["diagnoses"][1]["role"] == "SECONDARY"
|
||||
assert retrieved["abstentions"][0]["reason"] == "EXCLUDED_BY_NEGATION"
|
||||
|
||||
|
||||
def test_list_and_filter_documents(repo: MedicalCodingRepository) -> None:
|
||||
"""Test searching and filtering stored documents."""
|
||||
res1 = CodingResult(
|
||||
document_id="ENC-001",
|
||||
status=ExecutionStatus.SUCCESS,
|
||||
primary_diagnosis=CodedDiagnosisResponse(
|
||||
code="I50.21",
|
||||
description="Acute systolic heart failure",
|
||||
role=DiagnosisRole.PRIMARY,
|
||||
acuity=Acuity.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
evidence_quote="acute systolic heart failure",
|
||||
confidence_score=0.92,
|
||||
),
|
||||
processing_time_ms=100.0,
|
||||
)
|
||||
res2 = CodingResult(
|
||||
document_id="ENC-002",
|
||||
status=ExecutionStatus.PARTIAL_SUCCESS,
|
||||
primary_diagnosis=CodedDiagnosisResponse(
|
||||
code="E11.9",
|
||||
description="Type 2 diabetes mellitus",
|
||||
role=DiagnosisRole.PRIMARY,
|
||||
acuity=Acuity.CHRONIC,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
evidence_quote="type 2 diabetes",
|
||||
confidence_score=0.85,
|
||||
),
|
||||
processing_time_ms=80.0,
|
||||
)
|
||||
|
||||
repo.save_coding_result(res1, raw_text="Cardiology patient", filename="cardio.pdf")
|
||||
repo.save_coding_result(res2, raw_text="Endocrinology patient", filename="endo.pdf")
|
||||
|
||||
# List all
|
||||
all_docs = repo.list_documents()
|
||||
assert len(all_docs) == 2
|
||||
|
||||
# Filter by status
|
||||
success_docs = repo.list_documents(status="SUCCESS")
|
||||
assert len(success_docs) == 1
|
||||
assert success_docs[0]["document_id"] == "ENC-001"
|
||||
|
||||
# Filter by search term
|
||||
search_docs = repo.list_documents(search="Cardiology")
|
||||
assert len(search_docs) == 1
|
||||
assert search_docs[0]["document_id"] == "ENC-001"
|
||||
|
||||
# Filter by ICD code
|
||||
code_docs = repo.list_documents(code_filter="E11")
|
||||
assert len(code_docs) == 1
|
||||
assert code_docs[0]["document_id"] == "ENC-002"
|
||||
|
||||
|
||||
def test_analytics_summary(repo: MedicalCodingRepository) -> None:
|
||||
"""Test calculation of analytics aggregates and quality indicators."""
|
||||
res = CodingResult(
|
||||
document_id="ENC-ANALYTICS",
|
||||
status=ExecutionStatus.SUCCESS,
|
||||
primary_diagnosis=CodedDiagnosisResponse(
|
||||
code="I50.21",
|
||||
description="Acute systolic heart failure",
|
||||
role=DiagnosisRole.PRIMARY,
|
||||
acuity=Acuity.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
evidence_quote="heart failure",
|
||||
confidence_score=0.9,
|
||||
is_terminal_billable=True,
|
||||
),
|
||||
secondary_diagnoses=[
|
||||
CodedDiagnosisResponse(
|
||||
code="I10",
|
||||
description="Essential primary hypertension",
|
||||
role=DiagnosisRole.SECONDARY,
|
||||
acuity=Acuity.CHRONIC,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
evidence_quote="hypertension",
|
||||
confidence_score=0.9,
|
||||
is_terminal_billable=True,
|
||||
)
|
||||
],
|
||||
abstentions=[
|
||||
AbstentionRecord(
|
||||
raw_term="unspecified symptom",
|
||||
reason=AbstentionReason.BELOW_CONFIDENCE_THRESHOLD,
|
||||
detail="Low confidence",
|
||||
stage=PipelineStage.RANKING,
|
||||
)
|
||||
],
|
||||
processing_time_ms=120.0,
|
||||
)
|
||||
repo.save_coding_result(res, raw_text="Note content")
|
||||
|
||||
stats = repo.get_analytics_summary()
|
||||
assert stats["total_documents"] == 1
|
||||
assert stats["total_diagnoses"] == 2
|
||||
assert stats["billable_count"] == 2
|
||||
assert stats["billable_ratio_percent"] == 100.0
|
||||
assert stats["average_processing_time_ms"] == 120.0
|
||||
assert stats["status_breakdown"]["SUCCESS"] == 1
|
||||
assert len(stats["top_primary_codes"]) == 1
|
||||
assert stats["top_primary_codes"][0]["code"] == "I50.21"
|
||||
|
||||
|
||||
def test_delete_document_cascades(repo: MedicalCodingRepository) -> None:
|
||||
"""Test deleting a document cascades and deletes related diagnoses and abstentions."""
|
||||
res = CodingResult(
|
||||
document_id="ENC-DELETE",
|
||||
status=ExecutionStatus.SUCCESS,
|
||||
primary_diagnosis=CodedDiagnosisResponse(
|
||||
code="I50.21",
|
||||
description="Acute systolic heart failure",
|
||||
role=DiagnosisRole.PRIMARY,
|
||||
acuity=Acuity.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
evidence_quote="heart failure",
|
||||
confidence_score=0.9,
|
||||
),
|
||||
abstentions=[
|
||||
AbstentionRecord(
|
||||
raw_term="test",
|
||||
reason=AbstentionReason.EXCLUDED_BY_NEGATION,
|
||||
detail="test detail",
|
||||
stage=PipelineStage.CONTEXT_ANALYSIS,
|
||||
)
|
||||
],
|
||||
processing_time_ms=50.0,
|
||||
)
|
||||
repo.save_coding_result(res, raw_text="Content")
|
||||
|
||||
assert repo.get_document_by_id("ENC-DELETE") is not None
|
||||
deleted = repo.delete_document("ENC-DELETE")
|
||||
assert deleted is True
|
||||
assert repo.get_document_by_id("ENC-DELETE") is None
|
||||
|
||||
|
||||
def test_export_documents_df(repo: MedicalCodingRepository) -> None:
|
||||
"""Test exporting documents as a DataFrame."""
|
||||
res = CodingResult(
|
||||
document_id="ENC-DF",
|
||||
status=ExecutionStatus.SUCCESS,
|
||||
primary_diagnosis=CodedDiagnosisResponse(
|
||||
code="I50.21",
|
||||
description="Acute systolic heart failure",
|
||||
role=DiagnosisRole.PRIMARY,
|
||||
acuity=Acuity.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
evidence_quote="heart failure",
|
||||
confidence_score=0.9,
|
||||
),
|
||||
processing_time_ms=50.0,
|
||||
)
|
||||
repo.save_coding_result(res, raw_text="Content", filename="doc.pdf")
|
||||
|
||||
df = repo.get_documents_df()
|
||||
assert len(df) == 1
|
||||
assert df.iloc[0]["document_id"] == "ENC-DF"
|
||||
assert df.iloc[0]["primary_code"] == "I50.21"
|
||||
@@ -0,0 +1,349 @@
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pymupdf
|
||||
import pytest
|
||||
|
||||
from medical_coding.graph.pipeline import (
|
||||
process_clinical_document,
|
||||
)
|
||||
from medical_coding.graph.workflow import (
|
||||
export_graph_ascii,
|
||||
export_graph_mermaid,
|
||||
)
|
||||
from medical_coding.orchestration.pipeline import MedicalCodingPipeline
|
||||
from medical_coding.schemas.enums import (
|
||||
AbstentionReason,
|
||||
DiagnosisRole,
|
||||
ExecutionStatus,
|
||||
)
|
||||
from medical_coding.schemas.response import CodingResult
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_discharge_summary() -> str:
|
||||
"""Realistic discharge summary with primary, secondary, and historical conditions."""
|
||||
return """
|
||||
DISCHARGE SUMMARY
|
||||
Patient Name: John Doe
|
||||
MRN: 987654321
|
||||
Admission Date: 2026-09-15
|
||||
Discharge Date: 2026-09-20
|
||||
|
||||
CHIEF COMPLAINT:
|
||||
Acute shortness of breath and fluid overload.
|
||||
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Acute systolic heart failure - Patient admitted with acute exacerbation of systolic congestive heart failure. Transthoracic echocardiogram revealed left ventricular ejection fraction of 20% with severe diffuse hypokinesis. Treated with intravenous furosemide diuresis with 4 kg fluid loss and symptomatic resolution. Transitioned to oral lisinopril and carvedilol.
|
||||
2. Type 2 diabetes mellitus - Monitored daily fasting blood glucose; blood sugars remained controlled on home metformin 1000 mg twice daily.
|
||||
3. Essential primary hypertension - Blood pressure monitored on telemetry throughout admission; stable.
|
||||
|
||||
PAST MEDICAL HISTORY:
|
||||
1. Remote appendectomy in 2005.
|
||||
2. Resolved seasonal allergic rhinitis.
|
||||
|
||||
HOSPITAL COURSE:
|
||||
Patient presented to the emergency department in acute decompensated heart failure with bilateral lower extremity edema and pulmonary congestion. IV loop diuretics were administered with good response. Renal function was tracked and remained baseline. Patient was discharged in stable condition.
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_unsupported_specificity_summary() -> str:
|
||||
"""Discharge summary documenting only general condition without subtype specificity."""
|
||||
return """
|
||||
DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Fatigue and peripheral edema.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Heart failure. Patient was monitored on oral diuretic.
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_ruled_out_summary() -> str:
|
||||
"""Discharge summary containing explicitly ruled-out conditions."""
|
||||
return """
|
||||
DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Chest pressure.
|
||||
ASSESSMENT:
|
||||
1. Acute myocardial infarction definitively ruled out by serial negative troponins and normal ECG.
|
||||
2. Gastroesophageal reflux disease - managed with oral omeprazole with relief.
|
||||
"""
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 1. END-TO-END PIPELINE EXECUTION TEST
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_end_to_end_pipeline_success(sample_discharge_summary: str) -> None:
|
||||
"""Verify that a full clinical document executes across all 10 nodes to produce a verified CodingResult."""
|
||||
result: CodingResult = await process_clinical_document(
|
||||
source=sample_discharge_summary,
|
||||
document_id="doc-e2e-001",
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
assert result.status in (ExecutionStatus.SUCCESS, ExecutionStatus.PARTIAL_SUCCESS)
|
||||
|
||||
# 1. Guardrail 9: Maximum ONE Primary Diagnosis
|
||||
assert result.primary_diagnosis is not None
|
||||
assert result.primary_diagnosis.role == DiagnosisRole.PRIMARY
|
||||
assert result.primary_diagnosis.code == "I50.21"
|
||||
assert "Acute systolic heart failure" in result.primary_diagnosis.description
|
||||
assert result.primary_diagnosis.is_terminal_billable is True
|
||||
assert result.primary_diagnosis.evidence_quote != ""
|
||||
|
||||
# 2. Guardrails 3, 5: Secondary Diagnoses Active & Managed
|
||||
sec_codes = [s.code for s in result.secondary_diagnoses]
|
||||
for s in result.secondary_diagnoses:
|
||||
assert s.role == DiagnosisRole.SECONDARY
|
||||
assert s.is_terminal_billable is True
|
||||
assert s.evidence_quote != ""
|
||||
|
||||
# Either Diabetes E11.9 or Hypertension I10 are captured as valid active secondaries
|
||||
assert "E11.9" in sec_codes or "I10" in sec_codes
|
||||
|
||||
# 3. Guardrail 5: Historical appendectomy NOT coded as secondary
|
||||
assert not any("append" in s.description.lower() for s in result.secondary_diagnoses)
|
||||
|
||||
# 4. Internal Audit Trail Requirement
|
||||
audit_trail = result.metadata.get("audit_trail", [])
|
||||
assert len(audit_trail) >= 1
|
||||
sample_audit = audit_trail[0]
|
||||
assert "document_id" in sample_audit
|
||||
assert "evidence" in sample_audit
|
||||
assert "diagnosis_id" in sample_audit
|
||||
assert "context" in sample_audit
|
||||
assert "classification" in sample_audit
|
||||
assert "retrieved_candidates" in sample_audit
|
||||
assert "selected_candidate" in sample_audit
|
||||
assert "validation" in sample_audit
|
||||
assert "final_result" in sample_audit
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 2. PARALLELISM: ASYNCHRONOUS BATCH OF >= 10 DOCUMENTS
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_asynchronous_batch_processing_at_least_10_documents(
|
||||
sample_discharge_summary: str,
|
||||
) -> None:
|
||||
"""Verify that at least 10 documents are processed concurrently with bounded concurrency."""
|
||||
batch_size = 10
|
||||
documents = [
|
||||
{
|
||||
"document_id": f"batch-doc-{i:02d}",
|
||||
"text": f"{sample_discharge_summary}\nENCOUNTER ID: {i}",
|
||||
"metadata": {"doc_index": i},
|
||||
}
|
||||
for i in range(batch_size)
|
||||
]
|
||||
|
||||
pipeline = MedicalCodingPipeline()
|
||||
batch_status = await pipeline.run_batch_documents(documents, max_concurrency=10)
|
||||
|
||||
assert len(batch_status) == batch_size
|
||||
for i, res in enumerate(batch_status):
|
||||
assert res.document_id == f"batch-doc-{i:02d}"
|
||||
assert res.status in (ExecutionStatus.SUCCESS, ExecutionStatus.PARTIAL_SUCCESS)
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code == "I50.21"
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 3. GUARDRAILS: RULED OUT & HISTORICAL CONDITIONS
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_guardrail_ruled_out_cannot_be_coded_as_confirmed(
|
||||
sample_ruled_out_summary: str,
|
||||
) -> None:
|
||||
"""Guardrail 4: Ruled-out diagnoses must NEVER be coded as confirmed."""
|
||||
result = await process_clinical_document(
|
||||
source=sample_ruled_out_summary,
|
||||
document_id="doc-ruled-out",
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
# Myocardial infarction was explicitly ruled out; must NOT appear as primary or secondary
|
||||
coded_codes = [s.code for s in result.secondary_diagnoses]
|
||||
if result.primary_diagnosis:
|
||||
coded_codes.append(result.primary_diagnosis.code)
|
||||
|
||||
# I21 is myocardial infarction category
|
||||
assert not any(c.startswith("I21") for c in coded_codes)
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 4. GUARDRAILS: UNSUPPORTED SPECIFICITY
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_guardrail_unsupported_specificity_realigned_or_abstained(
|
||||
sample_unsupported_specificity_summary: str,
|
||||
) -> None:
|
||||
"""Guardrail 11: Documenting general condition cannot be forced into specific subtype."""
|
||||
result = await process_clinical_document(
|
||||
source=sample_unsupported_specificity_summary,
|
||||
document_id="doc-unsupported-spec",
|
||||
)
|
||||
|
||||
assert result is not None
|
||||
if result.primary_diagnosis:
|
||||
# If coded, must be general/unspecified code I50.9, NOT acute systolic I50.21!
|
||||
assert result.primary_diagnosis.code != "I50.21"
|
||||
assert result.primary_diagnosis.code in ("I50.9", "I50")
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 5. GUARDRAILS: MISSING / EMPTY EVIDENCE
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_guardrail_empty_input_clean_abstention() -> None:
|
||||
"""Guardrail 12: Empty or whitespace input cleanly abstains without unhandled exception."""
|
||||
result = await process_clinical_document(
|
||||
source="",
|
||||
document_id="doc-empty",
|
||||
)
|
||||
|
||||
assert result.status == ExecutionStatus.ABSTAINED
|
||||
assert result.primary_diagnosis is None
|
||||
assert len(result.secondary_diagnoses) == 0
|
||||
assert len(result.abstentions) >= 1
|
||||
assert result.abstentions[0].reason == AbstentionReason.INSUFFICIENT_CLINICAL_EVIDENCE
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 6. GRAPH VISUALIZATION & TOPOLOGY EXPORTS
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_graph_visualization_exports() -> None:
|
||||
"""Verify that graph topology exports to Mermaid and ASCII format without errors."""
|
||||
mermaid_def = export_graph_mermaid()
|
||||
assert "__start__" in mermaid_def or "START" in mermaid_def
|
||||
assert "validate_document" in mermaid_def
|
||||
assert "extract_text" in mermaid_def
|
||||
assert "extract_diagnoses" in mermaid_def
|
||||
assert "analyze_context" in mermaid_def
|
||||
assert "classify_diagnoses" in mermaid_def
|
||||
assert "retrieve_candidates" in mermaid_def
|
||||
assert "rank_candidates" in mermaid_def
|
||||
assert "validate_codes" in mermaid_def
|
||||
assert "evaluate_confidence" in mermaid_def
|
||||
assert "finalize_output" in mermaid_def
|
||||
assert "__end__" in mermaid_def or "END" in mermaid_def
|
||||
|
||||
ascii_def = export_graph_ascii()
|
||||
assert "START" in ascii_def
|
||||
assert "validate_document" in ascii_def
|
||||
assert "END" in ascii_def
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 7. DIAGNOSTIC FAILURE REPORTING FIXTURE
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def diagnostic_pipeline_harness():
|
||||
"""Harness running a variety of valid and deliberately broken inputs, producing a failure report."""
|
||||
|
||||
class DiagnosticHarness:
|
||||
async def evaluate_suite(self) -> dict[str, Any]:
|
||||
cases = [
|
||||
(
|
||||
"Valid Acute Systolic HF",
|
||||
"Patient admitted with acute systolic heart failure and fluid overload.",
|
||||
),
|
||||
(
|
||||
"Unspecified Heart Failure",
|
||||
"Patient has heart failure on maintenance oral diuretic.",
|
||||
),
|
||||
(
|
||||
"Ruled Out MI",
|
||||
"Patient had chest discomfort. Acute myocardial infarction was ruled out by negative troponins.",
|
||||
),
|
||||
("Empty Document", " "),
|
||||
(
|
||||
"Gibberish / No Clinical Content",
|
||||
"Hello world this is random text without medical findings.",
|
||||
),
|
||||
]
|
||||
report = []
|
||||
for name, text in cases:
|
||||
res = await process_clinical_document(text, document_id=f"diag-{name}")
|
||||
report.append(
|
||||
{
|
||||
"case_name": name,
|
||||
"status": str(res.status),
|
||||
"primary_code": res.primary_diagnosis.code
|
||||
if res.primary_diagnosis
|
||||
else None,
|
||||
"secondary_count": len(res.secondary_diagnoses),
|
||||
"abstention_count": len(res.abstentions),
|
||||
"abstention_reasons": [str(a.reason) for a in res.abstentions],
|
||||
}
|
||||
)
|
||||
return {"total_cases": len(cases), "cases": report}
|
||||
|
||||
return DiagnosticHarness()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_diagnostic_failure_report_execution(
|
||||
diagnostic_pipeline_harness: Any,
|
||||
) -> None:
|
||||
"""Execute diagnostic evaluation and assert that failure cases are properly captured."""
|
||||
report = await diagnostic_pipeline_harness.evaluate_suite()
|
||||
|
||||
assert report["total_cases"] == 5
|
||||
case_map = {c["case_name"]: c for c in report["cases"]}
|
||||
|
||||
# Valid HF should succeed with primary I50.21
|
||||
assert case_map["Valid Acute Systolic HF"]["status"] in ("SUCCESS", "PARTIAL_SUCCESS")
|
||||
assert case_map["Valid Acute Systolic HF"]["primary_code"] == "I50.21"
|
||||
|
||||
# Ruled Out MI must not code MI
|
||||
assert case_map["Ruled Out MI"]["primary_code"] != "I21.9"
|
||||
|
||||
# Empty document must abstain
|
||||
assert case_map["Empty Document"]["status"] == "ABSTAINED"
|
||||
assert case_map["Empty Document"]["abstention_count"] >= 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_end_to_end_pdf_extraction_and_coding(sample_discharge_summary: str) -> None:
|
||||
"""Verify that a raw PDF input is extracted and processed through all 10 LangGraph nodes."""
|
||||
doc = pymupdf.open()
|
||||
page = doc.new_page()
|
||||
page.insert_text((50, 72), sample_discharge_summary, fontsize=10)
|
||||
pdf_bytes = doc.write()
|
||||
doc.close()
|
||||
|
||||
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp:
|
||||
tmp_path = Path(tmp.name)
|
||||
tmp.write(pdf_bytes)
|
||||
|
||||
try:
|
||||
result = await process_clinical_document(
|
||||
source="",
|
||||
pdf_path=tmp_path,
|
||||
document_id="doc-pdf-e2e-001",
|
||||
)
|
||||
assert result is not None
|
||||
assert result.status in (ExecutionStatus.SUCCESS, ExecutionStatus.PARTIAL_SUCCESS)
|
||||
assert result.primary_diagnosis is not None
|
||||
assert result.primary_diagnosis.code == "I50.21"
|
||||
assert len(result.secondary_diagnoses) >= 1
|
||||
finally:
|
||||
if tmp_path.exists():
|
||||
tmp_path.unlink(missing_ok=True)
|
||||
@@ -0,0 +1,29 @@
|
||||
"""Unit tests for LangGraph workflow compilation and execution transitions."""
|
||||
|
||||
import pytest
|
||||
|
||||
from medical_coding.graph.state import create_initial_state
|
||||
from medical_coding.graph.workflow import create_coding_workflow, get_compiled_graph
|
||||
from medical_coding.schemas.enums import ExecutionStatus, PipelineStage
|
||||
|
||||
|
||||
def test_workflow_compilation() -> None:
|
||||
"""Verify that StateGraph compiles cleanly without dangling edges or schema mismatches."""
|
||||
workflow = create_coding_workflow()
|
||||
compiled = workflow.compile()
|
||||
assert compiled is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_graph_execution_empty_input_aborts_gracefully() -> None:
|
||||
"""Verify that an empty document input routes correctly and abstains."""
|
||||
graph = get_compiled_graph()
|
||||
initial_state = create_initial_state(document_id="empty-doc", raw_text="")
|
||||
|
||||
final_state = await graph.ainvoke(initial_state)
|
||||
|
||||
assert final_state["current_stage"] == PipelineStage.FINALIZATION
|
||||
assert final_state["is_aborted"] is True
|
||||
assert final_state["final_result"] is not None
|
||||
assert final_state["final_result"].status == ExecutionStatus.ABSTAINED
|
||||
assert len(final_state["abstentions"]) >= 1
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Import verification test checking all modules and detecting circular imports."""
|
||||
|
||||
import importlib
|
||||
import pkgutil
|
||||
|
||||
import medical_coding
|
||||
|
||||
|
||||
def test_import_all_submodules() -> None:
|
||||
"""Recursively import all submodules in medical_coding to guarantee no circular dependencies."""
|
||||
package = medical_coding
|
||||
prefix = package.__name__ + "."
|
||||
|
||||
for _, module_name, _ in pkgutil.walk_packages(package.__path__, prefix):
|
||||
mod = importlib.import_module(module_name)
|
||||
assert mod is not None
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Unit tests for multimodal document ingestion, auto-detection, and OCR parsing."""
|
||||
|
||||
import io
|
||||
|
||||
import pymupdf
|
||||
import pytest
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
from medical_coding.ingestion.agent import ClinicalDocumentIngestionAgent
|
||||
from medical_coding.ingestion.detector import DocumentFormat, DocumentFormatDetector
|
||||
from medical_coding.ingestion.parsers import (
|
||||
ImageOCRDocumentParser,
|
||||
ManualTextParser,
|
||||
PDFDocumentParser,
|
||||
TextDocumentParser,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ingestion_agent() -> ClinicalDocumentIngestionAgent:
|
||||
"""Fixture providing initialized ClinicalDocumentIngestionAgent."""
|
||||
return ClinicalDocumentIngestionAgent(max_pdf_pages=10)
|
||||
|
||||
|
||||
def test_detector_magic_bytes_and_extensions() -> None:
|
||||
"""Test format detection from binary magic bytes and file extensions."""
|
||||
# PDF detection
|
||||
pdf_header = b"%PDF-1.7\n%\xe2\xe3\xcf\xd3\n"
|
||||
fmt, mime = DocumentFormatDetector.detect_from_bytes(pdf_header, filename="test.pdf")
|
||||
assert fmt == DocumentFormat.PDF
|
||||
assert mime == "application/pdf"
|
||||
|
||||
# PNG detection
|
||||
png_header = b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR"
|
||||
fmt, mime = DocumentFormatDetector.detect_from_bytes(png_header)
|
||||
assert fmt == DocumentFormat.IMAGE
|
||||
assert mime == "image/png"
|
||||
|
||||
# JPEG detection
|
||||
jpeg_header = b"\xff\xd8\xff\xe0\x00\x10JFIF"
|
||||
fmt, mime = DocumentFormatDetector.detect_from_bytes(jpeg_header)
|
||||
assert fmt == DocumentFormat.IMAGE
|
||||
assert mime == "image/jpeg"
|
||||
|
||||
# Plain text detection
|
||||
txt_bytes = b"Patient admitted with acute chest pain."
|
||||
fmt, mime = DocumentFormatDetector.detect_from_bytes(txt_bytes, filename="notes.txt")
|
||||
assert fmt == DocumentFormat.TXT
|
||||
assert mime == "text/plain"
|
||||
|
||||
# Manual text string
|
||||
fmt, mime = DocumentFormatDetector.detect_format("Manual clinical note entry.\nNo history of asthma.")
|
||||
assert fmt == DocumentFormat.MANUAL_TEXT
|
||||
assert mime == "text/plain"
|
||||
|
||||
|
||||
def test_text_document_parser() -> None:
|
||||
"""Test TextDocumentParser handles UTF-8 bytes and plain text."""
|
||||
parser = TextDocumentParser()
|
||||
content = "DISCHARGE SUMMARY\nPatient has hypertension and diabetes."
|
||||
res = parser.parse(content.encode("utf-8"), filename="summary.txt")
|
||||
|
||||
assert res.format == DocumentFormat.TXT
|
||||
assert res.status == "SUCCESS"
|
||||
assert res.is_ocr is False
|
||||
assert "hypertension" in res.normalized_text
|
||||
assert res.word_count > 0
|
||||
|
||||
# Empty text
|
||||
empty_res = parser.parse(b" \n\t ", filename="empty.txt")
|
||||
assert empty_res.status == "EMPTY"
|
||||
|
||||
|
||||
def test_manual_text_parser() -> None:
|
||||
"""Test ManualTextParser cleans whitespace and parses raw text strings."""
|
||||
parser = ManualTextParser()
|
||||
raw = " Patient admitted with severe dyspnea. "
|
||||
res = parser.parse(raw)
|
||||
|
||||
assert res.format == DocumentFormat.MANUAL_TEXT
|
||||
assert res.status == "SUCCESS"
|
||||
assert res.normalized_text == "Patient admitted with severe dyspnea."
|
||||
|
||||
|
||||
def test_pdf_document_parser() -> None:
|
||||
"""Test PDFDocumentParser extracts text from PyMuPDF vector PDF."""
|
||||
parser = PDFDocumentParser(max_pages=5)
|
||||
|
||||
doc = pymupdf.open()
|
||||
page = doc.new_page()
|
||||
page.insert_text((50, 72), "DISCHARGE SUMMARY\nDiagnosis: Acute systolic heart failure.")
|
||||
pdf_bytes = doc.write()
|
||||
doc.close()
|
||||
|
||||
res = parser.parse(pdf_bytes, filename="discharge.pdf")
|
||||
assert res.format == DocumentFormat.PDF
|
||||
assert res.status == "SUCCESS"
|
||||
assert "heart failure" in res.normalized_text
|
||||
assert res.page_count == 1
|
||||
assert res.is_ocr is False
|
||||
|
||||
|
||||
def test_image_ocr_parser() -> None:
|
||||
"""Test ImageOCRDocumentParser executes OCR on synthetic image screenshot."""
|
||||
parser = ImageOCRDocumentParser()
|
||||
|
||||
# Generate synthetic screenshot with PIL
|
||||
img = Image.new("RGB", (600, 150), color=(255, 255, 255))
|
||||
draw = ImageDraw.Draw(img)
|
||||
draw.text((20, 40), "CLINICAL SUMMARY: Acute myocardial infarction anterior wall", fill=(0, 0, 0))
|
||||
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="PNG")
|
||||
png_bytes = buf.getvalue()
|
||||
|
||||
res = parser.parse(png_bytes, filename="screenshot.png")
|
||||
assert res.format == DocumentFormat.IMAGE
|
||||
assert res.status == "SUCCESS"
|
||||
assert res.is_ocr is True
|
||||
assert res.ocr_confidence is not None
|
||||
assert "myocardial" in res.normalized_text.lower() or "infarction" in res.normalized_text.lower()
|
||||
|
||||
|
||||
def test_agent_auto_detects_and_routes(ingestion_agent: ClinicalDocumentIngestionAgent) -> None:
|
||||
"""Test ClinicalDocumentIngestionAgent end-to-end routing across all four modalities."""
|
||||
# 1. Manual Text
|
||||
r1 = ingestion_agent.ingest("Patient presented with fever and cough.\nDiagnosed with community acquired pneumonia.")
|
||||
assert r1.format == DocumentFormat.MANUAL_TEXT
|
||||
assert r1.status == "SUCCESS"
|
||||
|
||||
# 2. Text File bytes
|
||||
txt_data = b"DISCHARGE NOTE\nEssential hypertension under control."
|
||||
r2 = ingestion_agent.ingest(txt_data, filename="encounter.txt")
|
||||
assert r2.format == DocumentFormat.TXT
|
||||
assert r2.status == "SUCCESS"
|
||||
assert "hypertension" in r2.normalized_text
|
||||
|
||||
# 3. PDF bytes
|
||||
doc = pymupdf.open()
|
||||
page = doc.new_page()
|
||||
page.insert_text((50, 72), "DISCHARGE SUMMARY\nDiagnosis: Acute systolic congestive heart failure.")
|
||||
pdf_bytes = doc.write()
|
||||
doc.close()
|
||||
r3 = ingestion_agent.ingest(pdf_bytes, filename="cardiology.pdf")
|
||||
assert r3.format == DocumentFormat.PDF
|
||||
assert r3.status == "SUCCESS"
|
||||
assert "heart failure" in r3.normalized_text
|
||||
|
||||
# 4. Image Screenshot bytes
|
||||
img = Image.new("RGB", (600, 120), color=(255, 255, 255))
|
||||
draw = ImageDraw.Draw(img)
|
||||
draw.text((20, 30), "DISCHARGE RECORD: Sepsis unspecified organism", fill=(0, 0, 0))
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="PNG")
|
||||
img_data = buf.getvalue()
|
||||
r4 = ingestion_agent.ingest(img_data, filename="chart_screenshot.png")
|
||||
assert r4.format == DocumentFormat.IMAGE
|
||||
assert r4.status == "SUCCESS"
|
||||
assert r4.is_ocr is True
|
||||
assert "sepsis" in r4.normalized_text.lower()
|
||||
@@ -0,0 +1,225 @@
|
||||
"""Unit and integration tests for local GPT4All LLM infrastructure."""
|
||||
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from medical_coding.config.settings import Settings
|
||||
from medical_coding.models.exceptions import LLMInitializationError
|
||||
from medical_coding.models.factory import ModelFactory
|
||||
from medical_coding.models.gpt4all_wrapper import GPT4AllWrapper
|
||||
from medical_coding.models.langchain_llm import LocalGPT4AllLangChainLLM
|
||||
from medical_coding.models.lifecycle import (
|
||||
LLMLifecycleManager,
|
||||
check_llm_health,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_lifecycle_manager() -> None:
|
||||
"""Ensure singleton manager is fresh before and after each test."""
|
||||
LLMLifecycleManager.reset_instance()
|
||||
yield
|
||||
LLMLifecycleManager.reset_instance()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_gpt4all_env(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> dict:
|
||||
"""Fixture providing a mock GPT4All backend with a dummy GGUF weight file."""
|
||||
model_file = tmp_path / "test-model.gguf"
|
||||
model_file.write_bytes(b"GGUF_TEST_HEADER_BYTES_1234567890")
|
||||
|
||||
mock_backend = MagicMock()
|
||||
mock_backend.generate.return_value = "Trivial clinical test response."
|
||||
|
||||
mock_class = MagicMock(return_value=mock_backend)
|
||||
monkeypatch.setattr("medical_coding.models.gpt4all_wrapper.GPT4All", mock_class)
|
||||
|
||||
test_settings = Settings(
|
||||
model_name=model_file.name,
|
||||
model_path=tmp_path,
|
||||
model_temperature=0.0,
|
||||
model_max_tokens=256,
|
||||
model_threads=4,
|
||||
model_context_size=1024,
|
||||
max_document_concurrency=10,
|
||||
max_llm_concurrency=1,
|
||||
llm_timeout_seconds=30.0,
|
||||
)
|
||||
|
||||
return {
|
||||
"model_file": model_file,
|
||||
"mock_class": mock_class,
|
||||
"mock_backend": mock_backend,
|
||||
"settings": test_settings,
|
||||
}
|
||||
|
||||
|
||||
def test_configuration_loads_model_and_concurrency_settings(
|
||||
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
||||
) -> None:
|
||||
"""Test 1: Verify all required MODEL_* and CONCURRENCY configuration parameters load from environment."""
|
||||
monkeypatch.setenv("MODEL_NAME", "custom_model.gguf")
|
||||
monkeypatch.setenv("MODEL_PATH", str(tmp_path))
|
||||
monkeypatch.setenv("MODEL_TEMPERATURE", "0.2")
|
||||
monkeypatch.setenv("MODEL_MAX_TOKENS", "512")
|
||||
monkeypatch.setenv("MODEL_THREADS", "8")
|
||||
monkeypatch.setenv("MODEL_CONTEXT_SIZE", "4096")
|
||||
monkeypatch.setenv("MAX_DOCUMENT_CONCURRENCY", "12")
|
||||
monkeypatch.setenv("MAX_LLM_CONCURRENCY", "2")
|
||||
|
||||
cfg = Settings()
|
||||
assert cfg.model_name == "custom_model.gguf"
|
||||
assert cfg.model_path == tmp_path
|
||||
assert cfg.model_temperature == 0.2
|
||||
assert cfg.model_max_tokens == 512
|
||||
assert cfg.model_threads == 8
|
||||
assert cfg.model_context_size == 4096
|
||||
assert cfg.max_document_concurrency == 12
|
||||
assert cfg.max_llm_concurrency == 2
|
||||
assert cfg.get_resolved_model_path() == tmp_path / "custom_model.gguf"
|
||||
|
||||
|
||||
def test_model_can_be_initialized_offline(mock_gpt4all_env: dict) -> None:
|
||||
"""Test 2: Verify model can be initialized offline with allow_download=False."""
|
||||
settings = mock_gpt4all_env["settings"]
|
||||
mock_class = mock_gpt4all_env["mock_class"]
|
||||
|
||||
wrapper = GPT4AllWrapper(
|
||||
model_name=settings.model_name,
|
||||
model_path=settings.model_path,
|
||||
n_threads=settings.model_threads,
|
||||
n_ctx=settings.model_context_size,
|
||||
)
|
||||
|
||||
assert wrapper.is_weight_file_present() is True
|
||||
assert wrapper.get_file_size_bytes() > 0
|
||||
|
||||
wrapper.load()
|
||||
assert wrapper._model is not None
|
||||
|
||||
# Verify allow_download was strictly False
|
||||
mock_class.assert_called_once()
|
||||
_, kwargs = mock_class.call_args
|
||||
assert kwargs.get("allow_download") is False
|
||||
assert kwargs.get("device") == "cpu"
|
||||
assert kwargs.get("n_threads") == 4
|
||||
assert kwargs.get("n_ctx") == 1024
|
||||
|
||||
|
||||
def test_model_can_produce_trivial_response_sync_and_async(mock_gpt4all_env: dict) -> None:
|
||||
"""Test 3: Verify model can produce a trivial response synchronously and asynchronously."""
|
||||
settings = mock_gpt4all_env["settings"]
|
||||
manager = LLMLifecycleManager.get_instance(settings=settings)
|
||||
|
||||
# Synchronous test
|
||||
sync_resp = manager.generate_sync("Ping")
|
||||
assert sync_resp == "Trivial clinical test response."
|
||||
|
||||
# Asynchronous test
|
||||
async def run_async() -> str:
|
||||
return await manager.generate_async("Ping async")
|
||||
|
||||
async_resp = asyncio.run(run_async())
|
||||
assert async_resp == "Trivial clinical test response."
|
||||
assert manager.check_health().inference_count == 2
|
||||
|
||||
|
||||
def test_model_is_not_reloaded_unnecessarily(mock_gpt4all_env: dict) -> None:
|
||||
"""Test 4: Verify model is loaded once and reused across multiple sequential and parallel calls."""
|
||||
settings = mock_gpt4all_env["settings"]
|
||||
mock_class = mock_gpt4all_env["mock_class"]
|
||||
manager = LLMLifecycleManager.get_instance(settings=settings)
|
||||
|
||||
# Execute 5 inferences
|
||||
for i in range(5):
|
||||
resp = manager.generate_sync(f"Query {i}")
|
||||
assert resp == "Trivial clinical test response."
|
||||
|
||||
# Crucial assertion: Model was initialized exactly once
|
||||
assert mock_class.call_count == 1
|
||||
assert manager.check_health().load_count == 1
|
||||
assert manager.check_health().inference_count == 5
|
||||
|
||||
|
||||
def test_langchain_interface_invoke_and_ainvoke(mock_gpt4all_env: dict) -> None:
|
||||
"""Verify LangChain-compatible LocalGPT4AllLangChainLLM interface works with invoke and ainvoke."""
|
||||
settings = mock_gpt4all_env["settings"]
|
||||
llm = LocalGPT4AllLangChainLLM(settings=settings)
|
||||
|
||||
assert llm._llm_type == "gpt4all_local"
|
||||
|
||||
# Synchronous LangChain invoke
|
||||
output = llm.invoke("Identify diagnosis")
|
||||
assert output == "Trivial clinical test response."
|
||||
|
||||
# Asynchronous LangChain ainvoke
|
||||
async def run_langchain_async() -> str:
|
||||
return await llm.ainvoke("Identify diagnosis async")
|
||||
|
||||
async_output = asyncio.run(run_langchain_async())
|
||||
assert async_output == "Trivial clinical test response."
|
||||
|
||||
|
||||
def test_controlled_concurrency_handles_multiple_concurrent_requests(
|
||||
mock_gpt4all_env: dict,
|
||||
) -> None:
|
||||
"""Verify that multiple concurrent async calls (e.g. 10 PDFs) are handled safely under MAX_LLM_CONCURRENCY."""
|
||||
settings = mock_gpt4all_env["settings"]
|
||||
manager = LLMLifecycleManager.get_instance(settings=settings)
|
||||
|
||||
async def execute_batch() -> list[str]:
|
||||
# Launch 10 simultaneous async calls simulating 10 PDFs requesting LLM inference
|
||||
tasks = [manager.generate_async(f"PDF doc #{i}") for i in range(10)]
|
||||
return await asyncio.gather(*tasks)
|
||||
|
||||
results = asyncio.run(execute_batch())
|
||||
assert len(results) == 10
|
||||
assert all(r == "Trivial clinical test response." for r in results)
|
||||
assert manager.check_health().inference_count == 10
|
||||
# Model should still only have been loaded once!
|
||||
assert manager.check_health().load_count == 1
|
||||
|
||||
|
||||
def test_health_check_reports_accurate_state(mock_gpt4all_env: dict) -> None:
|
||||
"""Verify health check diagnostics before and after loading."""
|
||||
settings = mock_gpt4all_env["settings"]
|
||||
report = check_llm_health(settings=settings)
|
||||
|
||||
assert report.file_exists is True
|
||||
assert report.status == "healthy"
|
||||
assert report.max_document_concurrency == 10
|
||||
assert report.max_llm_concurrency == 1
|
||||
assert report.configured_threads == 4
|
||||
|
||||
|
||||
def test_missing_weight_file_raises_initialization_error(tmp_path: Path) -> None:
|
||||
"""Verify that attempting to load a non-existent model raises an informative offline error."""
|
||||
settings = Settings(
|
||||
model_name="nonexistent.gguf",
|
||||
model_path=tmp_path,
|
||||
)
|
||||
wrapper = GPT4AllWrapper(
|
||||
model_name=settings.model_name,
|
||||
model_path=settings.model_path,
|
||||
)
|
||||
|
||||
assert wrapper.is_weight_file_present() is False
|
||||
with pytest.raises(LLMInitializationError, match="Per offline architectural constraints"):
|
||||
wrapper.load()
|
||||
|
||||
|
||||
def test_model_factory_methods(mock_gpt4all_env: dict) -> None:
|
||||
"""Verify that ModelFactory factory methods correctly instantiate components."""
|
||||
settings = mock_gpt4all_env["settings"]
|
||||
base_llm = ModelFactory.create_llm(settings=settings)
|
||||
langchain_llm = ModelFactory.create_langchain_llm(settings=settings)
|
||||
manager = ModelFactory.get_llm_manager(settings=settings)
|
||||
health = ModelFactory.check_llm_health(settings=settings)
|
||||
|
||||
assert base_llm is not None
|
||||
assert langchain_llm is not None
|
||||
assert manager is not None
|
||||
assert health.status == "healthy"
|
||||
@@ -0,0 +1,202 @@
|
||||
"""End-to-end integration test verifying all four input modalities with auto-detection, parsing, coding pipeline, and DB persistence."""
|
||||
|
||||
import asyncio
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from medical_coding.database.connection import init_db
|
||||
from medical_coding.database.repository import MedicalCodingRepository
|
||||
from medical_coding.ingestion.agent import ClinicalDocumentIngestionAgent
|
||||
from medical_coding.ingestion.detector import DocumentFormat
|
||||
from medical_coding.orchestration.pipeline import MedicalCodingPipeline
|
||||
from medical_coding.schemas.enums import ExecutionStatus
|
||||
from medical_coding.ui.sample_data import (
|
||||
CLINICAL_CASES,
|
||||
generate_sample_image,
|
||||
generate_sample_pdf,
|
||||
generate_sample_txt,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def pipeline():
|
||||
return MedicalCodingPipeline()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def repo():
|
||||
init_db()
|
||||
return MedicalCodingRepository()
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def ingestion_agent():
|
||||
return ClinicalDocumentIngestionAgent(max_pdf_pages=10)
|
||||
|
||||
|
||||
def test_modality_1_pdf_end_to_end(pipeline, repo, ingestion_agent):
|
||||
case = CLINICAL_CASES["Case 1: Decompensated Heart Failure & Comorbidities"]
|
||||
pdf_bytes = generate_sample_pdf(case["title"], case["text"])
|
||||
doc_id = f"TEST-PDF-{uuid4().hex[:6].upper()}"
|
||||
|
||||
# 1. Ingestion auto-detection & parsing
|
||||
ingest_res = ingestion_agent.ingest(source=pdf_bytes, filename="discharge_note.pdf")
|
||||
assert ingest_res.format == DocumentFormat.PDF
|
||||
assert ingest_res.status == "SUCCESS"
|
||||
assert "heart failure" in ingest_res.normalized_text.lower()
|
||||
assert ingest_res.page_count >= 1
|
||||
|
||||
# 2. Pipeline execution
|
||||
coding_res = asyncio.run(
|
||||
pipeline.run_document(
|
||||
document_id=doc_id,
|
||||
text=ingest_res.normalized_text,
|
||||
file_bytes=pdf_bytes,
|
||||
metadata={"filename": "discharge_note.pdf", "source_type": "pdf"},
|
||||
)
|
||||
)
|
||||
assert coding_res.status in (ExecutionStatus.SUCCESS, ExecutionStatus.PARTIAL_SUCCESS)
|
||||
all_diags = ([coding_res.primary_diagnosis] if coding_res.primary_diagnosis else []) + coding_res.secondary_diagnoses
|
||||
all_codes = [d.code for d in all_diags]
|
||||
assert "I50.21" in all_codes
|
||||
|
||||
# 3. DB Persistence
|
||||
saved = repo.save_coding_result(
|
||||
result=coding_res,
|
||||
raw_text=ingest_res.normalized_text,
|
||||
filename="discharge_note.pdf",
|
||||
source_type="pdf",
|
||||
page_count=ingest_res.page_count,
|
||||
file_size_bytes=len(pdf_bytes),
|
||||
)
|
||||
assert saved["id"] > 0
|
||||
assert saved["document_id"] == doc_id
|
||||
assert saved["source_type"] == "pdf"
|
||||
|
||||
|
||||
def test_modality_2_plain_text_end_to_end(pipeline, repo, ingestion_agent):
|
||||
case = CLINICAL_CASES["Case 4: Severe Sepsis & Acute Kidney Injury"]
|
||||
txt_bytes = generate_sample_txt(case["title"], case["text"])
|
||||
doc_id = f"TEST-TXT-{uuid4().hex[:6].upper()}"
|
||||
|
||||
# 1. Ingestion auto-detection & parsing
|
||||
ingest_res = ingestion_agent.ingest(source=txt_bytes, filename="sepsis_summary.txt")
|
||||
assert ingest_res.format == DocumentFormat.TXT
|
||||
assert ingest_res.status == "SUCCESS"
|
||||
assert "sepsis" in ingest_res.normalized_text.lower()
|
||||
|
||||
# 2. Pipeline execution
|
||||
coding_res = asyncio.run(
|
||||
pipeline.run_document(
|
||||
document_id=doc_id,
|
||||
text=ingest_res.normalized_text,
|
||||
file_bytes=txt_bytes,
|
||||
metadata={"filename": "sepsis_summary.txt", "source_type": "txt"},
|
||||
)
|
||||
)
|
||||
assert coding_res.status in (ExecutionStatus.SUCCESS, ExecutionStatus.PARTIAL_SUCCESS, ExecutionStatus.ABSTAINED)
|
||||
all_diags = ([coding_res.primary_diagnosis] if coding_res.primary_diagnosis else []) + coding_res.secondary_diagnoses
|
||||
assert len(all_diags) > 0 or len(coding_res.abstentions) > 0
|
||||
|
||||
# 3. DB Persistence
|
||||
saved = repo.save_coding_result(
|
||||
result=coding_res,
|
||||
raw_text=ingest_res.normalized_text,
|
||||
filename="sepsis_summary.txt",
|
||||
source_type="txt",
|
||||
page_count=1,
|
||||
file_size_bytes=len(txt_bytes),
|
||||
)
|
||||
assert saved["id"] > 0
|
||||
assert saved["document_id"] == doc_id
|
||||
assert saved["source_type"] == "txt"
|
||||
|
||||
|
||||
def test_modality_3_image_screenshot_ocr_end_to_end(pipeline, repo, ingestion_agent):
|
||||
case = CLINICAL_CASES["Case 2: Acute COPD Exacerbation with Pneumonia"]
|
||||
img_bytes = generate_sample_image(case["title"], case["text"])
|
||||
doc_id = f"TEST-IMG-{uuid4().hex[:6].upper()}"
|
||||
|
||||
# 1. Ingestion auto-detection & RapidOCR parsing
|
||||
ingest_res = ingestion_agent.ingest(source=img_bytes, filename="copd_screenshot.png")
|
||||
assert ingest_res.format == DocumentFormat.IMAGE
|
||||
assert ingest_res.status == "SUCCESS"
|
||||
assert ingest_res.is_ocr is True
|
||||
assert ingest_res.ocr_confidence is not None
|
||||
assert ingest_res.ocr_confidence > 0.60
|
||||
assert "copd" in ingest_res.normalized_text.lower() or "chronic obstructive" in ingest_res.normalized_text.lower()
|
||||
|
||||
# 2. Pipeline execution
|
||||
coding_res = asyncio.run(
|
||||
pipeline.run_document(
|
||||
document_id=doc_id,
|
||||
text=ingest_res.normalized_text,
|
||||
file_bytes=img_bytes,
|
||||
metadata={"filename": "copd_screenshot.png", "source_type": "image"},
|
||||
)
|
||||
)
|
||||
assert coding_res is not None
|
||||
|
||||
# 3. DB Persistence
|
||||
saved = repo.save_coding_result(
|
||||
result=coding_res,
|
||||
raw_text=ingest_res.normalized_text,
|
||||
filename="copd_screenshot.png",
|
||||
source_type="image",
|
||||
page_count=1,
|
||||
file_size_bytes=len(img_bytes),
|
||||
)
|
||||
assert saved["id"] > 0
|
||||
assert saved["document_id"] == doc_id
|
||||
assert saved["source_type"] == "image"
|
||||
|
||||
|
||||
def test_modality_4_manual_text_end_to_end(pipeline, repo, ingestion_agent):
|
||||
clinical_notes = """HOSPITAL DISCHARGE SUMMARY
|
||||
PATIENT ENCOUNTER: ENC-MANUAL-001
|
||||
|
||||
CHIEF COMPLAINT:
|
||||
Severe shortness of breath on exertion and progressive 3-pillow orthopnea.
|
||||
|
||||
HISTORY OF PRESENT ILLNESS:
|
||||
The patient is a 72-year-old male who presented with acute exertional dyspnea and bilateral lower extremity edema. Echocardiogram demonstrated severe systolic dysfunction with left ventricular ejection fraction 25%.
|
||||
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Acute systolic heart failure (decompensated congestive heart failure with systolic dysfunction).
|
||||
2. Essential primary hypertension.
|
||||
"""
|
||||
doc_id = f"TEST-MAN-{uuid4().hex[:6].upper()}"
|
||||
|
||||
# 1. Ingestion auto-detection & parsing
|
||||
ingest_res = ingestion_agent.ingest(source=clinical_notes, filename="manual_entry.txt")
|
||||
assert ingest_res.format == DocumentFormat.MANUAL_TEXT
|
||||
assert ingest_res.status == "SUCCESS"
|
||||
assert ingest_res.is_ocr is False
|
||||
assert "systolic heart failure" in ingest_res.normalized_text.lower()
|
||||
|
||||
# 2. Pipeline execution
|
||||
coding_res = asyncio.run(
|
||||
pipeline.run_document(
|
||||
document_id=doc_id,
|
||||
text=ingest_res.normalized_text,
|
||||
metadata={"filename": "manual_entry.txt", "source_type": "manual_text"},
|
||||
)
|
||||
)
|
||||
assert coding_res.status in (ExecutionStatus.SUCCESS, ExecutionStatus.PARTIAL_SUCCESS)
|
||||
all_diags = ([coding_res.primary_diagnosis] if coding_res.primary_diagnosis else []) + coding_res.secondary_diagnoses
|
||||
all_codes = [d.code for d in all_diags]
|
||||
assert "I50.21" in all_codes
|
||||
|
||||
# 3. DB Persistence
|
||||
saved = repo.save_coding_result(
|
||||
result=coding_res,
|
||||
raw_text=ingest_res.normalized_text,
|
||||
filename="manual_entry.txt",
|
||||
source_type="manual_text",
|
||||
page_count=1,
|
||||
file_size_bytes=len(clinical_notes.encode("utf-8")),
|
||||
)
|
||||
assert saved["id"] > 0
|
||||
assert saved["document_id"] == doc_id
|
||||
assert saved["source_type"] == "manual_text"
|
||||
@@ -0,0 +1,332 @@
|
||||
"""Unit and integration tests for PDF extraction, normalization, section detection, and batch concurrency."""
|
||||
|
||||
import io
|
||||
from pathlib import Path
|
||||
|
||||
import PIL.Image
|
||||
import pymupdf
|
||||
import pytest
|
||||
|
||||
from medical_coding.pdf.extractor import PDFExtractor
|
||||
from medical_coding.pdf.models import PDFExtractionStatus
|
||||
from medical_coding.pdf.normalizer import DocumentNormalizer
|
||||
from medical_coding.pdf.processor import (
|
||||
BatchPDFProcessor,
|
||||
process_document,
|
||||
process_documents_batch,
|
||||
)
|
||||
from medical_coding.pdf.section_detector import SectionDetector
|
||||
|
||||
|
||||
def generate_sample_clinical_pdf(
|
||||
patient_name: str = "DOE, JOHN",
|
||||
diagnoses: list[str] | None = None,
|
||||
num_pages: int = 1,
|
||||
) -> bytes:
|
||||
"""Generate a clean synthetic clinical discharge summary PDF in memory using PyMuPDF."""
|
||||
doc = pymupdf.open()
|
||||
diag_list = diagnoses or [
|
||||
"1. Acute systolic (congestive) heart failure (I50.21)",
|
||||
"2. Type 2 diabetes mellitus without complications (E11.9)",
|
||||
"3. Essential hypertension (I10)",
|
||||
]
|
||||
diag_text = "\n".join(diag_list)
|
||||
|
||||
page1_text = f"""DISCHARGE SUMMARY
|
||||
|
||||
PATIENT NAME: {patient_name}
|
||||
MRN: 987654321
|
||||
ADMISSION DATE: 2026-09-20
|
||||
DISCHARGE DATE: 2026-09-28
|
||||
|
||||
DISCHARGE DIAGNOSES:
|
||||
{diag_text}
|
||||
|
||||
HISTORY OF PRESENT ILLNESS:
|
||||
The patient is a 68-year-old male who presented with severe progressive dyspnea on exertion,
|
||||
orthopnea, and 3+ bilateral lower extremity edema over the past 5 days.
|
||||
|
||||
HOSPITAL COURSE:
|
||||
Patient was admitted to cardiology service and promptly initiated on intravenous furosemide diuresis.
|
||||
Echocardiogram revealed severely depressed left ventricular ejection fraction of 25%.
|
||||
Patient experienced significant clinical improvement with 4 kg fluid loss.
|
||||
|
||||
PAST MEDICAL HISTORY:
|
||||
1. Longstanding hypertension.
|
||||
2. Type 2 diabetes mellitus diagnosed 10 years ago.
|
||||
3. No prior history of myocardial infarction.
|
||||
"""
|
||||
|
||||
page = doc.new_page()
|
||||
page.insert_text((40, 50), page1_text, fontsize=10)
|
||||
|
||||
for p in range(1, num_pages):
|
||||
extra_page = doc.new_page()
|
||||
extra_page.insert_text(
|
||||
(40, 50),
|
||||
f"DISCHARGE MEDICATIONS (Page {p + 1}):\n1. Furosemide 40 mg daily\n2. Lisinopril 10 mg daily\n3. Metformin 500 mg BID\n\nDISCHARGE INSTRUCTIONS:\nFollow up with cardiology clinic in 2 weeks.",
|
||||
fontsize=10,
|
||||
)
|
||||
|
||||
pdf_bytes = doc.tobytes()
|
||||
doc.close()
|
||||
return pdf_bytes
|
||||
|
||||
|
||||
def generate_scanned_image_pdf() -> bytes:
|
||||
"""Generate an image-only PDF containing raster pixels and minimal/no text."""
|
||||
doc = pymupdf.open()
|
||||
page = doc.new_page()
|
||||
|
||||
# Create dummy raster image
|
||||
img = PIL.Image.new("RGB", (200, 200), color="blue")
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="PNG")
|
||||
|
||||
page.insert_image(pymupdf.Rect(50, 50, 400, 400), stream=buf.getvalue())
|
||||
# Add minimal header text (below 20 chars)
|
||||
page.insert_text((20, 20), "Scan", fontsize=8)
|
||||
|
||||
pdf_bytes = doc.tobytes()
|
||||
doc.close()
|
||||
return pdf_bytes
|
||||
|
||||
|
||||
def generate_insufficient_text_pdf() -> bytes:
|
||||
"""Generate a PDF with under 50 characters of total text."""
|
||||
doc = pymupdf.open()
|
||||
page = doc.new_page()
|
||||
page.insert_text((50, 50), "Short note.", fontsize=10)
|
||||
pdf_bytes = doc.tobytes()
|
||||
doc.close()
|
||||
return pdf_bytes
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Tests: Normalization and Section Detection
|
||||
# ============================================================================
|
||||
|
||||
|
||||
def test_whitespace_normalization() -> None:
|
||||
"""Verify whitespace normalizer cleans control chars, de-hyphenates, and preserves paragraphs."""
|
||||
normalizer = DocumentNormalizer()
|
||||
raw = "Patient with hyper-\n tension and dysp-\nnea.\x00\x08\n\n\n\nPlan:\n1. Diuresis"
|
||||
normalized = normalizer.normalize(raw)
|
||||
|
||||
assert "hypertension" in normalized
|
||||
assert "dyspnea" in normalized
|
||||
assert "\x00" not in normalized
|
||||
assert "\x08" not in normalized
|
||||
# Max two consecutive newlines between paragraphs
|
||||
assert "\n\n\n" not in normalized
|
||||
assert "Plan:\n1. Diuresis" in normalized
|
||||
|
||||
|
||||
def test_section_detector_identifies_clinical_boundaries() -> None:
|
||||
"""Verify SectionDetector detects headers, sets offsets, and flags high-yield coding sections."""
|
||||
detector = SectionDetector()
|
||||
text = """PATIENT HEADER: John Doe MRN 123
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Acute systolic heart failure
|
||||
2. Essential hypertension
|
||||
|
||||
HOSPITAL COURSE:
|
||||
Patient received diuresis and improved clinically.
|
||||
|
||||
DISCHARGE MEDICATIONS:
|
||||
1. Furosemide 40mg
|
||||
"""
|
||||
sections = detector.detect_sections(text)
|
||||
assert len(sections) >= 3
|
||||
|
||||
types = [s.section_type for s in sections]
|
||||
assert "DISCHARGE_DIAGNOSES" in types
|
||||
assert "HOSPITAL_COURSE" in types
|
||||
assert "MEDICATIONS" in types
|
||||
|
||||
# Check high-yield flags
|
||||
diag_sec = next(s for s in sections if s.section_type == "DISCHARGE_DIAGNOSES")
|
||||
assert diag_sec.is_high_yield_coding is True
|
||||
assert "Acute systolic heart failure" in diag_sec.content_text
|
||||
|
||||
med_sec = next(s for s in sections if s.section_type == "MEDICATIONS")
|
||||
assert med_sec.is_high_yield_coding is False
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Tests: Single and Batch PDF Processing
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_process_single_pdf_success() -> None:
|
||||
"""Verify processing a single valid PDF into a structured ClinicalPDFDocument."""
|
||||
pdf_bytes = generate_sample_clinical_pdf(patient_name="SMITH, JANE", num_pages=2)
|
||||
result = await process_document(pdf_source=pdf_bytes, filename="jane_smith.pdf")
|
||||
|
||||
assert result.status == PDFExtractionStatus.SUCCESS
|
||||
assert result.document is not None
|
||||
assert result.page_count == 2
|
||||
assert result.char_count > 100
|
||||
assert result.needs_ocr is False
|
||||
|
||||
doc = result.document
|
||||
assert doc.source_filename == "jane_smith.pdf"
|
||||
assert len(doc.pages) == 2
|
||||
assert len(doc.sections) >= 3
|
||||
|
||||
# Verify high-yield coding text extraction
|
||||
coding_text = doc.get_coding_text()
|
||||
assert "DISCHARGE DIAGNOSES" in coding_text
|
||||
assert "Acute systolic" in coding_text
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_process_ten_pdfs_batch() -> None:
|
||||
"""Requirement: Process a batch of 10 PDFs asynchronously without creating 10 LLM instances."""
|
||||
batch_size = 10
|
||||
pdf_sources = [
|
||||
generate_sample_clinical_pdf(patient_name=f"PATIENT_{i:02d}", num_pages=1)
|
||||
for i in range(batch_size)
|
||||
]
|
||||
filenames = [f"patient_{i:02d}.pdf" for i in range(batch_size)]
|
||||
|
||||
processor = BatchPDFProcessor(max_concurrency=10)
|
||||
batch_result = await processor.process_documents_batch(
|
||||
pdf_sources=pdf_sources,
|
||||
filenames=filenames,
|
||||
job_id="test-batch-10-docs",
|
||||
)
|
||||
|
||||
assert batch_result.total_documents == 10
|
||||
assert batch_result.successful_documents == 10
|
||||
assert batch_result.failed_documents == 0
|
||||
assert len(batch_result.results) == 10
|
||||
|
||||
# Ensure every document has a unique ID and successful status
|
||||
doc_ids = {r.document_id for r in batch_result.results}
|
||||
assert len(doc_ids) == 10
|
||||
for r in batch_result.results:
|
||||
assert r.status == PDFExtractionStatus.SUCCESS
|
||||
assert r.document is not None
|
||||
assert r.page_count == 1
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Tests: Edge Cases, Malformed, Empty, and Scanned PDFs
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_failed_nonexistent_pdf_file() -> None:
|
||||
"""Verify that a non-existent PDF file path returns EXTRACTION_ERROR without crashing."""
|
||||
missing_path = Path("./nonexistent_directory/missing_file_123.pdf")
|
||||
result = await process_document(pdf_source=missing_path)
|
||||
|
||||
assert result.status == PDFExtractionStatus.EXTRACTION_ERROR
|
||||
assert result.document is None
|
||||
assert "not found" in (result.error_message or "").lower()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_empty_pdf() -> None:
|
||||
"""Verify that an empty 0-byte stream returns EMPTY_PDF status."""
|
||||
empty_bytes = b""
|
||||
result = await process_document(pdf_source=empty_bytes, filename="empty.pdf")
|
||||
|
||||
assert result.status == PDFExtractionStatus.EMPTY_PDF
|
||||
assert result.document is None
|
||||
assert "empty" in (result.error_message or "").lower()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_malformed_pdf_corrupted_bytes() -> None:
|
||||
"""Verify that corrupted binary data returns MALFORMED_PDF without raising unhandled exceptions."""
|
||||
corrupted_bytes = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\nGARBAGE_DATA_CORRUPT_EOF"
|
||||
result = await process_document(pdf_source=corrupted_bytes, filename="corrupt.pdf")
|
||||
|
||||
assert result.status == PDFExtractionStatus.MALFORMED_PDF
|
||||
assert result.document is None
|
||||
assert result.error_message is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_insufficient_extracted_text() -> None:
|
||||
"""Verify that a document with minimal text (< 50 chars) returns INSUFFICIENT_TEXT."""
|
||||
short_pdf = generate_insufficient_text_pdf()
|
||||
result = await process_document(pdf_source=short_pdf, filename="short.pdf")
|
||||
|
||||
assert result.status == PDFExtractionStatus.INSUFFICIENT_TEXT
|
||||
assert result.document is None
|
||||
assert result.char_count < 50
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_scanned_pdf_detects_needs_ocr() -> None:
|
||||
"""Requirement: Gracefully detect scanned raster PDFs and return NEEDS_OCR without inventing text."""
|
||||
scanned_bytes = generate_scanned_image_pdf()
|
||||
extractor = PDFExtractor(min_page_chars_for_scanned=20, min_doc_chars=50)
|
||||
processor = BatchPDFProcessor(extractor=extractor)
|
||||
|
||||
result = await processor.process_document(pdf_source=scanned_bytes, filename="scanned_scan.pdf")
|
||||
|
||||
assert result.status == PDFExtractionStatus.NEEDS_OCR
|
||||
assert result.needs_ocr is True
|
||||
assert result.document is None
|
||||
assert "ocr is required" in (result.error_message or "").lower()
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Tests: Batch Fault Tolerance & Throughput Benchmark
|
||||
# ============================================================================
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_batch_fault_tolerance_mixed_payload() -> None:
|
||||
"""Verify that a batch with mixed valid and broken PDFs completes with isolated statuses."""
|
||||
valid_pdf = generate_sample_clinical_pdf("PATIENT_VALID")
|
||||
corrupt_pdf = b"NOT_A_REAL_PDF"
|
||||
empty_pdf = b""
|
||||
short_pdf = generate_insufficient_text_pdf()
|
||||
|
||||
sources = [valid_pdf, corrupt_pdf, empty_pdf, short_pdf, valid_pdf]
|
||||
filenames = ["valid1.pdf", "corrupt.pdf", "empty.pdf", "short.pdf", "valid2.pdf"]
|
||||
|
||||
batch_res = await process_documents_batch(
|
||||
pdf_sources=sources,
|
||||
filenames=filenames,
|
||||
)
|
||||
|
||||
assert batch_res.total_documents == 5
|
||||
assert batch_res.successful_documents == 2
|
||||
assert batch_res.failed_documents == 3
|
||||
|
||||
statuses = [r.status for r in batch_res.results]
|
||||
assert statuses[0] == PDFExtractionStatus.SUCCESS
|
||||
assert statuses[1] == PDFExtractionStatus.MALFORMED_PDF
|
||||
assert statuses[2] == PDFExtractionStatus.EMPTY_PDF
|
||||
assert statuses[3] == PDFExtractionStatus.INSUFFICIENT_TEXT
|
||||
assert statuses[4] == PDFExtractionStatus.SUCCESS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_throughput_benchmark_ten_documents() -> None:
|
||||
"""Benchmark extraction throughput on 10 multi-page clinical discharge summaries."""
|
||||
batch_size = 10
|
||||
sources = [
|
||||
generate_sample_clinical_pdf(patient_name=f"BENCHMARK_{i}", num_pages=2)
|
||||
for i in range(batch_size)
|
||||
]
|
||||
|
||||
batch_result = await process_documents_batch(sources)
|
||||
|
||||
assert batch_result.total_documents == 10
|
||||
assert batch_result.successful_documents == 10
|
||||
assert batch_result.total_elapsed_ms > 0
|
||||
assert batch_result.throughput_docs_per_sec > 0
|
||||
|
||||
print(
|
||||
f"\n[Throughput Benchmark] 10 Multi-page PDFs (2 pages each): "
|
||||
f"Total time = {batch_result.total_elapsed_ms:.2f} ms | "
|
||||
f"Throughput = {batch_result.throughput_docs_per_sec:.2f} docs/sec"
|
||||
)
|
||||
@@ -0,0 +1,422 @@
|
||||
"""Comprehensive unit and integration tests for the Local ICD-10-CM Retrieval and Knowledge Layer."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from medical_coding.dataset.loader import (
|
||||
CMSOrderFileLoader,
|
||||
TabularICDLoader,
|
||||
)
|
||||
from medical_coding.dataset.validator import LocalICDCatalog
|
||||
from medical_coding.models.factory import FastLocalEmbeddings
|
||||
from medical_coding.retrieval.hybrid import HybridICDRetriever
|
||||
from medical_coding.retrieval.lexical import BM25ICDRetriever
|
||||
from medical_coding.retrieval.vector import FAISSICDRetriever
|
||||
from medical_coding.schemas.icd import ICDCodeRecord
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_records() -> list[ICDCodeRecord]:
|
||||
"""Curated authoritative ICD records for testing retrieval behaviors."""
|
||||
return [
|
||||
ICDCodeRecord(
|
||||
code="I50.21",
|
||||
unformatted_code="I5021",
|
||||
description="Acute systolic heart failure",
|
||||
short_description="Acute systolic heart failure",
|
||||
long_description="Acute systolic (congestive) heart failure",
|
||||
is_valid_billable=True,
|
||||
category="I50",
|
||||
inclusion_terms=["Acute congestive heart failure with systolic dysfunction"],
|
||||
exclusion_terms=["Combined systolic and diastolic heart failure (I50.4-)"],
|
||||
synonyms=[
|
||||
"acute systolic HF",
|
||||
"acute decompensated systolic heart failure",
|
||||
"HFrEF acute",
|
||||
],
|
||||
),
|
||||
ICDCodeRecord(
|
||||
code="I50.22",
|
||||
unformatted_code="I5022",
|
||||
description="Chronic systolic heart failure",
|
||||
short_description="Chronic systolic heart failure",
|
||||
long_description="Chronic systolic (congestive) heart failure",
|
||||
is_valid_billable=True,
|
||||
category="I50",
|
||||
inclusion_terms=["Chronic congestive heart failure with systolic dysfunction"],
|
||||
exclusion_terms=["Combined systolic and diastolic heart failure (I50.4-)"],
|
||||
synonyms=["chronic systolic HF", "compensated systolic heart failure", "chronic HFrEF"],
|
||||
),
|
||||
ICDCodeRecord(
|
||||
code="I50.9",
|
||||
unformatted_code="I509",
|
||||
description="Heart failure, unspecified",
|
||||
short_description="Heart failure, unspecified",
|
||||
long_description="Congestive heart failure NOS; Cardiac failure NOS",
|
||||
is_valid_billable=True,
|
||||
category="I50",
|
||||
inclusion_terms=["Congestive heart failure NOS"],
|
||||
synonyms=["HF", "CHF", "heart failure"],
|
||||
),
|
||||
ICDCodeRecord(
|
||||
code="I10",
|
||||
unformatted_code="I10",
|
||||
description="Essential primary hypertension",
|
||||
short_description="Essential primary hypertension",
|
||||
long_description="Essential primary hypertension; High blood pressure",
|
||||
is_valid_billable=True,
|
||||
category="I10",
|
||||
inclusion_terms=["High blood pressure", "Arterial hypertension"],
|
||||
synonyms=["HTN", "primary hypertension", "high blood pressure"],
|
||||
),
|
||||
ICDCodeRecord(
|
||||
code="E11.9",
|
||||
unformatted_code="E119",
|
||||
description="Type 2 diabetes mellitus without complications",
|
||||
short_description="Type 2 diabetes mellitus without complications",
|
||||
long_description="Type 2 diabetes mellitus without complications",
|
||||
is_valid_billable=True,
|
||||
category="E11",
|
||||
inclusion_terms=["Diabetes mellitus type 2 NOS"],
|
||||
synonyms=["T2DM", "type 2 diabetes", "diabetes mellitus type 2"],
|
||||
),
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def indexed_hybrid_system(
|
||||
sample_records: list[ICDCodeRecord],
|
||||
) -> tuple[LocalICDCatalog, HybridICDRetriever]:
|
||||
"""Provide a fully configured local catalog and hybrid retriever."""
|
||||
catalog = LocalICDCatalog()
|
||||
for rec in sample_records:
|
||||
catalog.add_record(rec)
|
||||
catalog._initialized = True
|
||||
|
||||
bm25 = BM25ICDRetriever()
|
||||
bm25.build_index(sample_records)
|
||||
|
||||
embeddings = FastLocalEmbeddings(dim=384)
|
||||
faiss_ret = FAISSICDRetriever(embeddings=embeddings)
|
||||
faiss_ret.build_index(sample_records)
|
||||
|
||||
hybrid = HybridICDRetriever(
|
||||
lexical_retriever=bm25,
|
||||
vector_retriever=faiss_ret,
|
||||
catalog=catalog,
|
||||
weight_semantic=0.6,
|
||||
weight_lexical=0.4,
|
||||
min_score_threshold=0.35,
|
||||
default_top_k=5,
|
||||
)
|
||||
return catalog, hybrid
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 1. RETRIEVAL BEHAVIOR TESTS (Required Test Cases)
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_exact_diagnosis_retrieval(
|
||||
indexed_hybrid_system: tuple[LocalICDCatalog, HybridICDRetriever],
|
||||
) -> None:
|
||||
"""Exact clinical diagnosis must return the correct ICD code with high confidence."""
|
||||
_, hybrid = indexed_hybrid_system
|
||||
results = hybrid.retrieve("Acute systolic heart failure", top_k=3)
|
||||
|
||||
assert len(results) > 0
|
||||
top = results[0]
|
||||
assert top.code == "I50.21"
|
||||
assert "Acute systolic heart failure" in top.description
|
||||
assert top.retrieval_score >= 0.85
|
||||
assert top.is_valid_billable is True
|
||||
|
||||
|
||||
def test_synonym_retrieval(
|
||||
indexed_hybrid_system: tuple[LocalICDCatalog, HybridICDRetriever],
|
||||
) -> None:
|
||||
"""Clinical synonyms like 'HFrEF acute' must retrieve the correct underlying code."""
|
||||
_, hybrid = indexed_hybrid_system
|
||||
results = hybrid.retrieve("HFrEF acute", top_k=3)
|
||||
|
||||
assert len(results) > 0
|
||||
top = results[0]
|
||||
assert top.code == "I50.21"
|
||||
assert top.retrieval_score > 0.50
|
||||
|
||||
|
||||
def test_abbreviation_retrieval(
|
||||
indexed_hybrid_system: tuple[LocalICDCatalog, HybridICDRetriever],
|
||||
) -> None:
|
||||
"""Standard clinical abbreviations like 'HTN' or 'T2DM' must retrieve correct codes."""
|
||||
_, hybrid = indexed_hybrid_system
|
||||
|
||||
# Test HTN -> I10
|
||||
htn_results = hybrid.retrieve("HTN", top_k=3)
|
||||
assert len(htn_results) > 0
|
||||
assert htn_results[0].code == "I10"
|
||||
|
||||
# Test T2DM -> E11.9
|
||||
dm_results = hybrid.retrieve("T2DM", top_k=3)
|
||||
assert len(dm_results) > 0
|
||||
assert dm_results[0].code == "E11.9"
|
||||
|
||||
|
||||
def test_partial_terminology_retrieval(
|
||||
indexed_hybrid_system: tuple[LocalICDCatalog, HybridICDRetriever],
|
||||
) -> None:
|
||||
"""Incomplete/partial clinical terms like 'systolic failure' must retrieve relevant candidate codes."""
|
||||
_, hybrid = indexed_hybrid_system
|
||||
results = hybrid.retrieve("systolic failure", top_k=5)
|
||||
|
||||
assert len(results) >= 2
|
||||
codes = [c.code for c in results]
|
||||
assert "I50.21" in codes or "I50.22" in codes
|
||||
|
||||
|
||||
def test_ambiguous_diagnosis_retrieval(
|
||||
indexed_hybrid_system: tuple[LocalICDCatalog, HybridICDRetriever],
|
||||
) -> None:
|
||||
"""Ambiguous diagnosis like 'heart failure' must retrieve multiple candidates with graded scores."""
|
||||
_, hybrid = indexed_hybrid_system
|
||||
results = hybrid.retrieve("heart failure", top_k=5)
|
||||
|
||||
assert len(results) >= 2
|
||||
codes = [c.code for c in results]
|
||||
assert "I50.9" in codes
|
||||
assert "I50.21" in codes or "I50.22" in codes
|
||||
# Ensure scores are strictly monotonically descending
|
||||
scores = [c.retrieval_score for c in results]
|
||||
assert scores == sorted(scores, reverse=True)
|
||||
|
||||
|
||||
def test_no_match_abstention(
|
||||
indexed_hybrid_system: tuple[LocalICDCatalog, HybridICDRetriever],
|
||||
) -> None:
|
||||
"""Uncovered, nonsensical, or out-of-catalog conditions must return an empty list (abstention)."""
|
||||
_, hybrid = indexed_hybrid_system
|
||||
results = hybrid.retrieve("completely unknown martian syndrome x789", top_k=5)
|
||||
|
||||
assert results == [] # Explicit abstention state
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 2. DATASET INGESTION: DUPLICATES & MALFORMED RECORDS
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_duplicate_candidate_handling(tmp_path: Path) -> None:
|
||||
"""Dataset loader must detect duplicate codes, merge synonyms/terms, and record metrics."""
|
||||
csv_file = tmp_path / "duplicates.csv"
|
||||
csv_content = (
|
||||
"code,description,is_valid_billable,synonyms\n"
|
||||
"I50.21,Acute systolic heart failure,1,acute systolic HF\n"
|
||||
"I50.21,Acute systolic heart failure duplicate,1,HFrEF acute\n"
|
||||
"E11.9,Type 2 diabetes,1,T2DM\n"
|
||||
)
|
||||
csv_file.write_text(csv_content, encoding="utf-8")
|
||||
|
||||
loader = TabularICDLoader(csv_file)
|
||||
records, stats = loader.load()
|
||||
|
||||
assert stats.total_records == 2
|
||||
assert stats.duplicates_dropped == 1
|
||||
assert "I50.21" in records
|
||||
# Merged synonyms check
|
||||
assert "acute systolic HF" in records["I50.21"].synonyms
|
||||
assert "HFrEF acute" in records["I50.21"].synonyms
|
||||
|
||||
|
||||
def test_malformed_icd_dataset_handling(tmp_path: Path) -> None:
|
||||
"""Dataset loader must filter out malformed codes, empty descriptions, and invalid rows."""
|
||||
csv_file = tmp_path / "malformed.csv"
|
||||
csv_content = (
|
||||
"code,description,is_valid_billable\n"
|
||||
"I50.21,Acute systolic heart failure,1\n"
|
||||
",Missing code diagnosis,1\n" # Malformed: no code
|
||||
"123.45,Code starts with digit,1\n" # Malformed: invalid ICD pattern
|
||||
"I50.22,,1\n" # Malformed: empty description
|
||||
"I50.23,Acute on chronic systolic heart failure,1\n" # Valid
|
||||
)
|
||||
csv_file.write_text(csv_content, encoding="utf-8")
|
||||
|
||||
loader = TabularICDLoader(csv_file)
|
||||
records, stats = loader.load()
|
||||
|
||||
assert stats.total_records == 2
|
||||
assert stats.malformed_dropped == 3
|
||||
assert "I50.21" in records
|
||||
assert "I50.23" in records
|
||||
|
||||
|
||||
def test_missing_required_columns_error(tmp_path: Path) -> None:
|
||||
"""Tabular loader must reject dataset missing required code/description columns."""
|
||||
bad_csv = tmp_path / "bad_columns.csv"
|
||||
bad_csv.write_text("random_col1,random_col2\nval1,val2\n", encoding="utf-8")
|
||||
|
||||
loader = TabularICDLoader(bad_csv)
|
||||
with pytest.raises(ValueError, match="Missing required columns"):
|
||||
loader.load()
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 3. FORMATS & CMS ORDER FILE INGESTION
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_json_dataset_ingestion(tmp_path: Path) -> None:
|
||||
"""Loader must support JSON array format."""
|
||||
json_file = tmp_path / "dataset.json"
|
||||
data = [
|
||||
{
|
||||
"code": "I50.21",
|
||||
"description": "Acute systolic heart failure",
|
||||
"is_valid_billable": True,
|
||||
},
|
||||
{"code": "I10", "description": "Essential primary hypertension", "is_valid_billable": True},
|
||||
]
|
||||
json_file.write_text(json.dumps(data), encoding="utf-8")
|
||||
|
||||
loader = TabularICDLoader(json_file)
|
||||
records, stats = loader.load()
|
||||
|
||||
assert stats.total_records == 2
|
||||
assert "I50.21" in records
|
||||
assert "I10" in records
|
||||
|
||||
|
||||
def test_cms_order_file_ingestion(tmp_path: Path) -> None:
|
||||
"""CMSOrderFileLoader must parse fixed-width CMS order lines correctly."""
|
||||
cms_file = tmp_path / "cms_order.txt"
|
||||
# Format: order(5) space code(7) space valid(1) space short(60) space long
|
||||
line1 = f"{1:05d} I5021 1 {'Acute systolic heart failure':<60} Acute systolic (congestive) heart failure"
|
||||
line2 = f"{2:05d} I50 0 {'Heart failure':<60} Heart failure category header"
|
||||
cms_file.write_text(f"{line1}\n{line2}\n", encoding="utf-8")
|
||||
|
||||
loader = CMSOrderFileLoader(cms_file)
|
||||
records, stats = loader.load()
|
||||
|
||||
assert stats.total_records == 2
|
||||
assert stats.valid_billable_count == 1
|
||||
assert stats.non_billable_count == 1
|
||||
assert "I50.21" in records
|
||||
assert records["I50.21"].is_valid_billable is True
|
||||
assert "I50" in records
|
||||
assert records["I50"].is_valid_billable is False
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 4. CONFIGURABLE RETRIEVAL WEIGHTS & CATALOG SOURCE OF TRUTH
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_configurable_retrieval_weights(sample_records: list[ICDCodeRecord]) -> None:
|
||||
"""Configuring pure semantic or pure lexical weights alters candidate ranking accordingly."""
|
||||
bm25 = BM25ICDRetriever()
|
||||
bm25.build_index(sample_records)
|
||||
|
||||
faiss_ret = FAISSICDRetriever(embeddings=FastLocalEmbeddings(dim=384))
|
||||
faiss_ret.build_index(sample_records)
|
||||
|
||||
# 100% lexical weight
|
||||
lexical_only = HybridICDRetriever(
|
||||
lexical_retriever=bm25,
|
||||
vector_retriever=faiss_ret,
|
||||
weight_semantic=0.0,
|
||||
weight_lexical=1.0,
|
||||
min_score_threshold=0.10,
|
||||
)
|
||||
lex_res = lexical_only.retrieve("Acute systolic heart failure", top_k=1)
|
||||
assert len(lex_res) > 0
|
||||
assert lex_res[0].code == "I50.21"
|
||||
assert lex_res[0].retrieval_score == lex_res[0].lexical_score
|
||||
|
||||
# 100% semantic weight
|
||||
semantic_only = HybridICDRetriever(
|
||||
lexical_retriever=bm25,
|
||||
vector_retriever=faiss_ret,
|
||||
weight_semantic=1.0,
|
||||
weight_lexical=0.0,
|
||||
min_score_threshold=0.10,
|
||||
)
|
||||
sem_res = semantic_only.retrieve("Acute systolic heart failure", top_k=1)
|
||||
assert len(sem_res) > 0
|
||||
assert sem_res[0].code == "I50.21"
|
||||
assert sem_res[0].retrieval_score == sem_res[0].semantic_score
|
||||
|
||||
|
||||
def test_catalog_enforcement_strictly_prevents_unindexed_codes(
|
||||
sample_records: list[ICDCodeRecord],
|
||||
) -> None:
|
||||
"""Catalog filtering must discard any candidate not present in authoritative dataset."""
|
||||
catalog = LocalICDCatalog()
|
||||
# Catalog contains ONLY I10 and E11.9
|
||||
catalog.add_record(sample_records[3]) # I10
|
||||
catalog.add_record(sample_records[4]) # E11.9
|
||||
catalog._initialized = True
|
||||
|
||||
bm25 = BM25ICDRetriever()
|
||||
bm25.build_index(sample_records) # Built with all 5 records
|
||||
|
||||
faiss_ret = FAISSICDRetriever(embeddings=FastLocalEmbeddings(dim=384))
|
||||
faiss_ret.build_index(sample_records)
|
||||
|
||||
hybrid = HybridICDRetriever(
|
||||
lexical_retriever=bm25,
|
||||
vector_retriever=faiss_ret,
|
||||
catalog=catalog, # Constrained catalog
|
||||
min_score_threshold=0.10,
|
||||
)
|
||||
|
||||
# Query for heart failure (I50.21 is in retriever index but NOT in catalog)
|
||||
results = hybrid.retrieve("Acute systolic heart failure")
|
||||
# Must NOT return I50.21 because catalog is the sole source of truth
|
||||
for c in results:
|
||||
assert catalog.is_valid_code(c.code)
|
||||
assert not any(c.code == "I50.21" for c in results)
|
||||
|
||||
|
||||
# ==============================================================================
|
||||
# 5. PERSISTENCE & DISK RELOADING
|
||||
# ==============================================================================
|
||||
|
||||
|
||||
def test_retrieval_index_persistence(tmp_path: Path, sample_records: list[ICDCodeRecord]) -> None:
|
||||
"""Indices and catalogs saved to disk must reload and produce identical retrieval results."""
|
||||
catalog = LocalICDCatalog()
|
||||
for rec in sample_records:
|
||||
catalog.add_record(rec)
|
||||
catalog._initialized = True
|
||||
catalog.save_to_json(tmp_path / "catalog.json")
|
||||
|
||||
bm25 = BM25ICDRetriever()
|
||||
bm25.build_index(sample_records)
|
||||
bm25.save(tmp_path)
|
||||
|
||||
embeddings = FastLocalEmbeddings(dim=384)
|
||||
faiss_ret = FAISSICDRetriever(embeddings=embeddings)
|
||||
faiss_ret.build_index(sample_records)
|
||||
faiss_ret.save(tmp_path)
|
||||
|
||||
# Reload from disk
|
||||
reloaded_catalog = LocalICDCatalog.load_from_json(tmp_path / "catalog.json")
|
||||
reloaded_bm25 = BM25ICDRetriever()
|
||||
reloaded_bm25.load(tmp_path)
|
||||
reloaded_faiss = FAISSICDRetriever(embeddings=embeddings)
|
||||
reloaded_faiss.load(tmp_path)
|
||||
|
||||
assert len(reloaded_catalog) == len(sample_records)
|
||||
assert reloaded_bm25.is_indexed is True
|
||||
assert reloaded_faiss.is_indexed is True
|
||||
|
||||
reloaded_hybrid = HybridICDRetriever(
|
||||
lexical_retriever=reloaded_bm25,
|
||||
vector_retriever=reloaded_faiss,
|
||||
catalog=reloaded_catalog,
|
||||
)
|
||||
|
||||
results = reloaded_hybrid.retrieve("Acute systolic heart failure", top_k=1)
|
||||
assert len(results) == 1
|
||||
assert results[0].code == "I50.21"
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Unit tests for Pydantic domain schemas and invariants."""
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from medical_coding.schemas.clinical import (
|
||||
ClinicalDocument,
|
||||
EvidenceSnippet,
|
||||
ExtractedDiagnosis,
|
||||
)
|
||||
from medical_coding.schemas.enums import (
|
||||
Acuity,
|
||||
Certainty,
|
||||
DiagnosisRole,
|
||||
ExecutionStatus,
|
||||
)
|
||||
from medical_coding.schemas.response import (
|
||||
CodedDiagnosisResponse,
|
||||
CodingResult,
|
||||
)
|
||||
|
||||
|
||||
def test_clinical_document_instantiation() -> None:
|
||||
doc = ClinicalDocument(text="Patient diagnosed with acute appendicitis.")
|
||||
assert len(doc.document_id) > 0
|
||||
assert doc.source_type == "text"
|
||||
assert "appendicitis" in doc.text
|
||||
|
||||
|
||||
def test_extracted_diagnosis_requires_evidence() -> None:
|
||||
evidence = EvidenceSnippet(quote="Admitted for acute asthma exacerbation.")
|
||||
extracted = ExtractedDiagnosis(
|
||||
raw_term="acute asthma exacerbation",
|
||||
evidence=evidence,
|
||||
extraction_confidence=0.92,
|
||||
)
|
||||
assert extracted.raw_term == "acute asthma exacerbation"
|
||||
assert extracted.evidence.quote == "Admitted for acute asthma exacerbation."
|
||||
|
||||
# Must fail without evidence
|
||||
with pytest.raises(ValidationError):
|
||||
ExtractedDiagnosis( # type: ignore[call-arg]
|
||||
raw_term="acute asthma exacerbation",
|
||||
extraction_confidence=0.92,
|
||||
)
|
||||
|
||||
|
||||
def test_coding_result_single_primary_invariant() -> None:
|
||||
"""Verify invariant: secondary_diagnoses cannot contain role PRIMARY."""
|
||||
primary = CodedDiagnosisResponse(
|
||||
code="I50.21",
|
||||
description="Acute systolic heart failure",
|
||||
role=DiagnosisRole.PRIMARY,
|
||||
acuity=Acuity.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
evidence_quote="Patient presented with acute systolic heart failure.",
|
||||
confidence_score=0.95,
|
||||
)
|
||||
|
||||
invalid_secondary = CodedDiagnosisResponse(
|
||||
code="E11.9",
|
||||
description="Type 2 diabetes",
|
||||
role=DiagnosisRole.PRIMARY, # INVARIANT VIOLATION: Role is PRIMARY in secondary list
|
||||
acuity=Acuity.CHRONIC,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
evidence_quote="History of diabetes.",
|
||||
confidence_score=0.90,
|
||||
)
|
||||
|
||||
valid_secondary = CodedDiagnosisResponse(
|
||||
code="E11.9",
|
||||
description="Type 2 diabetes",
|
||||
role=DiagnosisRole.SECONDARY,
|
||||
acuity=Acuity.CHRONIC,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
evidence_quote="History of diabetes.",
|
||||
confidence_score=0.90,
|
||||
)
|
||||
|
||||
# Valid scenario
|
||||
result = CodingResult(
|
||||
document_id="doc-123",
|
||||
status=ExecutionStatus.SUCCESS,
|
||||
primary_diagnosis=primary,
|
||||
secondary_diagnoses=[valid_secondary],
|
||||
abstentions=[],
|
||||
processing_time_ms=120.5,
|
||||
)
|
||||
assert result.primary_diagnosis.code == "I50.21"
|
||||
assert len(result.secondary_diagnoses) == 1
|
||||
|
||||
# Invalid scenario: secondary list contains PRIMARY role
|
||||
with pytest.raises(ValueError, match="Secondary diagnoses cannot have role PRIMARY"):
|
||||
CodingResult(
|
||||
document_id="doc-123",
|
||||
status=ExecutionStatus.SUCCESS,
|
||||
primary_diagnosis=primary,
|
||||
secondary_diagnoses=[invalid_secondary],
|
||||
abstentions=[],
|
||||
processing_time_ms=120.5,
|
||||
)
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Unit tests for LangGraph state management and reducers."""
|
||||
|
||||
from medical_coding.graph.state import create_initial_state
|
||||
from medical_coding.schemas.enums import PipelineStage
|
||||
from medical_coding.schemas.state import (
|
||||
PipelineExecutionSnapshot,
|
||||
append_items,
|
||||
merge_dicts,
|
||||
)
|
||||
|
||||
|
||||
def test_initial_state_generation() -> None:
|
||||
state = create_initial_state(document_id="doc-test-1", raw_text="Sample clinical note.")
|
||||
assert state["document_id"] == "doc-test-1"
|
||||
assert state["raw_text"] == "Sample clinical note."
|
||||
assert state["current_stage"] == PipelineStage.INGESTION
|
||||
assert state["is_aborted"] is False
|
||||
assert state["extracted_diagnoses"] == []
|
||||
assert state["candidate_pool"] == {}
|
||||
|
||||
|
||||
def test_append_items_reducer() -> None:
|
||||
existing = ["item1", "item2"]
|
||||
new_items = ["item3"]
|
||||
result = append_items(existing, new_items)
|
||||
assert result == ["item1", "item2", "item3"]
|
||||
|
||||
# None / empty checks
|
||||
assert append_items([], ["a"]) == ["a"]
|
||||
assert append_items(["b"], []) == ["b"]
|
||||
|
||||
|
||||
def test_merge_dicts_reducer() -> None:
|
||||
d1 = {"k1": "v1"}
|
||||
d2 = {"k2": "v2", "k1": "updated"}
|
||||
merged = merge_dicts(d1, d2)
|
||||
assert merged == {"k1": "updated", "k2": "v2"}
|
||||
|
||||
|
||||
def test_state_snapshot() -> None:
|
||||
snap = PipelineExecutionSnapshot(
|
||||
document_id="doc-123",
|
||||
current_stage=PipelineStage.FINALIZATION,
|
||||
extracted_count=3,
|
||||
classified_count=2,
|
||||
validated_count=2,
|
||||
abstention_count=1,
|
||||
has_primary=True,
|
||||
is_terminal=True,
|
||||
)
|
||||
assert snap.extracted_count == 3
|
||||
assert snap.has_primary is True
|
||||
@@ -0,0 +1,124 @@
|
||||
"""Unit tests for deterministic ICD validation and rule enforcement."""
|
||||
|
||||
from medical_coding.dataset.validator import LocalICDCatalog
|
||||
from medical_coding.schemas.clinical import ClassifiedDiagnosis
|
||||
from medical_coding.schemas.enums import AbstentionReason, DiagnosisRole
|
||||
from medical_coding.schemas.icd import ICDCandidate, RankedSelection
|
||||
from medical_coding.validation.deterministic import DeterministicValidator
|
||||
|
||||
|
||||
def test_validation_passes_valid_billable_code(
|
||||
mock_catalog: LocalICDCatalog,
|
||||
sample_classified_primary: ClassifiedDiagnosis,
|
||||
sample_ranked_selection: RankedSelection,
|
||||
) -> None:
|
||||
validator = DeterministicValidator(catalog=mock_catalog)
|
||||
validated, abstention = validator.validate_code(
|
||||
condition=sample_classified_primary,
|
||||
selection=sample_ranked_selection,
|
||||
)
|
||||
|
||||
assert abstention is None
|
||||
assert validated is not None
|
||||
assert validated.code == "I50.21"
|
||||
assert validated.role == DiagnosisRole.PRIMARY
|
||||
assert len(validated.checks) == 2
|
||||
assert all(c.passed for c in validated.checks)
|
||||
|
||||
|
||||
def test_validation_rejects_nonexistent_code(
|
||||
mock_catalog: LocalICDCatalog,
|
||||
sample_classified_primary: ClassifiedDiagnosis,
|
||||
) -> None:
|
||||
validator = DeterministicValidator(catalog=mock_catalog)
|
||||
fake_candidate = ICDCandidate(
|
||||
code="Z99.9999", # Does not exist in local catalog
|
||||
description="Fictitious condition",
|
||||
retrieval_score=0.99,
|
||||
retrieval_method="hybrid",
|
||||
is_valid_billable=True,
|
||||
)
|
||||
selection = RankedSelection(
|
||||
diagnosis_id=sample_classified_primary.diagnosis_id,
|
||||
raw_term=sample_classified_primary.raw_term,
|
||||
selected_candidate=fake_candidate,
|
||||
ranking_score=0.99,
|
||||
selection_justification="Candidate tested for existence.",
|
||||
decision="ACCEPTED",
|
||||
)
|
||||
|
||||
validated, abstention = validator.validate_code(
|
||||
condition=sample_classified_primary,
|
||||
selection=selection,
|
||||
)
|
||||
assert validated is None
|
||||
assert abstention is not None
|
||||
assert abstention.reason == AbstentionReason.INVALID_ICD_CODE
|
||||
|
||||
|
||||
def test_validation_rejects_category_header_requiring_specificity(
|
||||
mock_catalog: LocalICDCatalog,
|
||||
sample_classified_primary: ClassifiedDiagnosis,
|
||||
) -> None:
|
||||
validator = DeterministicValidator(catalog=mock_catalog)
|
||||
# I50 is non-billable category header in our mock catalog
|
||||
header_candidate = ICDCandidate(
|
||||
code="I50",
|
||||
description="Heart failure category header",
|
||||
retrieval_score=0.85,
|
||||
retrieval_method="hybrid",
|
||||
is_valid_billable=False,
|
||||
)
|
||||
selection = RankedSelection(
|
||||
diagnosis_id=sample_classified_primary.diagnosis_id,
|
||||
raw_term=sample_classified_primary.raw_term,
|
||||
selected_candidate=header_candidate,
|
||||
ranking_score=0.85,
|
||||
selection_justification="Category header selected.",
|
||||
decision="ACCEPTED",
|
||||
)
|
||||
|
||||
validated, abstention = validator.validate_code(
|
||||
condition=sample_classified_primary,
|
||||
selection=selection,
|
||||
)
|
||||
assert validated is None
|
||||
assert abstention is not None
|
||||
assert abstention.reason == AbstentionReason.SPECIFICITY_REQUIRED
|
||||
|
||||
|
||||
def test_validation_detects_multiple_primaries_and_abstains(
|
||||
mock_catalog: LocalICDCatalog,
|
||||
sample_classified_primary: ClassifiedDiagnosis,
|
||||
sample_ranked_selection: RankedSelection,
|
||||
) -> None:
|
||||
validator = DeterministicValidator(catalog=mock_catalog)
|
||||
|
||||
# Create a second conflicting primary
|
||||
cond2 = sample_classified_primary.model_copy(deep=True)
|
||||
cond2.diagnosis_id = "diag-002"
|
||||
cond2.raw_term = "type 2 diabetes"
|
||||
cand2 = ICDCandidate(
|
||||
code="E11.9",
|
||||
description="Type 2 diabetes mellitus",
|
||||
retrieval_score=0.91,
|
||||
retrieval_method="hybrid",
|
||||
is_valid_billable=True,
|
||||
)
|
||||
sel2 = RankedSelection(
|
||||
diagnosis_id=cond2.diagnosis_id,
|
||||
raw_term=cond2.raw_term,
|
||||
selected_candidate=cand2,
|
||||
ranking_score=0.91,
|
||||
selection_justification="Candidate matching diabetes.",
|
||||
decision="ACCEPTED",
|
||||
)
|
||||
|
||||
validated_list, abstentions = validator.validate_encounter_set(
|
||||
conditions=[sample_classified_primary, cond2],
|
||||
selections=[sample_ranked_selection, sel2],
|
||||
)
|
||||
|
||||
# Invariant: Must abstain multiple conflicting primaries
|
||||
assert len(validated_list) == 0
|
||||
assert any(a.reason == AbstentionReason.MULTIPLE_AMBIGUOUS_PRIMARY for a in abstentions)
|
||||
Reference in New Issue
Block a user