Files
stack/tests/pay/test_bounds.py
kert 1aa288c344
Some checks failed
CI / lint (push) Failing after 48s
CI / notebooks-smoke (push) Successful in 2m0s
Deploy / changes (push) Successful in 18s
CI / test (push) Successful in 4m23s
Infra CI / notebooks (push) Successful in 1m5s
Infra CI / zotero (push) Successful in 16s
Infra CI / docs (push) Successful in 19s
Infra CI / api (push) Successful in 1m19s
Infra CI / bcda (push) Successful in 1m48s
Infra CI / mc (push) Successful in 18s
Infra CI / llm (push) Successful in 56s
Deploy / notebooks (push) Has been skipped
Deploy / zotero (push) Has been skipped
Deploy / docs (push) Has been skipped
Deploy / api (push) Successful in 2m34s
Lean Pay / pay (push) Successful in 3m22s
Deploy / llm (push) Successful in 1m43s
Deploy / mc (push) Has been skipped
Deploy / bcda (push) Successful in 2m10s
Deploy / report (push) Successful in 16s
feat(pay): load the published numbers the fence was missing
The wage index, pass-through rates, the missing APC years, the CY2027
work GPCI, equipment usage, IPPS standardized amounts, MS-DRG weights,
and the MSSP and REACH financial results now come from the CMS files.
The snapshot records those observed ranges. Maintenance stays the
published 5/100. There is still no IPPS or LEAD pricer.
2026-11-17 17:04:51 -05:00

688 lines
25 KiB
Python

