feat(pay): fence every payment input the formulas can take
Some checks failed
CI / lint (push) Failing after 53s
CI / notebooks-smoke (push) Successful in 2m12s
Deploy / changes (push) Successful in 18s
CI / test (push) Successful in 4m54s
Infra CI / docs (push) Successful in 23s
Infra CI / api (push) Successful in 1m13s
Infra CI / bcda (push) Successful in 1m59s
Infra CI / notebooks (push) Successful in 1m19s
Infra CI / zotero (push) Successful in 17s
Infra CI / llm (push) Successful in 1m0s
Infra CI / mc (push) Successful in 22s
Package Supply Chain / pkg-supply-chain (push) Successful in 3m9s
Deploy / notebooks (push) Has been skipped
Deploy / zotero (push) Has been skipped
Deploy / docs (push) Has been skipped
Lean Pay / pay (push) Successful in 3m33s
Deploy / api (push) Successful in 1m32s
Deploy / bcda (push) Successful in 1m51s
Deploy / mc (push) Has been skipped
Deploy / llm (push) Successful in 1m9s
Deploy / report (push) Successful in 15s

src/pay/bounds.json records each numeric rule field, the Lean
constants, and the per-period min and max from the replica.
allows() rejects proposed NPRM numbers, unstated nulls, a missing
wage index, and a calculated fee. A new numeric field fails the
test until the snapshot is rebuilt.
This commit is contained in:
kert
2026-11-17 16:00:44 -05:00
parent a8ed6dde9a
commit a15bccb8c5
6 changed files with 16626 additions and 1 deletions

View File

