Files
stack/tests/aco/test_load_bcda.py
kert 52ebad29cd
Some checks failed
CI / lint (push) Successful in 31s
CI / test (push) Failing after 2m16s
Infra CI / notebooks (push) Successful in 53s
Infra CI / docs (push) Successful in 1m30s
Infra CI / api (push) Successful in 1m0s
Infra CI / mc (push) Failing after 32s
Infra CI / llm (push) Successful in 47s
CI / notebooks-smoke (push) Successful in 1m40s
Infra CI / zotero (push) Successful in 16s
CI / lint (pull_request) Successful in 47s
Infra CI / zotero (pull_request) Successful in 14s
Infra CI / docs (pull_request) Successful in 19s
Infra CI / notebooks (pull_request) Successful in 56s
Infra CI / api (pull_request) Successful in 16s
CI / notebooks-smoke (pull_request) Successful in 1m33s
CI / test (pull_request) Failing after 2m35s
Infra CI / mc (pull_request) Failing after 32s
Infra CI / llm (pull_request) Successful in 14s
feat(bcda): rewrite the input_layer connector for v3 semantics
The connector (bcda.express.cclf / bcda.pipe.cclf) still routed on the v2
near-line RIC code, read v2-only amount columns, and had never run end to
end: its contracts named CCLF columns the EOB table does not have, so the
runner's exact-match check would have refused every stage.

One header stage now carries the v3 semantics. _stg_claim_header drops
NotFinalAction claims (9% of the sandbox), derives claim_family from
EOB-TYPE → CLM-TYPE-CD → pde_id → RIC (v3 emits the RIC on only some
claims), collapses a claim seen in two sources on its claim control number
(NationalClaimsHistory/DDPS over SharedSystem, then newest last_updated;
rows without a control number are never collapsed) and resolves the MBI.
The four family stages are filters on it.

One mapping produces input_layer.medical_claim for institutional, carrier
and DME lines: admission/discharge from the C4BB admission period, NUBC
type of bill (new clm_bill_type_cd on the EOB table; rebuilt as "0" + the
three-character v3 frequency code when the coding is missing — the v2
fac+clsfctn+freq concatenation yields "88787J" on v3), MS-DRG, revenue
centre, HCPCS + modifiers, attending→operating→rendering / rendering /
rendering→ordering NPIs, billing Organization NPI and tax number,
paid/allowed/charge/coinsurance/deductible from the consolidated v3
Adjudication amounts, paid date from clm_pd_dt → NCH weekly → CMS process.
Part D uses the PDE id, prescribing care-team NPI, contained pharmacy NPI,
NDC quantity, total drug cost as charge and paid-by-patient as copayment.
Eligibility reads the Part A row (Part B fallback) for status, entitlement
and enrollment, the Dual row for dual status, and accepts both CCW sex
codes and the FHIR words the v2 flattener passed through.

Contracts inherit: header stages subclass ExplanationOfBenefit, outputs
subclass aco.table.input_layer.InputLayer*, so downstream pipelines run on
BCDA output exactly as on CCLF output. load_bcda(run_pipeline=True),
stack load bcda --run-pipeline and stack run bcda land input_layer.*.

Large-entity sandbox pull: 221,021 medical lines on 28,282 claims (equal to
the FinalAction non-PDE EOBs by type), 11,968 pharmacy rows, 9,582
eligibility rows; all 16 reconciliation checks in the notebook pass. Tests
run the whole connector on CMS's official v3 samples through DuckDB.

refs #1139
2026-10-25 13:42:24 -04:00

143 lines
4.8 KiB
Python

