feat(pipeline): complete healing and hardening of clinical reasoning and matching pipeline
- Implement soft dimensional compatibility and 3-way attribute logic (SUPPORTED, CONTRADICTED, UNKNOWN) - Replace binary hardwall rejection with nuanced compatibility scoring - Isolate context per diagnosis to prevent cross-condition contamination (MD Sec 41) - Generalize disease families (liver sarcoma, net, asthma, acl) and category priors - Add regex word boundary acuity checking and laterality alignment scoring in ranker - Fix candidate sort by sorting on unconstrained multi-factor raw score before output clamping - Preserve zero-modification immutability of local Database_2.xlsx - Pass 100% of full regression test suite (158/158 tests) and ruff linting
This commit is contained in:
@@ -0,0 +1,142 @@
|
||||
"""Adversarial and Edge-Case Test Suite for Generalized Clinical NLP Engine.
|
||||
|
||||
Enforces zero-hallucination, abstention-first policies, and strict gate rejections
|
||||
across edge cases detailed in Section 35 of the Master Prompt:
|
||||
1. Negated disease
|
||||
2. Historical condition without inpatient care
|
||||
3. Medication-only mention
|
||||
4. Isolated symptom without underlying diagnosis
|
||||
5. Disease attribute/staging not converted to standalone diagnosis
|
||||
6. Ambiguous specificity without documentary distinction
|
||||
7. Duplicate diagnosis across multiple sections
|
||||
8. Missing database code resulting in clean NO_DATABASE_MATCH
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from medical_coding.graph.pipeline import process_clinical_document
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adversarial_negated_disease():
|
||||
"""Negated condition ('pneumonia ruled out', 'no evidence of pulmonary embolism') must NOT code."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Chest pain and shortness of breath.
|
||||
HOSPITAL COURSE: CT pulmonary angiogram was negative for pulmonary embolism. Chest X-ray ruled out pneumonia. Patient had musculoskeletal chest wall strain, improved with NSAIDs.
|
||||
DISCHARGE DIAGNOSIS:
|
||||
Musculoskeletal chest pain.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="adv-negated")
|
||||
all_codes = [res.primary_diagnosis.code if res.primary_diagnosis else None] + [
|
||||
s.code for s in res.secondary_diagnoses
|
||||
]
|
||||
assert not any(c and c.startswith("I26") for c in all_codes)
|
||||
all_descs = [res.primary_diagnosis.description.lower() if res.primary_diagnosis else ""] + [
|
||||
s.description.lower() for s in res.secondary_diagnoses
|
||||
]
|
||||
assert not any("embolism" in d for d in all_descs)
|
||||
assert not any("pneumonia" in d for d in all_descs)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adversarial_historical_condition():
|
||||
"""Past condition without documented active evaluation/treatment must be EXCLUDED."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Inguinal hernia repair.
|
||||
PAST MEDICAL HISTORY: Remote history of cholecystectomy 10 years ago. History of childhood asthma (resolved).
|
||||
HOSPITAL COURSE: Underwent elective uncomplicated right inguinal hernia repair.
|
||||
DISCHARGE DIAGNOSIS:
|
||||
Right inguinal hernia.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="adv-historical")
|
||||
assert res.primary_diagnosis is not None
|
||||
assert "hernia" in res.primary_diagnosis.description.lower()
|
||||
all_descs = [s.description.lower() for s in res.secondary_diagnoses]
|
||||
assert not any("asthma" in d for d in all_descs)
|
||||
assert not any("cholecystectomy" in d for d in all_descs)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adversarial_medication_firewall():
|
||||
"""Medication mentions alone must NEVER become clinical diagnoses."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
DISCHARGE MEDICATIONS:
|
||||
1. Metformin 500mg PO BID
|
||||
2. Atorvastatin 20mg PO QHS
|
||||
3. Lisinopril 10mg PO Daily
|
||||
4. Syp. Cremaffin 15ml PO QHS PRN
|
||||
5. Alex cough lozenges PRN
|
||||
PLAN: Routine follow up in 1 month.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="adv-med-firewall")
|
||||
# Should not produce diagnoses from medications
|
||||
all_descs = []
|
||||
if res.primary_diagnosis:
|
||||
all_descs.append(res.primary_diagnosis.description.lower())
|
||||
all_descs.extend(s.description.lower() for s in res.secondary_diagnoses)
|
||||
assert not any("metformin" in d for d in all_descs)
|
||||
assert not any("cremaffin" in d for d in all_descs)
|
||||
assert not any("lozenge" in d for d in all_descs)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adversarial_standalone_attribute_firewall():
|
||||
"""Disease attributes (Stage IV, Triple Negative, GCB, Grade III) must not be separate diagnoses."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
PRINCIPAL DIAGNOSIS:
|
||||
Invasive ductal carcinoma of breast.
|
||||
BIOMARKERS:
|
||||
Stage IV.
|
||||
Triple negative.
|
||||
BRCA pathogenic.
|
||||
Grade III.
|
||||
GCB subtype.
|
||||
HOSPITAL COURSE: Restaged and treated with paclitaxel.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="adv-attr-firewall")
|
||||
assert res.primary_diagnosis is not None
|
||||
sec_descs = [s.description.lower() for s in res.secondary_diagnoses]
|
||||
assert not any("stage iv" in d for d in sec_descs)
|
||||
assert not any("triple negative" in d for d in sec_descs)
|
||||
assert not any("brca" in d for d in sec_descs)
|
||||
assert not any("grade iii" in d for d in sec_descs)
|
||||
assert not any("gcb" in d for d in sec_descs)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adversarial_unsupported_displacement_abstention():
|
||||
"""If database requires displaced/nondisplaced and text is ambiguous without support, must abstain."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
PRINCIPAL DIAGNOSIS:
|
||||
Fracture of shaft of left humerus.
|
||||
HOSPITAL COURSE: Patient sustained left arm injury. Radiograph revealed left humerus shaft fracture. Arm immobilized in coaptation splint. Displacement not evaluated due to splint artifact.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="adv-ambig-disp")
|
||||
# If the system matches a code, it must NOT choose a displaced code without evidence
|
||||
if res.primary_diagnosis and res.primary_diagnosis.code:
|
||||
desc = res.primary_diagnosis.description.lower()
|
||||
assert "displaced" not in desc or "nondisplaced" in desc or "without mention of displacement" in desc
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_adversarial_candidate_deduplication():
|
||||
"""The same clinical concept mentioned across 4 sections must become ONE canonical candidate."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Chronic gastritis symptoms.
|
||||
ADMITTING DIAGNOSIS: Chronic gastritis.
|
||||
HOSPITAL COURSE: Patient evaluated for chronic gastritis with EGD showing mild chronic antral gastritis.
|
||||
DISCHARGE DIAGNOSIS:
|
||||
1. Chronic gastritis
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="adv-dedup")
|
||||
assert res.primary_diagnosis is not None
|
||||
assert "gastritis" in res.primary_diagnosis.description.lower()
|
||||
# Must NOT have chronic gastritis also in secondary diagnoses!
|
||||
sec_descs = [s.description.lower() for s in res.secondary_diagnoses]
|
||||
assert not any("gastritis" in d for d in sec_descs), "Duplicate gastritis candidate leaked into secondaries"
|
||||
@@ -0,0 +1,235 @@
|
||||
"""Full Regression Test Suite for Generalized Clinical NLP & ICD-10-CM Coding Pipeline.
|
||||
|
||||
Validates all 10 canonical benchmark cases plus Orthopedic (Case H) and Oncology (Case I).
|
||||
Enforces 100% recall, exact primary/secondary designation, and zero hallucination/pollution.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from medical_coding.graph.pipeline import process_clinical_document
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_case_acute_bronchitis():
|
||||
"""Case 3: Acute bronchitis admitted, ruled-out pneumonia, unmanaged history of falling."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Productive cough, low-grade fever, and wheezing.
|
||||
PAST MEDICAL HISTORY: History of falling.
|
||||
HOSPITAL COURSE: Patient presented with acute worsening cough and purulent sputum. Chest X-ray was performed and pneumonia was definitively ruled out. Diagnosed with acute bronchitis and treated with bronchodilators and supportive hydration with symptom resolution.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Acute bronchitis
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="reg-case-bronchitis")
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code == "J20.9"
|
||||
assert not any("pneumonia" in (s.description or "").lower() for s in res.secondary_diagnoses)
|
||||
assert not any("fall" in (s.description or "").lower() for s in res.secondary_diagnoses)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_case_ureteric_calculus():
|
||||
"""Case 4: Right ureteric calculus (N20.1) - symptom N23 rejected as primary."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Severe right flank pain radiating to groin.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Right ureteric calculus. CT showed 4mm distal right ureteral stone with renal colic. Managed with IV hydration, analgesics, and tamsulosin.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="reg-case-ureter")
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code == "N20.1"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_case_chronic_gastritis_hpylori():
|
||||
"""Case 5: Chronic gastritis (K29.50) without bleeding + H. pylori (B96.81)."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Chronic dyspepsia and epigastric discomfort.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Chronic gastritis
|
||||
2. Helicobacter pylori infection
|
||||
HOSPITAL COURSE: Endoscopy confirmed chronic gastritis without bleeding or ulceration. Biopsy positive for Helicobacter pylori. Triple therapy initiated.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="reg-case-gastritis")
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code == "K29.50"
|
||||
sec_codes = {s.code for s in res.secondary_diagnoses}
|
||||
assert "B96.81" in sec_codes
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_case_dlbcl_chemo():
|
||||
"""Case 6: DLBCL chemotherapy admission - zero absence statement leakage."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
ADMITTING DIAGNOSIS: Diffuse Large B-Cell Lymphoma (DLBCL)
|
||||
REASON FOR ADMISSION: Admitted for initiation of cycle 1 chemotherapy for DLBCL.
|
||||
HOSPITAL COURSE: Patient received R-CHOP chemotherapy infusion without acute event. No major acute complication occurred during the admission.
|
||||
DISCHARGE DIAGNOSIS:
|
||||
1. Diffuse Large B-Cell Lymphoma
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="reg-case-dlbcl")
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code == "C83.30"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_case_cap_t2dm_htn_ckd():
|
||||
"""Case 7: CAP (J18.9) Primary, T2DM (E11.9), HTN (I10), CKD3 (N18.30) Secondaries."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
REASON FOR ADMISSION: Admitted with high fever, dyspnea, and productive cough due to community-acquired pneumonia.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Community-acquired pneumonia
|
||||
2. Type 2 diabetes mellitus
|
||||
3. Essential hypertension
|
||||
4. Chronic kidney disease stage 3
|
||||
HOSPITAL COURSE: Treated with IV ceftriaxone for community-acquired pneumonia. Blood sugars monitored and sliding scale insulin continued for Type 2 diabetes. Amlodipine continued for essential hypertension. Baseline creatinine 1.8 followed for CKD stage 3.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="reg-case-cap")
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code == "J18.9"
|
||||
sec_codes = {s.code for s in res.secondary_diagnoses}
|
||||
assert "E11.9" in sec_codes
|
||||
assert "I10" in sec_codes
|
||||
assert "N18.30" in sec_codes or "N18.3" in sec_codes
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_case_dlbcl_full():
|
||||
"""DLBCL Full: Primary C83.30, zero medication or instruction leakage."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
PATIENT NAME: [Redacted]
|
||||
ADMITTING DIAGNOSIS: Diffuse Large B-Cell Lymphoma, Stage IV, GCB type.
|
||||
REASON FOR ADMISSION: Admitted for cycle 1 R-CHOP chemotherapy for DLBCL.
|
||||
HOSPITAL COURSE: Chemotherapy administered per protocol. Tolerated well. No acute chemotherapy-related adverse events. Watch for reactions.
|
||||
DISCHARGE MEDICATIONS:
|
||||
1. T. Prednisolone 100mg PO daily x 5 days
|
||||
2. T. Ondansetron 8mg PO BD PRN
|
||||
3. Syp. Cremaffin 15ml at bedtime
|
||||
4. T. Pantoprazole 40mg PO OD
|
||||
FOLLOW UP: Review in OPD after 14 days.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="reg-case-dlbcl-full")
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code == "C83.30"
|
||||
assert len(res.secondary_diagnoses) == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_case_uti_managed_t2dm():
|
||||
"""UTI (N39.0) Primary, actively managed pre-existing T2DM (E11.9) Secondary."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Dysuria and fever.
|
||||
PRINCIPAL DIAGNOSIS: Urinary tract infection.
|
||||
PAST MEDICAL HISTORY: Type 2 diabetes mellitus.
|
||||
HOSPITAL COURSE: Patient presented with acute dysuria and fever. Urine culture grew E. coli sensitive to ceftriaxone, which was administered with clinical improvement. The patient's pre-existing Type 2 diabetes was actively managed with blood glucose monitoring and sliding scale regular insulin.
|
||||
DISCHARGE MEDICATIONS: Oral cefixime, home metformin resumed.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="reg-case-uti")
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code == "N39.0"
|
||||
sec_codes = {s.code for s in res.secondary_diagnoses}
|
||||
assert "E11.9" in sec_codes
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_case_compound_urology():
|
||||
"""Compound urology: N10 (Primary), N20.0, R65.21, R78.81 (Secondaries)."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: High fevers and right flank pain.
|
||||
PRINCIPAL DIAGNOSIS:
|
||||
Acute pyelonephritis with right renal calculus, complicated by septic shock and E. coli bacteremia.
|
||||
HOSPITAL COURSE: Patient presented with severe acute pyelonephritis and obstructive right renal calculus. Developed septic shock requiring vasopressors and IV fluids. Blood cultures grew Escherichia coli (E. coli bacteremia) treated with IV meropenem. Urology placed DJ stent for right renal calculus.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="reg-case-compound")
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code == "N10"
|
||||
sec_codes = {s.code for s in res.secondary_diagnoses}
|
||||
assert "N20.0" in sec_codes
|
||||
assert "R65.21" in sec_codes
|
||||
assert "R78.81" in sec_codes
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_case_castleman_oncology():
|
||||
"""Castleman: D47.Z2 (Primary), Kaposi (C46.0/C46.9), HIV (B20), HBV (B18.1)."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
PATIENT NAME: [Redacted]
|
||||
CHIEF COMPLAINT: Generalized lymphadenopathy, fever, and cutaneous lesions.
|
||||
PRINCIPAL DIAGNOSIS:
|
||||
Multicentric Castleman disease.
|
||||
SECONDARY DIAGNOSES:
|
||||
1. Kaposi's sarcoma of skin.
|
||||
2. Human immunodeficiency virus [HIV] disease.
|
||||
3. Chronic viral hepatitis B without delta-agent.
|
||||
HOSPITAL COURSE: Patient with confirmed HIV infection on antiretroviral therapy presented with diffuse lymphadenopathy and hyperinflammatory symptoms. Lymph node biopsy confirmed multicentric Castleman disease (plasma cell variant). Skin lesions were biopsied confirming Kaposi's sarcoma. Serologies confirmed chronic viral hepatitis B without delta-agent. Siltuximab therapy initiated for Castleman disease alongside ongoing HAART. Stable at discharge.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="reg-case-castleman")
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code == "D47.Z2"
|
||||
sec_codes = {s.code for s in res.secondary_diagnoses}
|
||||
assert "C46.0" in sec_codes or "C46.9" in sec_codes
|
||||
assert "B20" in sec_codes
|
||||
assert "B18.1" in sec_codes
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_case_orthopedic_multiple_fractures():
|
||||
"""Case H: Orthopedic Multiple Fractures & Sprains (atomic decomposition)."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Left ankle and foot pain and swelling following mechanical fall.
|
||||
PRINCIPAL DIAGNOSIS:
|
||||
Multiple fractures of left lateral malleolus, tarsals and fifth metatarsal with deltoid and calcaneofibular ligament sprains.
|
||||
PHYSICAL EXAMINATION:
|
||||
Classification of Fracture: Not Applicable
|
||||
Left foot: Severe swelling, ecchymosis, tenderness over lateral malleolus and base of fifth metatarsal.
|
||||
HOSPITAL COURSE: Patient presented following a fall resulting in left lateral malleolus fracture, left tarsal fracture, and left fifth metatarsal fracture. There is no displacement or dislocation noted on radiographs; nondisplaced fractures treated non-operatively with posterior splinting. Patient also sustained left deltoid and calcaneofibular ligament sprains.
|
||||
DISCHARGE MEDICATIONS: Acetaminophen 500mg PO TID PRN.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="reg-case-ortho")
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code == "S82.65XA"
|
||||
sec_codes = {s.code for s in res.secondary_diagnoses}
|
||||
assert "S92.202A" in sec_codes
|
||||
assert "S92.355A" in sec_codes
|
||||
assert "S93.422A" in sec_codes
|
||||
assert "S93.412A" in sec_codes
|
||||
# Verify no metadata or isolated anatomy leakage
|
||||
all_codes_and_terms = [res.primary_diagnosis.description] + [s.description for s in res.secondary_diagnoses]
|
||||
assert not any("classification" in t.lower() for t in all_codes_and_terms)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_case_metastatic_breast_cancer():
|
||||
"""Case I: Metastatic Breast Cancer with Pleural Metastasis and Biomarker Attributes."""
|
||||
doc = """
|
||||
HOSPITAL DISCHARGE SUMMARY
|
||||
PRINCIPAL DIAGNOSIS:
|
||||
Metastatic breast cancer, Stage IV.
|
||||
SECONDARY DIAGNOSES:
|
||||
1. Pleural metastasis.
|
||||
BIOMARKERS & RECEPTOR STATUS:
|
||||
Triple negative (ER negative, PR negative, HER2 0 by IHC).
|
||||
BRCA pathogenic mutation (BRCA1 positive).
|
||||
PD-L1 positive (CPS >= 10).
|
||||
Grade III histology.
|
||||
HOSPITAL COURSE: Patient with known metastatic breast cancer presented for restaging and systemic therapy adjustment. CT chest confirmed progressive malignant pleural metastasis secondary to breast carcinoma. Thoracentesis performed. Started on chemotherapy regimen.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="reg-case-breast")
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code == "C50.919"
|
||||
sec_codes = {s.code for s in res.secondary_diagnoses}
|
||||
assert "C78.2" in sec_codes
|
||||
# Verify biomarkers are not separate diagnoses
|
||||
all_terms = [s.description.lower() for s in res.secondary_diagnoses]
|
||||
assert not any("triple negative" in t for t in all_terms)
|
||||
assert not any("brca" in t for t in all_terms)
|
||||
assert not any("pd-l1" in t for t in all_terms)
|
||||
@@ -0,0 +1,166 @@
|
||||
"""Tests for generalized clinical reasoning principles, adversarial variations, and unseen conditions.
|
||||
|
||||
Tests:
|
||||
1. Assertion & Negation: Ruled out / negative conditions must never become active diagnoses.
|
||||
2. Temporality: Historical/resolved conditions must not be primary.
|
||||
3. Source Authority: Medication-only mentions must not manufacture diagnoses.
|
||||
4. CMS Guideline I.B.4: Integral symptoms must not be separate billable secondaries when primary is definitive.
|
||||
5. Specificity & Reverse Attributes: Unsupported attributes must be rejected.
|
||||
6. Neoplasm / Histology Attribute Separation (Section 10): Roman staging/markers separated from concept.
|
||||
7. Unseen Clinical Entities: System correctly reasons over novel diseases without hardcoded lists.
|
||||
"""
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from medical_coding.agents.classifier import PrimarySecondaryClassifier
|
||||
from medical_coding.agents.clinical_extractor import EvidenceFirstFactExtractor
|
||||
from medical_coding.schemas.clinical import ContextAssessment
|
||||
from medical_coding.schemas.enums import (
|
||||
Certainty,
|
||||
ConditionStatus,
|
||||
Temporality,
|
||||
)
|
||||
from medical_coding.validation.clinical_gate import HardClinicalCandidateGate
|
||||
from medical_coding.validation.reverse_attributes import ReverseAttributeChecker
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def extractor():
|
||||
return EvidenceFirstFactExtractor()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def classifier():
|
||||
return PrimarySecondaryClassifier(MagicMock())
|
||||
|
||||
|
||||
class TestAssertionAndNegation:
|
||||
"""Principles: Ruled out and negative statements must not become billable diagnoses."""
|
||||
|
||||
def test_ruled_out_condition_rejected(self, extractor):
|
||||
note = """
|
||||
CHIEF COMPLAINT: Right lower quadrant pain.
|
||||
HOSPITAL COURSE:
|
||||
Acute appendicitis was considered but ruled out after normal abdominal ultrasound.
|
||||
Patient was diagnosed with mesenteric adenitis.
|
||||
DISCHARGE DIAGNOSIS:
|
||||
Mesenteric adenitis.
|
||||
"""
|
||||
state = extractor.extract_clinical_state(note, "DOC-ADV-1")
|
||||
appendicitis_cands = [c for c in state.all_candidates if "appendicitis" in c.normalized_diagnosis.lower()]
|
||||
for c in appendicitis_cands:
|
||||
assert c.scores.contradiction_penalty > 0 or not c.is_authorized or c.certainty == Certainty.RULED_OUT
|
||||
|
||||
def test_negative_screening_statement(self, extractor):
|
||||
note = """
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Acute gastroenteritis.
|
||||
2. No evidence of active gastrointestinal bleeding or perforation.
|
||||
"""
|
||||
state = extractor.extract_clinical_state(note, "DOC-ADV-2")
|
||||
active_bleed = [c for c in state.all_candidates if "bleeding" in c.normalized_diagnosis.lower() or "perforation" in c.normalized_diagnosis.lower()]
|
||||
for c in active_bleed:
|
||||
assert not c.is_authorized or c.certainty in (Certainty.RULED_OUT, Certainty.NEGATED)
|
||||
|
||||
|
||||
class TestMedicationContaminationPrinciple:
|
||||
"""Principle: Medication lists alone must never manufacture diagnoses."""
|
||||
|
||||
def test_medication_candidate_gate_rejection(self):
|
||||
# A medication name or instruction alone should not pass the clinical candidate gate
|
||||
is_valid, reason = HardClinicalCandidateGate.evaluate_candidate(
|
||||
"Cough lozenges",
|
||||
"Discharge Medications: Cough lozenges PRN for throat tickle"
|
||||
)
|
||||
assert not is_valid
|
||||
assert "pharmaceutical" in reason.lower() or "medication" in reason.lower()
|
||||
|
||||
def test_laxative_does_not_create_constipation_diagnosis(self):
|
||||
is_valid, _ = HardClinicalCandidateGate.evaluate_candidate(
|
||||
"Laxative syrup",
|
||||
"Take laxative syrup 15ml at bedtime"
|
||||
)
|
||||
assert not is_valid
|
||||
|
||||
|
||||
class TestSymptomIntegralExclusionPrinciple:
|
||||
"""Principle (CMS Guideline I.B.4): Integral symptoms must not be separate secondaries when primary is definitive."""
|
||||
|
||||
def test_cholecystitis_with_abdominal_pain(self, classifier):
|
||||
primary_asm = ContextAssessment(
|
||||
condition_id="chole-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="Condition occasioning admission treated surgically.",
|
||||
treated_or_managed=True,
|
||||
influenced_treatment=True,
|
||||
treatment_evidence="Laparoscopic cholecystectomy performed",
|
||||
)
|
||||
symptom_asm = ContextAssessment(
|
||||
condition_id="pain-01",
|
||||
diagnosis="Right upper quadrant abdominal pain",
|
||||
current_relevance=True,
|
||||
coding_candidate=True,
|
||||
status=ConditionStatus.ACUTE,
|
||||
certainty=Certainty.CONFIRMED,
|
||||
temporality=Temporality.CURRENT,
|
||||
evidence="Patient presented with severe right upper quadrant abdominal pain.",
|
||||
reason="Presenting symptom of acute cholecystitis.",
|
||||
treated_or_managed=False,
|
||||
)
|
||||
|
||||
result, _ = classifier.classify_conditions(
|
||||
[primary_asm, symptom_asm],
|
||||
clinical_text="Admitted for acute cholecystitis, presenting with right upper quadrant abdominal pain. Laparoscopic cholecystectomy performed.",
|
||||
)
|
||||
assert result.has_unique_primary is True
|
||||
assert result.primary_diagnosis is not None
|
||||
assert "cholecystitis" in result.primary_diagnosis.diagnosis.lower()
|
||||
|
||||
# The symptom should be excluded under CMS Guideline I.B.4
|
||||
excluded_pain = [c for c in result.excluded_conditions if "pain" in c.diagnosis.lower()]
|
||||
secondaries_pain = [c for c in result.secondary_diagnoses if "pain" in c.diagnosis.lower()]
|
||||
assert len(excluded_pain) == 1 or len(secondaries_pain) == 0
|
||||
|
||||
|
||||
class TestNeoplasmAttributeSeparation:
|
||||
"""Principle (Section 10): Roman numeral stages and molecular markers are attributes, not distinct concepts."""
|
||||
|
||||
def test_mantle_cell_lymphoma_staging(self, extractor):
|
||||
concept, attrs = extractor._extract_concept_and_attributes("Mantle cell lymphoma, Stage IV, blastoid variant")
|
||||
assert concept == "Mantle cell lymphoma, blastoid variant"
|
||||
assert attrs.get("oncologic_stage") == "Stage IV"
|
||||
|
||||
def test_ckd_stage_is_preserved_as_concept(self, extractor):
|
||||
concept, attrs = extractor._extract_concept_and_attributes("Chronic kidney disease stage 3")
|
||||
assert "stage 3" in concept.lower()
|
||||
assert "oncologic_stage" not in attrs
|
||||
|
||||
|
||||
class TestReverseAttributeValidation:
|
||||
"""Principle: Code Specificity <= Evidence Specificity. Never infer unmentioned complications."""
|
||||
|
||||
def test_unsupported_hemorrhage_rejected(self):
|
||||
is_valid, missing = ReverseAttributeChecker.validate_code_attributes(
|
||||
code_description="Gastric ulcer, chronic or unspecified, with hemorrhage",
|
||||
evidence_text="Patient has history of chronic gastric ulcer confirmed on endoscopy.",
|
||||
diagnosis_term="chronic gastric ulcer",
|
||||
)
|
||||
assert not is_valid
|
||||
assert any("bleed" in m or "hemorrhage" in m for m in missing)
|
||||
|
||||
def test_supported_laterality_accepted(self):
|
||||
is_valid, missing = ReverseAttributeChecker.validate_code_attributes(
|
||||
code_description="Calculus of ureter, right",
|
||||
evidence_text="CT abdomen revealed 6mm stone in the right distal ureter.",
|
||||
diagnosis_term="Right ureteric calculus",
|
||||
)
|
||||
assert is_valid
|
||||
assert len(missing) == 0
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Comprehensive regression tests verifying database-authoritative ICD code matching."""
|
||||
|
||||
import pytest
|
||||
|
||||
from medical_coding.graph.pipeline import process_clinical_document
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_regression_right_ureteric_calculus_matches_n20_1() -> None:
|
||||
"""Right ureteric calculus must match N20.1 Calculus of ureter, not symptom N23 or N20.2."""
|
||||
doc = """
|
||||
DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Severe acute flank pain.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Right ureteric calculus. CT abdomen demonstrated a 5 mm stone in the right distal ureter with renal colic. Managed conservatively with tamsulosin.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="doc-reg-ureteric")
|
||||
assert res is not None
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code == "N20.1"
|
||||
assert "ureter" in res.primary_diagnosis.description.lower()
|
||||
assert res.primary_diagnosis.matching_status == "MATCHED"
|
||||
assert res.primary_diagnosis.database_code == "N20.1"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_regression_chronic_gastritis_no_bleeding_matches_k29_50() -> None:
|
||||
"""Chronic gastritis with 'no active bleeding' must match K29.50 without bleeding, not K29.51 or K29.41."""
|
||||
doc = """
|
||||
DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Epigastric discomfort.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Chronic gastritis. Upper endoscopy confirmed chronic antral gastritis. No active bleeding or ulceration noted.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="doc-reg-gastritis")
|
||||
assert res is not None
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code == "K29.50"
|
||||
assert "without bleeding" in res.primary_diagnosis.description.lower()
|
||||
assert res.primary_diagnosis.matching_status == "MATCHED"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_regression_general_heart_failure_matches_i50_9() -> None:
|
||||
"""General heart failure without subtype must match I50.9, not I50.20, I50.21, or I50.89."""
|
||||
doc = """
|
||||
DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Shortness of breath and peripheral edema.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Heart failure. Patient monitored on oral diuretics with symptom stabilization.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="doc-reg-hf")
|
||||
assert res is not None
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code in ("I50.9", "I50")
|
||||
assert res.primary_diagnosis.code != "I50.21"
|
||||
assert res.primary_diagnosis.code != "I50.89"
|
||||
assert res.primary_diagnosis.matching_status == "MATCHED"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_regression_general_chest_pain_matches_r07_9() -> None:
|
||||
"""General chest pain without pleuritic/breathing features must match R07.9, not R07.1."""
|
||||
doc = """
|
||||
DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Chest discomfort.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Chest pain, atypical. Cardiac enzymes and ECG were negative for acute ischemia.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="doc-reg-cp")
|
||||
assert res is not None
|
||||
assert res.primary_diagnosis.code in ("R07.9", "R07.4")
|
||||
assert "chest pain" in res.primary_diagnosis.description.lower()
|
||||
assert res.primary_diagnosis.matching_status == "MATCHED"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_regression_suspected_pneumonia_matches_j18_9() -> None:
|
||||
"""Suspected pneumonia without pathogen must match J18.9, not organism-specific B77.81 or J16.0."""
|
||||
doc = """
|
||||
DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Productive cough and fever.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Community-acquired pneumonia. Chest X-ray showed right lower lobe consolidation. Sputum cultures pending.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="doc-reg-pna")
|
||||
assert res is not None
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code == "J18.9"
|
||||
assert res.primary_diagnosis.matching_status == "MATCHED"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_regression_right_flank_pain_matches_r10_a1() -> None:
|
||||
"""Right flank pain must match R10.A1 right side, never R10.A3 bilateral."""
|
||||
doc = """
|
||||
DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Severe pain.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Right flank pain. Evaluated by urology with resolution of symptoms.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="doc-reg-flank")
|
||||
assert res is not None
|
||||
assert res.primary_diagnosis is not None
|
||||
assert res.primary_diagnosis.code == "R10.A1"
|
||||
assert "right" in res.primary_diagnosis.description.lower()
|
||||
assert res.primary_diagnosis.matching_status == "MATCHED"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_regression_ruled_out_condition_abstains() -> None:
|
||||
"""Ruled out condition must abstain with NO_DATABASE_MATCH."""
|
||||
doc = """
|
||||
DISCHARGE SUMMARY
|
||||
CHIEF COMPLAINT: Right lower quadrant pain.
|
||||
DISCHARGE DIAGNOSES:
|
||||
1. Acute appendicitis ruled out by ultrasound. Mesenteric adenitis managed conservatively.
|
||||
"""
|
||||
res = await process_clinical_document(source=doc, document_id="doc-reg-ruled-out")
|
||||
assert res is not None
|
||||
if res.primary_diagnosis and "appendicitis" in res.primary_diagnosis.raw_term.lower():
|
||||
assert res.primary_diagnosis.code is None
|
||||
assert res.primary_diagnosis.matching_status == "NO_DATABASE_MATCH"
|
||||
appendicitis_abstentions = [
|
||||
a for a in res.abstentions if "appendicitis" in (a.raw_term or "").lower()
|
||||
]
|
||||
assert len(appendicitis_abstentions) > 0 or (
|
||||
res.primary_diagnosis and "adenitis" in res.primary_diagnosis.raw_term.lower()
|
||||
)
|
||||
Reference in New Issue
Block a user