@@ -38,6 +38,28 @@ labor share then cancels.
- QPP thresholds stay in `src/qpp`, cited to the Federal Register. Only
the two-year offset is a formula in this slice.
## Bounds
`src/pay/bounds.json` is the fence for a later search. Published
constants (a year's conversion factor, ASP + 6%, the limiting-charge
factor, the 60% labor share, the two-year QPP offset) are points, not
knobs. Observed rows are the per-period minimum and maximum in the
replica for the columns the formulas read. A global span is not stored.
The free knobs are a tag confidence in [0, 1], a REACH quality score in
[0, 1], and an MPPR rank that is an integer of at least 1. The year
window is whichever periods the file lists.
`pay.bounds.allows` rejects a point outside that row. It also rejects
proposed NPRM numbers, an unstated null (nothing is imputed), a missing
wage index, a missing equipment maintenance factor, and a
limiting-charge fee, which is an output of `pfsPayment`. IPPS and LEAD
have no pricer. MSSP and REACH settlements stay published tables. The
budget-neutrality adjustor is already inside the conversion factor.
Rebuild the file from the registries and `data/replica/aco.ro.duckdb`
when either changes. A checkout without the replica still checks the
registries against the committed file.
## Check
```sh

View File

@@ -285,6 +285,6 @@ link-mode = "copy"
python-preference = "managed"
[tool.uv.build-backend]
module-name = ["aco", "api", "bcda", "bib", "bls", "ccw", "cli", "cms", "conf", "focus", "lead", "llm", "mail", "nlm", "opps", "perf", "pfs", "prisma", "qpp", "rec", "rex", "sem"]
module-name = ["aco", "api", "bcda", "bib", "bls", "ccw", "cli", "cms", "conf", "focus", "lead", "llm", "mail", "nlm", "opps", "pay", "perf", "pfs", "prisma", "qpp", "rec", "rex", "sem"]
namespace = true
source-exclude = ["compose.yml","infra/**","data/**","notebooks/**","tuva/**","assets/**","docs/**","dev/**","bundle/**","cloud/**"]

10
src/pay/__init__.py Normal file
View File

@@ -0,0 +1,10 @@
"""Fences for the payment formulas.
Published rule numbers, Lean constants, and per-period ranges from the
replica. A later search calls :func:`pay.bounds.allows` and stays inside
the fence.
"""
from pay.bounds import SNAPSHOT, allows, build, load
__all__ = ["SNAPSHOT", "allows", "build", "load"]

14929
src/pay/bounds.json Normal file

File diff suppressed because it is too large Load Diff

998
src/pay/bounds.py Normal file
View File

@@ -0,0 +1,998 @@
"""The fence around Medicare payment inputs.
Three kinds of number stay apart.
* A published constant (a year's conversion factor, ASP + 6%, the
limiting-charge factor) is a point. It is not a knob.
* An observed row is the min and max, in one period, of a column the
formula reads. A global span is not stored beside it.
* A knob is a real search dimension: tag confidence, a REACH quality
score, an MPPR rank.
:func:`allows` rejects anything outside that fence. Proposed NPRM
numbers, an unstated null, a missing series, and a calculated output
are recorded so the hole is visible, and then rejected. Nothing is
imputed.
"""
from __future__ import annotations
import json
import math
from collections.abc import Iterator
from dataclasses import dataclass
from fractions import Fraction
from pathlib import Path
from types import NoneType, UnionType
from typing import Any, Union, get_args, get_origin
import duckdb
from pydantic import BaseModel
from opps.rules import RULES as OPPS_RULES
from pfs.rules import PROPOSED
from pfs.rules import RULES as PFS_RULES
from qpp import QPP
SCHEMA = 1
SNAPSHOT = Path(__file__).with_name("bounds.json")
REPLICA = Path(__file__).resolve().parents[2] / "data" / "replica" / "aco.ro.duckdb"
# Closed policy strings. Other strings on the rule models are labels.
CATEGORICAL = frozenset({"skin_sub_payment_method"})
_INFORMATIONAL = frozenset(
{
"budget_neutrality_adjustor",
"clinical_labor_rate_update",
"supply_equipment_price_update",
}
)
_CONSTRAINT = frozenset({"work_gpci_floor", "pe_gpci_floor"})
_REJECT_KINDS = frozenset(
{
"proposed",
"unobserved",
"absent",
"unstated",
"derived",
"rejected",
"published_table",
}
)
_REJECT_ROLES = frozenset({"proposed", "outside", "output"})
# (name, numerator, denominator, note). The fraction is the Lean literal,
# not a reduced float.
_CONSTANTS = (
("parReduction", 5, 100, "Non-PAR fee is the PAR fee times (1 - 5/100)."),
("nonParMarkup", 15, 100, "Limiting-charge markup over the non-PAR fee."),
(
"limitingChargeFactor",
10925,
10000,
"(1 - 5/100) x (1 + 15/100).",
),
("aspAddOn", 6, 100, "Part B drug add-on. The limit is ASP times (1 + 6/100)."),
(
"reachQualityWithhold",
2,
100,
"Share of benchmark withheld for REACH quality.",
),
("paymentYearOffset", 2, 1, "payment_year = performance_year + 2."),
(
"missingWageIndex",
1,
1,
"Fill used when the wage index is missing. Not an observed index.",
),
(
"maintenanceDefault",
0,
1,
"Fill used when maintenance_factor is absent.",
),
("mpprReduction", 1, 2, "Default PE reduction for rank 2 and later."),
("laborShare", 3, 5, "Default OPPS labor share, 0.60."),
("passThroughDrugs", 106, 100, "ASP times 1.06. Equals 1 + aspAddOn."),
)
# Lean Pay.ceiling. The value is the only legal label for that method.
_CEILINGS = (
("pfs", "formula"),
("opps", "formula"),
("partBAsp", "formula"),
("qpp", "formula"),
("mssp", "published_table"),
("reach", "published_table"),
("ipps", "absent"),
("lead", "absent"),
)
@dataclass(frozen=True)
class _Spec:
"""One observed scan: a table, the period columns, the measures."""
table: str
period: tuple[str, ...]
columns: tuple[str, ...]
role: str
# Columns the formulas read, plus the other numerics on those same
# tables. ``outside`` is recorded and then rejected by allows().
SPECS = (
_Spec(
"pfs.rvu",
("year",),
("work_rvu", "non_fac_pe_rvu", "fac_pe_rvu", "mp_rvu"),
"payment",
),
_Spec(
"pfs.rvu",
("year",),
("pre_op", "intra_op", "post_op"),
"outside",
),
_Spec("pfs.gpci", ("year",), ("work_gpci", "pe_gpci", "mp_gpci"), "payment"),
_Spec(
"pfs.gpci_proposed",
("cms_rule_id", "gpci_year"),
("work_gpci", "pe_gpci", "mp_gpci"),
"proposed",
),
_Spec(
"pfs.rvu_proposed",
("cms_rule_id",),
("work_rvu", "non_fac_pe_rvu", "fac_pe_rvu", "mp_rvu"),
"proposed",
),
_Spec(
"pfs.medical_equipment",
("year",),
(
"unit_price",
"useful_life",
"minutes_per_year",
"nf_minutes",
"f_minutes",
"maintenance_factor",
),
"payment",
),
_Spec(
"opps.addendum_b",
("year",),
("payment_rate", "relative_weight"),
"payment",
),
_Spec(
"opps.addendum_b",
("year",),
("minimum_unadjusted_copayment",),
"outside",
),
_Spec(
"opps.apc_weight",
("year",),
("payment_rate", "relative_weight"),
"payment",
),
_Spec(
"opps.apc_weight",
("year",),
("minimum_unadjusted_copayment",),
"outside",
),
_Spec(
"opps.skin_sub_addendum_b",
("year",),
("payment_rate", "relative_weight"),
"payment",
),
_Spec(
"opps.skin_sub_addendum_b",
("year",),
("minimum_unadjusted_copayment",),
"outside",
),
_Spec("opps.wage_index", ("year",), ("wage_index",), "payment"),
_Spec(
"opps.wage_index",
("year",),
("reclassified_wage_index",),
"outside",
),
_Spec(
"opps.pass_through",
("year",),
("payment_rate", "asp_per_unit"),
"payment",
),
_Spec(
"skin_subs.asp_quarterly",
("quarter",),
("asp_per_unit", "payment_limit"),
"payment",
),
_Spec("drugs.asp_payment", ("quarter",), ("payment_limit",), "payment"),
_Spec("drugs.asp_payment", ("quarter",), ("coinsurance_pct",), "outside"),
_Spec("drugs.asp_noc", ("quarter",), ("payment_limit",), "payment"),
)
# Output tables and the derived ASP trajectory. Named so a new numeric
# column fails the column test, and stored without a range so they are
# not a second fence.
DERIVED = (
(
"skin_subs.asp_trajectories",
"quarter",
(
"asp_per_unit",
"payment_limit",
"total_quarters",
"qoq_pct_change",
"cumulative_pct_change",
"flat_rate_delta",
"anomalous_spike",
),
"Derived from skin_subs.asp_quarterly. Not a second fence.",
),
(
"opps.adjusted_payment",
"year",
("relative_weight", "payment_rate", "wage_index", "adjusted_payment"),
"Output of opps.calcs.payment.payment. Not an input.",
),
(
"opps.skin_sub_impact",
"year",
(
"units",
"paid_amount",
"asp_per_unit",
"payment_limit",
"old_payment",
"new_payment",
"payment_delta",
"pct_change",
),
"Output of the skin-substitute impact step. Not an input.",
),
)
_MISSING_NOTES = {
("opps.wage_index", "wage_index"): (
"No opps.wage_index table. oppsAdjusted fills a missing index with 1."
" Do not sample an index."
),
("opps.wage_index", "reclassified_wage_index"): (
"No opps.wage_index table. oppsAdjusted does not read this column."
),
("pfs.medical_equipment", "maintenance_factor"): (
"Column is not loaded. equipmentCostPerMinute uses 0."
),
("opps.pass_through", "payment_rate"): (
"Addendum D is not in the replica. Do not invent a pass-through rate."
),
("opps.pass_through", "asp_per_unit"): (
"Addendum D is not in the replica. Do not invent an ASP."
),
}
_NUMERIC_TYPES = frozenset(
{
"DOUBLE",
"FLOAT",
"REAL",
"DECIMAL",
"INTEGER",
"BIGINT",
"HUGEINT",
"SMALLINT",
"TINYINT",
"UBIGINT",
"UINTEGER",
"BOOLEAN",
}
)
def num(value: object) -> str:
"""Format a bound the same way on both sides of a snapshot compare."""
number = float(value) # type: ignore[arg-type]
if not math.isfinite(number):
raise ValueError(f"non-finite bound: {value!r}")
return format(number, ".12g")
def element(
*,
item: str,
name: str,
kind: str,
role: str,
period: str = "",
low: str | None = None,
high: str | None = None,
value: object = None,
rows: int | None = None,
note: str = "",
integer: bool = False,
) -> dict[str, Any]:
"""One fence row. Floats are already formatted; bools stay bools."""
return {
"high": high,
"integer": integer,
"item": item,
"kind": kind,
"low": low,
"name": name,
"note": note,
"period": period,
"role": role,
"rows": rows,
"value": value,
}
def canonical(doc: dict[str, Any]) -> str:
"""Deterministic JSON. Key order and element order are both fixed."""
return json.dumps(doc, indent=2, sort_keys=True) + "\n"
def load(path: Path | None = None) -> dict[str, Any]:
"""Read the committed snapshot."""
return json.loads((path or SNAPSHOT).read_text())
def build(con: Any = None) -> dict[str, Any]:
"""Rebuild the snapshot from the rule registries and a replica.
Opens :data:`REPLICA` read-only when ``con`` is omitted. A missing
file raises ``FileNotFoundError``. The caller keeps a connection it
passed in.
"""
own = con is None
if own:
if not REPLICA.is_file():
raise FileNotFoundError(REPLICA)
con = duckdb.connect(str(REPLICA), read_only=True)
try:
rows = [
*registry_rows(),
*constant_rows(),
*ceiling_rows(),
*hole_rows(),
*observed_rows(con),
*derived_rows(con),
]
_reject_dupes(rows)
rows.sort(key=lambda row: (row["item"], row["name"], row["period"]))
return {"schema": SCHEMA, "elements": rows}
finally:
if own:
con.close()
def allows(
item: str,
name: str,
value: object,
period: str | int | None = None,
*,
doc: dict[str, Any] | None = None,
) -> bool:
"""True when ``value`` is inside the one fence row for this input.
A name that spans several periods requires ``period``. Proposed
numbers, unstated nulls, missing series, and calculated outputs
are inside the file and still return False.
"""
rows = _rows_for(doc or load(), item, name, period)
if len(rows) != 1:
return False
return _admits(rows[0], value)
def registry_rows() -> list[dict[str, Any]]:
"""One row per numeric, bool, null, and categorical rule field."""
rows: list[dict[str, Any]] = []
for year, rule in sorted(PFS_RULES.items()):
rows.extend(_model_rows("pfs.rules.RuleYear", str(year), rule, "payment"))
for year, rule in sorted(PROPOSED.items()):
rows.extend(_model_rows("pfs.rules.ProposedRule", str(year), rule, "proposed"))
for year, rule in sorted(OPPS_RULES.items()):
rows.extend(_model_rows("opps.rules.RuleYear", str(year), rule, "payment"))
for year, rule in sorted(QPP.items()):
rows.extend(_model_rows("qpp.QppYear", str(year), rule, "payment"))
return rows
def constant_rows() -> list[dict[str, Any]]:
"""Lean rationals. ``value`` keeps the unreduced fraction."""
rows = []
for name, numerator, denominator, note in _CONSTANTS:
point = num(float(Fraction(numerator, denominator)))
rows.append(
element(
item="lean",
name=name,
kind="constant",
role="payment",
low=point,
high=point,
value=f"{numerator}/{denominator}",
note=note,
)
)
return rows
def ceiling_rows() -> list[dict[str, Any]]:
"""The eight Lean methods and the only legal label for each."""
return [
element(
item="lean.ceiling",
name=name,
kind="category",
role="payment",
value=value,
note="Lean Pay.ceiling for this method.",
)
for name, value in _CEILINGS
]
def hole_rows() -> list[dict[str, Any]]:
"""Elements the formulas name and the replica must not invent."""
return [
element(
item="pfs.limiting_charge",
name="fee",
kind="derived",
role="output",
note=(
"Output of pfsPayment times the limiting-charge factor."
" Do not sample a fee."
),
),
element(
item="pfs.rvu",
name="conv_factor",
kind="rejected",
role="informational",
note=(
"Not a payment input. Use pfs.rules.RuleYear.conversion_factor"
" and each CfSegment."
),
),
element(
item="pfs.rvu",
name="non_fac_total",
kind="derived",
role="output",
note="Sum of work, non-facility PE, and MP. pfsPayment does not read it.",
),
element(
item="pfs.rvu",
name="fac_total",
kind="derived",
role="output",
note="Sum of work, facility PE, and MP. pfsPayment does not read it.",
),
element(
item="pfs.mppr",
name="rank",
kind="knob",
role="knob",
low="1",
integer=True,
note=(
"Rank 1 keeps the PE RVU. Later ranks keep 1 minus the"
" reduction. An integer, at least 1."
),
),
element(
item="reach",
name="total_quality",
kind="knob",
role="knob",
low="0",
high="1",
note=(
"Quality score as a fraction from 0 to 1."
" Earn-back is this score times 2/100."
),
),
element(
item="reach",
name="settlement",
kind="published_table",
role="payment",
note=(
"Shared savings are a published CMS table."
" There is no savings function to sample."
),
),
element(
item="mssp",
name="settlement",
kind="published_table",
role="payment",
note=(
"Shared savings are a published CMS table."
" There is no savings function to sample."
),
),
element(
item="ipps",
name="payment",
kind="absent",
role="payment",
note="No IPPS pricer in this repo.",
),
element(
item="lead",
name="pricer",
kind="absent",
role="payment",
note="src/lead is the review application, not a payment model.",
),
element(
item="lead.tag",
name="confidence",
kind="knob",
role="knob",
low="0",
high="1",
note="Theme-tag confidence. The only tagging knob.",
),
]
def observed_rows(con: Any) -> list[dict[str, Any]]:
"""Per-period min, max, and non-null count. Missing tables stay blank."""
present = _table_names(con)
rows: list[dict[str, Any]] = []
for spec in SPECS:
rows.extend(_spec_rows(con, spec, present))
return rows
def derived_rows(con: Any) -> list[dict[str, Any]]:
"""Name every numeric column of a derived table, with no range."""
present = _table_names(con)
rows: list[dict[str, Any]] = []
for table, period_col, columns, note in DERIVED:
names = list(columns)
if table in present:
extra = _measure_columns(con, table) - set(columns) - {period_col}
names.extend(sorted(extra))
for name in names:
rows.append(
element(
item=table,
name=name,
kind="derived",
role="output",
note=note,
)
)
return rows
def _model_rows(
item: str, period: str, obj: BaseModel, role: str
) -> list[dict[str, Any]]:
return [_leaf_row(item, period, leaf) for leaf in _leaves(obj, role)]
def _leaves(
obj: BaseModel, role: str, prefix: str = "", period: str | None = None
) -> Iterator[_Leaf]:
for fname, field in type(obj).model_fields.items():
ann = _peel(field.annotation)
path = f"{prefix}.{fname}" if prefix else fname
value = getattr(obj, fname)
child = "proposed" if role == "proposed" or fname == "proposed" else role
if _is_model(ann):
if value is None:
yield _Leaf(path, None, child, period, "unstated")
else:
yield from _leaves(value, child, path, period)
continue
if _is_model_list(ann):
for item in value or []:
span = f"{item.start.isoformat()}/{item.end.isoformat()}"
yield from _leaves(item, child, path, span)
continue
if ann is bool or ann in (int, float):
kind = "unstated" if value is None else "scalar"
yield _Leaf(path, value, _leaf_role(fname, child), period, kind)
continue
if fname in CATEGORICAL:
kind = "unstated" if value is None else "category"
yield _Leaf(path, value, child, period, kind)
@dataclass(frozen=True)
class _Leaf:
name: str
value: object
role: str
period: str | None
kind: str
def _leaf_row(item: str, default_period: str, leaf: _Leaf) -> dict[str, Any]:
period = leaf.period or default_period
note = _leaf_note(leaf.name, leaf.role, leaf.value)
if leaf.kind == "unstated" or leaf.value is None:
return element(
item=item,
name=leaf.name,
period=period,
kind="unstated",
role=leaf.role,
note=note,
)
if leaf.kind == "category":
return element(
item=item,
name=leaf.name,
period=period,
kind="category",
role=leaf.role,
value=leaf.value,
note=note,
)
if isinstance(leaf.value, bool):
return element(
item=item,
name=leaf.name,
period=period,
kind="published",
role=leaf.role,
value=leaf.value,
note=note,
)
point = num(leaf.value)
kind = "proposed" if leaf.role == "proposed" else "published"
return element(
item=item,
name=leaf.name,
period=period,
kind=kind,
role=leaf.role,
low=point,
high=point,
value=point,
note=note,
)
def _leaf_role(fname: str, role: str) -> str:
if role == "proposed":
return "proposed"
if fname in _INFORMATIONAL:
return "informational"
if fname in _CONSTRAINT:
return "constraint"
return "payment"
def _leaf_note(name: str, role: str, value: object) -> str:
leaf = name.rsplit(".", 1)[-1]
if role == "proposed" and value is None:
if name == "proposed":
return "No NPRM block captured for this year."
return "The NPRM proposed no numeric change. Do not invent one."
if role == "proposed" and value is not None:
if leaf == "budget_neutrality_adjustor":
return (
"NPRM adjustor, already inside the proposed conversion factor."
" Not a payment input."
)
return "NPRM value. Not a payment input."
if leaf == "budget_neutrality_adjustor":
return (
"Already inside conversion_factor. Do not multiply payment by this again."
)
if leaf == "work_gpci_floor":
return (
"Legal minimum on the final work GPCI."
" An observed GPCI below it stays in the catalog."
)
if value is None and leaf == "benchmark_nominal_pct":
return "Not stated in the Federal Register corpus. Do not impute it."
if value is None and leaf == "apm_incentive_pct":
return "No APM incentive payment this payment year. Do not impute zero."
if value is None and leaf == "cf_qp":
return "No QP conversion factor this year."
if value is None and leaf == "anesthesia_cf":
return "No separate anesthesia conversion factor transcribed for this year."
if value is None and leaf == "skin_sub_flat_rate":
return "No flat rate this year."
if value is None and leaf == "packaging_threshold":
return "Not transcribed. Do not impute it."
if value is None and leaf == "telehealth_originating_site_fee":
return "Not transcribed for this year."
return ""
def _spec_rows(con: Any, spec: _Spec, present: set[str]) -> list[dict[str, Any]]:
if spec.table not in present:
return [_missing(spec, column) for column in spec.columns]
have = _column_names(con, spec.table)
rows = [_missing(spec, column) for column in spec.columns if column not in have]
present_cols = tuple(column for column in spec.columns if column in have)
if not present_cols:
return rows
scanned = _scan(con, spec.table, spec.period, present_cols)
if not scanned:
for column in present_cols:
rows.append(
element(
item=spec.table,
name=column,
kind="unstated",
role=spec.role,
rows=0,
note="Table has no rows. No range is invented.",
)
)
return rows
width = len(spec.period)
for record in scanned:
period = ":".join(_cell(value) for value in record[:width])
for index, column in enumerate(present_cols):
low, high, count = record[width + 3 * index : width + 3 * index + 3]
rows.append(_observed(spec, column, period, low, high, count))
return rows
def _missing(spec: _Spec, column: str) -> dict[str, Any]:
return element(
item=spec.table,
name=column,
kind="unobserved",
role=spec.role,
note=_MISSING_NOTES.get(
(spec.table, column),
"Not in the replica. No range is invented.",
),
)
def _observed(
spec: _Spec,
column: str,
period: str,
low: object,
high: object,
count: object,
) -> dict[str, Any]:
seen = int(count or 0)
if low is None or high is None or seen == 0:
return element(
item=spec.table,
name=column,
period=period,
kind="unstated",
role=spec.role,
rows=seen,
note="No non-null values in this period. No range is invented.",
)
kind = "proposed" if spec.role == "proposed" else "observed"
return element(
item=spec.table,
name=column,
period=period,
kind=kind,
role=spec.role,
low=num(low),
high=num(high),
rows=seen,
note=_observed_note(spec, column, kind, num(low), period),
)
def _observed_note(spec: _Spec, column: str, kind: str, low: str, period: str) -> str:
notes: list[str] = []
if spec.table == "skin_subs.asp_quarterly" and column == "asp_per_unit":
notes.append(
"Back-calculated as payment_limit / 1.06."
" The CMS allowance is payment_limit."
)
elif spec.table == "skin_subs.asp_quarterly" and column == "payment_limit":
notes.append(
"CMS payment allowance. asp_per_unit is this value divided by 1.06."
)
elif spec.table == "drugs.asp_payment" and column == "payment_limit":
notes.append("CMS payment allowance (ASP + 6%), not the ASP itself.")
elif spec.table == "drugs.asp_noc" and column == "payment_limit":
notes.append("CMS payment allowance for a not-otherwise-classified drug.")
if column == "work_gpci" and kind in {"observed", "proposed"}:
year = _year(period)
floor = PFS_RULES[year].work_gpci_floor if year in PFS_RULES else 1.0
if float(low) < floor:
if spec.role == "proposed":
notes.append(
"Published without the statutory work GPCI floor."
" Observed min is below it. The row stays."
)
else:
notes.append(
f"Observed min is below the {num(floor)} work GPCI floor."
" The floor is a separate constraint and this row stays."
)
elif spec.role == "proposed":
notes.append("Published without the statutory work GPCI floor.")
if spec.role == "outside":
notes.append("On the file, and not an input of the payment formula.")
return " ".join(notes)
def _scan(
con: Any, table: str, period: tuple[str, ...], columns: tuple[str, ...]
) -> list[tuple[Any, ...]]:
chosen = ", ".join(_ident(column) for column in period)
aggs: list[str] = []
for column in columns:
quoted = _ident(column)
aggs.append(f"min({quoted})")
aggs.append(f"max({quoted})")
aggs.append(f"count({quoted})")
sql = (
f"SELECT {chosen}, {', '.join(aggs)} FROM {_table(table)}"
f" GROUP BY {chosen} ORDER BY {chosen}"
)
return con.execute(sql).fetchall()
def _rows_for(
doc: dict[str, Any], item: str, name: str, period: str | int | None
) -> list[dict[str, Any]]:
rows = [
row for row in doc["elements"] if row["item"] == item and row["name"] == name
]
if period is None:
return rows
key = str(period)
return [row for row in rows if row["period"] == key]
def _admits(row: dict[str, Any], value: object) -> bool:
if row["kind"] in _REJECT_KINDS or row["role"] in _REJECT_ROLES:
return False
if isinstance(value, bool) or isinstance(row["value"], bool):
return isinstance(value, bool) and value is row["value"]
if row["integer"]:
if not isinstance(value, int):
return False
return _in_range(float(value), row["low"], row["high"])
if row["low"] is None and row["high"] is None:
return isinstance(value, str) and value == row["value"]
number = _number(value)
if number is None:
return False
return _in_range(number, row["low"], row["high"])
def _in_range(number: float, low: str | None, high: str | None) -> bool:
if not math.isfinite(number):
return False
if low is not None and _cmp(number, float(low)) < 0:
return False
if high is not None and _cmp(number, float(high)) > 0:
return False
return low is not None or high is not None
def _cmp(left: float, right: float) -> int:
"""Compare after the same ``.12g`` rounding the snapshot stores."""
a = float(format(left, ".12g"))
b = float(format(right, ".12g"))
return (a > b) - (a < b)
def _number(value: object) -> float | None:
if isinstance(value, bool) or isinstance(value, str):
return None
if isinstance(value, Fraction):
return float(value)
if isinstance(value, int | float):
return float(value)
return None
def _reject_dupes(rows: list[dict[str, Any]]) -> None:
seen: set[tuple[str, str, str]] = set()
for row in rows:
key = (row["item"], row["name"], row["period"])
if key in seen:
raise ValueError(f"duplicate fence row: {key}")
seen.add(key)
def _year(period: str) -> int | None:
part = period.split(":")[-1]
if len(part) == 4 and part.isdigit():
return int(part)
return None
def _cell(value: object) -> str:
if value is None:
return "null"
if isinstance(value, float) and value.is_integer():
return str(int(value))
return str(value)
def _peel(ann: Any) -> Any:
origin = get_origin(ann)
if origin in (Union, UnionType):
args = [arg for arg in get_args(ann) if arg is not NoneType]
if len(args) == 1:
return args[0]
return ann
def _is_model(ann: Any) -> bool:
return isinstance(ann, type) and issubclass(ann, BaseModel)
def _is_model_list(ann: Any) -> bool:
return (
get_origin(ann) is list
and len(args := get_args(ann)) == 1
and _is_model(args[0])
)
def _ident(name: str) -> str:
if not name.isidentifier():
raise ValueError(name)
return f'"{name}"'
def _table(name: str) -> str:
schema, table = name.split(".")
if not schema.isidentifier() or not table.isidentifier():
raise ValueError(name)
return f"{schema}.{table}"
def _table_names(con: Any) -> set[str]:
rows = con.execute(
"SELECT table_schema, table_name FROM information_schema.tables"
).fetchall()
return {f"{schema}.{table}" for schema, table in rows}
def _column_names(con: Any, table: str) -> set[str]:
schema, name = table.split(".")
rows = con.execute(
"""
SELECT column_name FROM information_schema.columns
WHERE table_schema = ? AND table_name = ?
""",
[schema, name],
).fetchall()
return {row[0] for row in rows}
def _measure_columns(con: Any, table: str) -> set[str]:
schema, name = table.split(".")
rows = con.execute(
"""
SELECT column_name, data_type FROM information_schema.columns
WHERE table_schema = ? AND table_name = ?
""",
[schema, name],
).fetchall()
return {column for column, data_type in rows if data_type in _NUMERIC_TYPES}

666
tests/pay/test_bounds.py Normal file
View File

@@ -0,0 +1,666 @@
"""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["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
for row in below:
assert row["kind"] == "proposed"
assert row["role"] == "proposed"
assert "below" in row["note"]
assert not bounds.allows(
row["item"], row["name"], float(row["low"]), period=row["period"]
)
final = index(bounds.load())["pfs.gpci", "work_gpci", "2027"]
assert final["kind"] == "unstated"
assert final["rows"] == 0
assert not bounds.allows("pfs.gpci", "work_gpci", 1, 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"
)
assert "uses 0" in got["pfs.medical_equipment", "maintenance_factor", ""]["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"}
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()