"""Tests for BCDA data loading."""
from __future__ import annotations
from pathlib import Path
import pytest
from aco.load.bcda import _find_latest_export
class TestFindLatestExport:
def test_no_exports_dir_raises(self, tmp_path: Path) -> None:
with pytest.raises(FileNotFoundError, match="No exports directory"):
_find_latest_export(tmp_path)
def test_empty_exports_dir_raises(self, tmp_path: Path) -> None:
(tmp_path / "exports").mkdir()
with pytest.raises(FileNotFoundError, match="No export directories"):
_find_latest_export(tmp_path)
def test_finds_latest(self, tmp_path: Path) -> None:
import os
exports = tmp_path / "exports"
exports.mkdir()
(exports / "old_job").mkdir()
(exports / "new_job").mkdir()
# Set old_job mtime to past so new_job is clearly newer
os.utime(exports / "old_job", (1000000, 1000000))
result = _find_latest_export(tmp_path)
assert [d.name for d in result] == ["new_job"]
def test_newest_per_resource_type(self, tmp_path: Path) -> None:
"""Three single-type v3 jobs: each type comes from its own dir."""
import os
exports = tmp_path / "exports"
exports.mkdir()
for i, (name, rtype) in enumerate(
[
("j_eob", "ExplanationOfBenefit"),
("j_pat", "Patient"),
("j_cov", "Coverage"),
]
):
d = exports / name
d.mkdir()
(d / f"{rtype}.ndjson").write_text("{}\n")
os.utime(d, (1000000 + i, 1000000 + i))
# a newer Patient-only job supersedes j_pat
d = exports / "j_pat2"
d.mkdir()
(d / "Patient.ndjson").write_text("{}\n")
os.utime(d, (2000000, 2000000))
result = _find_latest_export(tmp_path)
assert [d.name for d in result] == ["j_eob", "j_cov", "j_pat2"]
class TestLoadV3EndToEnd:
"""Official v3 samples, split like three single-type jobs → DuckDB."""
def test_load_from_three_export_dirs(self, tmp_path: Path) -> None:
import shutil
import duckdb
from aco.load.bcda import load_bcda
from conf import path as conf_path
samples = Path(__file__).resolve().parents[2] / "dev" / "vendor" / "bcda-site"
store = tmp_path / "store"
for job, rtype in (
("j1", "Patient"),
("j2", "Coverage"),
("j3", "ExplanationOfBenefit"),
):
d = store / "exports" / job
d.mkdir(parents=True)
shutil.copy(samples / f"v3_{rtype}.ndjson", d / f"{rtype}.ndjson")
# a second EOB part in the same job dir
shutil.copy(
samples / "v3_ExplanationOfBenefit.ndjson",
store / "exports" / "j3" / "ExplanationOfBenefit.1.ndjson",
)
db = tmp_path / "aco.duckdb"
from unittest.mock import patch
real_path = conf_path
def fake_path(key: str):
if key == "storage.bcda":
return store
return real_path(key)
with patch("conf.path", side_effect=fake_path):
stats = load_bcda(database=str(db), run_pipeline=True)
assert stats == {
"bcda.patient": 94,
"bcda.explanation_of_benefit": 538,
"bcda.eob_item": 2464,
"bcda.coverage": 175,
# the connector pipeline ran and landed input_layer.*; the
# duplicated EOB part collapses on claim control number
"input_layer.medical_claim": 1021,
"input_layer.pharmacy_claim": 102,
"input_layer.eligibility": 94,
}
con = duckdb.connect(str(db), read_only=True)
plans = dict(
con.execute(
"select class_plan, count(*) from bcda.coverage group by 1"
).fetchall()
)
assert set(plans) == {"Part A", "Part B", "Part C", "Dual Medicare/Medicaid"}
sys_types = dict(
con.execute(
"select system_type, count(*) from bcda.explanation_of_benefit group by 1"
).fetchall()
)
assert sys_types == {"NationalClaimsHistory": 282, "DDPS": 256}
assert (
con.execute(
"select count(*) from bcda.patient where bene_mbi_id is null"
).fetchone()[0]
== 0
)
assert (
con.execute(
"select count(distinct claim_id) from input_layer.medical_claim"
).fetchone()[0]
== 131
)
assert (
con.execute(
"select count(*) from input_layer.medical_claim "
"where claim_type = 'institutional' and length(bill_type_code) <> 4"
).fetchone()[0]
== 0
)
con.close()