"""The payment fence names every rule field and stays inside the data.
Published points come from the rule registries. Observed rows come from
the replica, one period at a time. ``allows`` rejects a search point
that the formulas cannot actually take.
"""
from __future__ import annotations
import inspect
from fractions import Fraction
from pathlib import Path
import duckdb
import pytest
from pydantic import BaseModel
from opps.calcs.payment import payment as opps_payment
from opps.rules import RULES as OPPS_RULES
from opps.table.addendum_b import AddendumB
from opps.table.apc_weight import ApcWeight
from opps.table.pass_through import PassThrough
from opps.table.payment import OppsAdjustedPayment, OppsSkinSubImpact
from opps.table.wage_index import WageIndex
from pay import bounds
from pfs.calcs.payment import (
LIMITING_CHARGE_FACTOR,
NON_PAR_MARKUP,
PAR_REDUCTION,
mppr_reduction,
)
from pfs.rules import PROPOSED
from pfs.rules import RULES as PFS_RULES
from pfs.table.equipment import MedicalEquipment
from pfs.table.gpci import Gpci
from pfs.table.rvu import Rvu
from qpp import QPP
ROOT = Path(__file__).resolve().parents[2]
DEFS = (ROOT / "lean" / "Pay" / "Pay" / "Defs.lean").read_text()
CASES = (ROOT / "lean" / "Pay" / "Pay" / "Cases.lean").read_text()
def index(doc: dict) -> dict[tuple[str, str, str], dict]:
found: dict[tuple[str, str, str], dict] = {}
for row in doc["elements"]:
key = (row["item"], row["name"], row["period"])
assert key not in found, key
found[key] = row
return found
def scalar_paths(obj: BaseModel, prefix: str = ""):
"""Every numeric, bool, and categorical field, including a null."""
for fname, field in type(obj).model_fields.items():
ann = bounds._peel(field.annotation)
path = f"{prefix}.{fname}" if prefix else fname
value = getattr(obj, fname)
if bounds._is_model(ann):
if value is None:
yield path
else:
yield from scalar_paths(value, path)
continue
if bounds._is_model_list(ann):
for piece in value or []:
yield from scalar_paths(piece, path)
continue
if ann is bool or ann in (int, float) or fname in bounds.CATEGORICAL:
yield path
def test_the_walker_names_every_scalar_on_the_rule_models() -> None:
produced: dict[tuple[str, str], set[str]] = {}
for row in bounds.registry_rows():
produced.setdefault((row["item"], row["period"]), set()).add(row["name"])
def assert_year(item: str, year: int, obj: BaseModel) -> None:
for path in scalar_paths(obj):
if path.startswith("cf_segments"):
periods = [
period
for (got_item, period), names in produced.items()
if got_item == item
and path in names
and period.startswith(f"{year}-")
]
assert periods, (item, year, path)
else:
assert path in produced[item, str(year)], (item, year, path)
for year, rule in PFS_RULES.items():
assert_year("pfs.rules.RuleYear", year, rule)
segments = [
period
for (item, period), names in produced.items()
if item == "pfs.rules.RuleYear"
and "cf_segments.cf" in names
and period.startswith(f"{year}-")
]
assert len(segments) == len(rule.cf_segments)
for year, rule in PROPOSED.items():
assert_year("pfs.rules.ProposedRule", year, rule)
for year, rule in OPPS_RULES.items():
assert_year("opps.rules.RuleYear", year, rule)
for year, rule in QPP.items():
assert_year("qpp.QppYear", year, rule)
if not PROPOSED:
assert "pfs.rules.ProposedRule" not in {item for item, _ in produced}
def test_prose_fields_are_not_search_dimensions() -> None:
names = {row["name"] for row in bounds.registry_rows()}
assert "citation" not in names
assert "notes" not in names
assert "federal_register_citation" not in names
assert "proposed.changes" not in names
assert "skin_sub_new_codes" not in names
def test_the_snapshot_matches_the_registries_and_the_constants() -> None:
snap = index(bounds.load())
expect = [
*bounds.registry_rows(),
*bounds.constant_rows(),
*bounds.ceiling_rows(),
*bounds.hole_rows(),
]
for row in expect:
got = snap[row["item"], row["name"], row["period"]]
assert got["kind"] == row["kind"]
assert got["role"] == row["role"]
assert got["low"] == row["low"]
assert got["high"] == row["high"]
assert got["value"] == row["value"]
assert got["note"] == row["note"]
assert got["integer"] == row["integer"]
def test_the_snapshot_file_is_canonical() -> None:
text = bounds.SNAPSHOT.read_text()
assert text == bounds.canonical(bounds.load())
assert bounds.load()["schema"] == 1
def test_lean_constants_match_the_definitions() -> None:
assert "def parReduction : Rat := 5 / 100" in DEFS
assert "def nonParMarkup : Rat := 15 / 100" in DEFS
assert "def aspAddOn : Rat := 6 / 100" in DEFS
assert "def reachQualityWithhold : Rat := 2 / 100" in DEFS
assert (
"def paymentYear (performanceYear : Nat) : Nat := performanceYear + 2" in DEFS
)
assert "oppsAdjusted 80 1 (3 / 5)" in CASES
assert "equipmentCostPerMinute 1000 5 10000 0" in CASES
assert "mpprPe 4 2 (1 / 2)" in CASES
by_name = {row["name"]: row for row in bounds.constant_rows()}
assert by_name["parReduction"]["value"] == "5/100"
assert by_name["limitingChargeFactor"]["value"] == "10925/10000"
assert Fraction(10925, 10000) == (1 - Fraction(5, 100)) * (1 + Fraction(15, 100))
assert by_name["laborShare"]["value"] == "3/5"
assert by_name["passThroughDrugs"]["value"] == "106/100"
assert Fraction(by_name["passThroughDrugs"]["value"]) == 1 + Fraction(6, 100)
assert by_name["missingWageIndex"]["value"] == "1/1"
assert by_name["maintenanceDefault"]["value"] == "0/1"
assert by_name["maintenanceFactor"]["value"] == "5/100"
assert by_name["maintenanceFactor"]["low"] == bounds.num(0.05)
assert by_name["mpprReduction"]["value"] == "1/2"
assert by_name["paymentYearOffset"]["value"] == "2/1"
assert bounds.num(PAR_REDUCTION) == by_name["parReduction"]["low"]
assert bounds.num(NON_PAR_MARKUP) == by_name["nonParMarkup"]["low"]
assert bounds.num(LIMITING_CHARGE_FACTOR) == by_name["limitingChargeFactor"]["low"]
assert inspect.signature(mppr_reduction).parameters["reduction_pct"].default == 0.50
assert inspect.signature(opps_payment).parameters["labor_share"].default == 0.60
def test_payment_year_is_performance_year_plus_two() -> None:
snap = index(bounds.load())
for year, rule in QPP.items():
assert rule.payment_year == year + 2
got = snap["qpp.QppYear", "payment_year", str(year)]
perf = snap["qpp.QppYear", "performance_year", str(year)]
assert int(got["value"]) == int(perf["value"]) + 2
assert bounds.allows("lean", "paymentYearOffset", 2)
assert not bounds.allows("lean", "paymentYearOffset", 1)
def test_a_null_benchmark_stays_null() -> None:
snap = index(bounds.load())
for year in QPP:
row = snap[
"qpp.QppYear",
"risk_standards.benchmark_nominal_pct",
str(year),
]
assert row["kind"] == "unstated"
assert row["value"] is None
assert row["low"] is None
assert "Do not impute" in row["note"]
assert not bounds.allows(
"qpp.QppYear",
"risk_standards.benchmark_nominal_pct",
8,
period=year,
)
assert not bounds.allows(
"qpp.QppYear",
"risk_standards.benchmark_nominal_pct",
0,
period=year,
)
def test_proposed_numbers_are_not_payment_values() -> None:
assert not bounds.allows(
"pfs.rules.RuleYear",
"proposed.conversion_factor",
PFS_RULES[2026].proposed.conversion_factor,
period=2026,
)
assert bounds.allows(
"pfs.rules.RuleYear",
"conversion_factor",
PFS_RULES[2026].conversion_factor,
period=2026,
)
assert not bounds.allows(
"pfs.rules.RuleYear",
"conversion_factor",
PFS_RULES[2026].proposed.conversion_factor,
period=2026,
)
assert not bounds.allows(
"pfs.rules.RuleYear", "conversion_factor", PFS_RULES[2026].conversion_factor
)
def test_the_budget_neutrality_adjustor_is_not_a_second_multiplier() -> None:
snap = index(bounds.load())
row = snap["pfs.rules.RuleYear", "budget_neutrality_adjustor", "2026"]
assert row["role"] == "informational"
assert "Do not multiply" in row["note"]
assert bounds.allows(
"pfs.rules.RuleYear",
"budget_neutrality_adjustor",
PFS_RULES[2026].budget_neutrality_adjustor,
period=2026,
)
assert not bounds.allows(
"pfs.rules.RuleYear", "budget_neutrality_adjustor", 1, period=2026
)
def test_a_single_cf_segment_matches_the_year_and_splits_stay_split() -> None:
snap = index(bounds.load())
for year, rule in PFS_RULES.items():
assert rule.cf_segments
for seg in rule.cf_segments:
period = f"{seg.start.isoformat()}/{seg.end.isoformat()}"
row = snap["pfs.rules.RuleYear", "cf_segments.cf", period]
assert row["value"] == bounds.num(seg.cf)
assert bounds.allows(
"pfs.rules.RuleYear", "cf_segments.cf", seg.cf, period=period
)
if len(rule.cf_segments) == 1:
period = (
f"{rule.cf_segments[0].start.isoformat()}"
f"/{rule.cf_segments[0].end.isoformat()}"
)
assert (
snap["pfs.rules.RuleYear", "cf_segments.cf", period]["value"]
== snap["pfs.rules.RuleYear", "conversion_factor", str(year)]["value"]
)
assert len(PFS_RULES[2015].cf_segments) == 2
assert len(PFS_RULES[2024].cf_segments) == 2
def test_published_flags_admit_only_the_stored_value() -> None:
assert bounds.allows(
"pfs.rules.RuleYear", "clinical_labor_rate_update", True, period=2022
)
assert not bounds.allows(
"pfs.rules.RuleYear", "clinical_labor_rate_update", False, period=2022
)
assert bounds.allows(
"pfs.rules.RuleYear", "clinical_labor_rate_update", False, period=2014
)
assert not bounds.allows(
"pfs.rules.RuleYear", "clinical_labor_rate_update", 1, period=2022
)
assert bounds.allows(
"opps.rules.RuleYear", "skin_sub_payment_method", "flat_rate", period=2026
)
assert not bounds.allows(
"opps.rules.RuleYear", "skin_sub_payment_method", "pass_through", period=2026
)
assert bounds.allows("lean.ceiling", "pfs", "formula")
assert bounds.allows("lean.ceiling", "ipps", "absent")
assert not bounds.allows("lean.ceiling", "ipps", "formula")
assert not bounds.allows("lean.ceiling", "pfs", 1)
def test_shared_defaults_match_every_published_year() -> None:
snap = index(bounds.load())
labor = {
row["low"] for row in bounds.constant_rows() if row["name"] == "laborShare"
}
drugs = {
row["low"]
for row in bounds.constant_rows()
if row["name"] == "passThroughDrugs"
}
half = {
row["low"] for row in bounds.constant_rows() if row["name"] == "mpprReduction"
}
for year in OPPS_RULES:
assert snap["opps.rules.RuleYear", "labor_share", str(year)]["value"] in labor
assert (
snap["opps.rules.RuleYear", "pass_through_drugs_pct", str(year)]["low"]
in drugs
)
for year in PFS_RULES:
for name in ("mppr_diagnostic_imaging_pct", "mppr_therapy_pct"):
assert snap["pfs.rules.RuleYear", name, str(year)]["low"] in half
def test_knobs_and_holes_reject_a_made_up_point() -> None:
assert bounds.allows("lead.tag", "confidence", 0)
assert bounds.allows("lead.tag", "confidence", 1)
assert bounds.allows("lead.tag", "confidence", 0.45)
assert not bounds.allows("lead.tag", "confidence", -0.01)
assert not bounds.allows("lead.tag", "confidence", 1.01)
assert bounds.allows("reach", "total_quality", 0.85)
assert not bounds.allows("reach", "total_quality", 1.01)
assert bounds.allows("pfs.mppr", "rank", 1)
assert bounds.allows("pfs.mppr", "rank", 4)
assert not bounds.allows("pfs.mppr", "rank", 0)
assert not bounds.allows("pfs.mppr", "rank", 1.5)
assert not bounds.allows("pfs.mppr", "rank", True)
assert bounds.allows("lean", "missingWageIndex", 1)
assert not bounds.allows("lean", "missingWageIndex", 1.05)
assert bounds.allows("lean", "maintenanceDefault", 0)
assert not bounds.allows("lean", "maintenanceDefault", 0.05)
assert bounds.allows("lean", "parReduction", Fraction(5, 100))
assert not bounds.allows("lean", "parReduction", 0.06)
for item, name, sample in (
("opps.wage_index", "wage_index", 1),
("opps.wage_index", "reclassified_wage_index", 1),
("pfs.medical_equipment", "maintenance_factor", 0),
("pfs.limiting_charge", "fee", 100),
("pfs.rvu", "conv_factor", 33.4),
("ipps", "payment", 1),
("lead", "pricer", 1),
("mssp", "settlement", 1),
("reach", "settlement", 1),
("opps.pass_through", "payment_rate", 10),
):
assert not bounds.allows(item, name, sample), (item, name)
assert not bounds.allows("no.such", "field", 1)
def test_a_bool_is_not_a_number_and_a_non_finite_bound_is_rejected() -> None:
assert bounds._number(True) is None
assert bounds._number("1") is None
assert bounds._number(Fraction(1, 2)) == 0.5
assert not bounds.allows("lean", "paymentYearOffset", float("nan"))
with pytest.raises(ValueError):
bounds.num(float("nan"))
def test_a_duplicate_fence_row_is_an_error() -> None:
row = bounds.element(item="a", name="b", kind="published", role="payment")
with pytest.raises(ValueError, match="duplicate"):
bounds._reject_dupes([row, dict(row)])
def test_observed_endpoints_are_ordered_and_admitted() -> None:
for row in bounds.load()["elements"]:
if row["low"] is None or row["high"] is None:
continue
assert bounds._cmp(float(row["low"]), float(row["high"])) <= 0
row = next(
item
for item in bounds.load()["elements"]
if item["item"] == "pfs.rvu"
and item["name"] == "work_rvu"
and item["kind"] == "observed"
)
low, high = float(row["low"]), float(row["high"])
assert bounds.allows("pfs.rvu", "work_rvu", low, period=row["period"])
assert bounds.allows("pfs.rvu", "work_rvu", high, period=row["period"])
assert not bounds.allows("pfs.rvu", "work_rvu", low - 1, period=row["period"])
assert not bounds.allows("pfs.rvu", "work_rvu", high + 1, period=row["period"])
def test_a_work_gpci_below_the_floor_stays_in_the_catalog() -> None:
below = [
row
for row in bounds.load()["elements"]
if row["name"] == "work_gpci"
and row["low"] is not None
and float(row["low"]) < 1
]
assert below
proposed = [row for row in below if row["kind"] == "proposed"]
observed = [row for row in below if row["item"] == "pfs.gpci"]
assert proposed
assert observed
for row in proposed:
assert row["role"] == "proposed"
assert "below" in row["note"]
assert not bounds.allows(
row["item"], row["name"], float(row["low"]), period=row["period"]
)
for row in observed:
assert row["kind"] == "observed"
assert row["role"] == "payment"
assert "floor" in row["note"]
assert bounds.allows(
row["item"], row["name"], float(row["low"]), period=row["period"]
)
final = index(bounds.load())["pfs.gpci", "work_gpci", "2027"]
assert final["kind"] == "observed"
assert final["low"] == "0.948"
assert bounds.allows("pfs.gpci", "work_gpci", 0.948, period="2027")
def test_outside_columns_are_recorded_and_rejected() -> None:
snap = index(bounds.load())
assert snap["pfs.rvu", "conv_factor", ""]["kind"] == "rejected"
assert snap["pfs.rvu", "non_fac_total", ""]["kind"] == "derived"
copay = next(
row
for row in bounds.load()["elements"]
if row["item"] == "opps.addendum_b"
and row["name"] == "minimum_unadjusted_copayment"
and row["kind"] == "observed"
)
assert "not an input" in copay["note"]
assert not bounds.allows(
copay["item"], copay["name"], float(copay["low"]), period=copay["period"]
)
def test_table_models_have_every_measure_in_the_fence() -> None:
snap_names: dict[str, set[str]] = {}
for row in bounds.load()["elements"]:
snap_names.setdefault(row["item"], set()).add(row["name"])
models = (
(Rvu, "pfs.rvu", {"year"}),
(Gpci, "pfs.gpci", {"year"}),
(MedicalEquipment, "pfs.medical_equipment", {"year"}),
(AddendumB, "opps.addendum_b", {"year"}),
(ApcWeight, "opps.apc_weight", {"year"}),
(WageIndex, "opps.wage_index", {"year"}),
(PassThrough, "opps.pass_through", {"year"}),
(OppsAdjustedPayment, "opps.adjusted_payment", {"year"}),
(OppsSkinSubImpact, "opps.skin_sub_impact", {"year"}),
)
for model, item, periods in models:
measures = set()
for fname, field in model.model_fields.items():
if fname in periods:
continue
ann = bounds._peel(field.annotation)
if ann in (int, float, bool):
measures.add(fname)
missing = measures - snap_names[item]
assert not missing, (item, missing)
skin = snap_names["opps.skin_sub_addendum_b"]
for fname, field in AddendumB.model_fields.items():
if fname == "year":
continue
ann = bounds._peel(field.annotation)
if ann in (int, float, bool):
assert fname in skin
def test_build_requires_the_replica(monkeypatch, tmp_path) -> None:
monkeypatch.setattr(bounds, "REPLICA", tmp_path / "missing.duckdb")
with pytest.raises(FileNotFoundError):
bounds.build()
def test_build_opens_and_closes_its_replica(monkeypatch, tmp_path) -> None:
path = tmp_path / "aco.ro.duckdb"
duckdb.connect(str(path)).close()
monkeypatch.setattr(bounds, "REPLICA", path)
doc = bounds.build()
assert doc["schema"] == 1
assert any(row["item"] == "pfs.rules.RuleYear" for row in doc["elements"])
again = duckdb.connect(str(path))
again.execute("SELECT 1")
again.close()
def test_a_small_table_sets_the_period_fence() -> None:
con = duckdb.connect()
con.execute("CREATE SCHEMA pfs")
con.execute(
"""
CREATE TABLE pfs.rvu (
year INTEGER,
work_rvu DOUBLE,
non_fac_pe_rvu DOUBLE,
fac_pe_rvu DOUBLE,
mp_rvu DOUBLE,
pre_op DOUBLE,
intra_op DOUBLE,
post_op DOUBLE
)
"""
)
con.execute(
"""
INSERT INTO pfs.rvu VALUES
(2020, 1.5, NULL, 0.25, 0.1, 0, 0, 0),
(2020, 3, NULL, 0.5, NULL, 1, 0, 0),
(NULL, 4, 1, 1, 1, 0, 0, 0)
"""
)
con.execute(
"""
CREATE TABLE pfs.gpci (
year INTEGER, work_gpci DOUBLE, pe_gpci DOUBLE, mp_gpci DOUBLE
)
"""
)
con.execute("INSERT INTO pfs.gpci VALUES (2026, 0.9, 1, 1), (2024, 1.2, 1, 1)")
con.execute(
"""
CREATE TABLE pfs.gpci_proposed (
cms_rule_id VARCHAR,
gpci_year BIGINT,
work_gpci DOUBLE,
pe_gpci DOUBLE,
mp_gpci DOUBLE
)
"""
)
con.execute(
"""
INSERT INTO pfs.gpci_proposed VALUES
('CMS-1832-P', 2026, 0.95, 1, 1),
('CMS-1832-P', 2024, 1.1, 1, 1)
"""
)
con.execute(
"""
CREATE TABLE pfs.medical_equipment (
year INTEGER,
unit_price DOUBLE,
useful_life DOUBLE,
minutes_per_year DOUBLE,
nf_minutes DOUBLE,
f_minutes DOUBLE
)
"""
)
con.execute("INSERT INTO pfs.medical_equipment VALUES (2020, 10, 5, 1000, 1, 0)")
con.execute("CREATE SCHEMA drugs")
con.execute("CREATE TABLE drugs.asp_noc (quarter VARCHAR, payment_limit DOUBLE)")
con.execute("CREATE SCHEMA skin_subs")
con.execute(
"""
CREATE TABLE skin_subs.asp_quarterly (
quarter VARCHAR, asp_per_unit DOUBLE, payment_limit DOUBLE
)
"""
)
con.execute("INSERT INTO skin_subs.asp_quarterly VALUES ('2024-Q1', 10, 10.6)")
con.execute(
"""
CREATE TABLE drugs.asp_payment (
quarter VARCHAR, payment_limit DOUBLE, coinsurance_pct DOUBLE
)
"""
)
con.execute(
"INSERT INTO drugs.asp_payment VALUES ('2006-Q1', NULL, 20), ('2006-Q2', 12.5, 20)"
)
rows = bounds.observed_rows(con)
got = index({"elements": rows})
work = got["pfs.rvu", "work_rvu", "2020"]
assert work["kind"] == "observed"
assert work["low"] == "1.5"
assert work["high"] == "3"
assert work["rows"] == 2
pe = got["pfs.rvu", "non_fac_pe_rvu", "2020"]
assert pe["kind"] == "unstated"
assert pe["rows"] == 0
assert "No range is invented" in pe["note"]
assert got["pfs.rvu", "work_rvu", "null"]["high"] == "4"
assert got["pfs.rvu", "mp_rvu", "2020"]["rows"] == 1
assert "not an input" in got["pfs.rvu", "pre_op", "2020"]["note"]
below = got["pfs.gpci", "work_gpci", "2026"]
assert below["kind"] == "observed"
assert "separate constraint" in below["note"]
assert "below" not in got["pfs.gpci", "work_gpci", "2024"]["note"]
proposed = got["pfs.gpci_proposed", "work_gpci", "CMS-1832-P:2026"]
assert proposed["kind"] == "proposed"
assert "below" in proposed["note"]
above = got["pfs.gpci_proposed", "work_gpci", "CMS-1832-P:2024"]
assert "without the statutory" in above["note"]
assert "below" not in above["note"]
assert got["pfs.medical_equipment", "unit_price", "2020"]["low"] == "10"
assert (
got["pfs.medical_equipment", "maintenance_factor", ""]["kind"] == "unobserved"
)
maint_note = got["pfs.medical_equipment", "maintenance_factor", ""]["note"]
assert "no maintenance column" in maint_note
assert "not that factor" in maint_note
assert got["opps.wage_index", "wage_index", ""]["kind"] == "unobserved"
assert got["drugs.asp_noc", "payment_limit", ""]["kind"] == "unstated"
assert got["drugs.asp_noc", "payment_limit", ""]["rows"] == 0
assert (
"Back-calculated"
in got["skin_subs.asp_quarterly", "asp_per_unit", "2024-Q1"]["note"]
)
assert "not the ASP" in got["drugs.asp_payment", "payment_limit", "2006-Q2"]["note"]
assert got["drugs.asp_payment", "payment_limit", "2006-Q1"]["kind"] == "unstated"
assert (
"not an input" in got["drugs.asp_payment", "coinsurance_pct", "2006-Q1"]["note"]
)
con.close()
def test_derived_tables_name_every_measure_and_add_no_range() -> None:
con = duckdb.connect()
con.execute("CREATE SCHEMA skin_subs")
con.execute(
"""
CREATE TABLE skin_subs.asp_trajectories (
quarter VARCHAR,
asp_per_unit DOUBLE,
surprise DOUBLE
)
"""
)
rows = bounds.derived_rows(con)
by_item: dict[str, dict[str, dict]] = {}
for row in rows:
by_item.setdefault(row["item"], {})[row["name"]] = row
surprise = by_item["skin_subs.asp_trajectories"]["surprise"]
assert surprise["kind"] == "derived"
assert surprise["low"] is None
assert "asp_per_unit" in by_item["skin_subs.asp_trajectories"]
assert "adjusted_payment" in by_item["opps.adjusted_payment"]
assert by_item["opps.adjusted_payment"]["adjusted_payment"]["low"] is None
con.close()
@pytest.mark.skipif(not bounds.REPLICA.is_file(), reason="replica not on disk")
def test_snapshot_matches_a_fresh_read_of_the_replica() -> None:
assert bounds.load() == bounds.build()
@pytest.mark.skipif(not bounds.REPLICA.is_file(), reason="replica not on disk")
def test_every_numeric_column_of_a_fenced_table_is_an_element() -> None:
period = {
"year",
"quarter",
"gpci_year",
"cms_rule_id",
"fiscal_year",
"perf_year",
}
tables = {spec.table for spec in bounds.SPECS} | {
item[0] for item in bounds.DERIVED
}
names: dict[str, set[str]] = {}
for row in bounds.load()["elements"]:
names.setdefault(row["item"], set()).add(row["name"])
con = duckdb.connect(str(bounds.REPLICA), read_only=True)
try:
present = bounds._table_names(con)
for table in sorted(tables):
if table not in present:
continue
measures = bounds._measure_columns(con, table) - period
missing = measures - names[table]
assert not missing, (table, missing)
finally:
con.close()