feat(pfs): curated family registry with cited membership — HOME-VISITS

This commit is contained in:
kert
2026-11-11 23:08:48 -05:00
parent cfd490e715
commit cb87721a2a
9 changed files with 395 additions and 15 deletions

View File

@@ -110,6 +110,7 @@ pfs = [
"stack[rex]",
"duckdb>=1.5.4",
"narwhals>=2.17.0",
"pyyaml>=6.0.0", # pfs.curated reads curated.yaml
]
qpp = [
"stack[conf]",

View File

@@ -43,10 +43,12 @@ from pfs.codetables import (
write_reaction,
)
from pfs.cpt_load import ingest as cpt_ingest
from pfs.curated import apply_curated, load_curated
from pfs.exposure import build as build_exposures
from pfs.exposure import control_codes
from pfs.extract import extract_codes
from pfs.families import (
CURATED_FAMILIES,
FAMILIES,
HAND_FAMILIES,
derive_families,
@@ -414,15 +416,18 @@ def _print_families(rows: list[Any], *, verbose: bool = False) -> None:
total = len(by_key)
multi = sum(1 for members in by_key.values() if len(members) >= 2)
hand = sum(1 for key in by_key if key in HAND_FAMILIES)
curated = sum(1 for key in by_key if key in CURATED_FAMILIES)
cpt_named = sum(
1
for key, members in by_key.items()
if key not in HAND_FAMILIES and any(r.note for r in members)
if key not in HAND_FAMILIES
and key not in CURATED_FAMILIES
and any(r.note for r in members)
)
other = total - hand - cpt_named
other = total - hand - curated - cpt_named
typer.echo(
f"families: total {total}, multi-code {multi}, cpt-named {cpt_named}, "
f"hand {hand}, other {other}"
f"hand {hand}, curated {curated}, other {other}"
)
@@ -437,7 +442,7 @@ def families(
if write:
with _batch() as con:
ensure_tables(con)
rows = _derive_rows(con)
rows = apply_curated(_derive_rows(con), load_curated())
write_families(con, rows)
_publish()
# refresh_from and printing don't need the write lock open — do

139
src/pfs/curated.py Normal file
View File

@@ -0,0 +1,139 @@
"""Curated code families — membership and links stated by hand, each fact
carrying its own citation (an FR paragraph, an FR/book page, or the RVU
file a code last appears in). Packaged as ``curated.yaml``; ``families``
seeds ``CURATED_FAMILIES`` from it and ``stack pfs families --write``
overlays the rows on the derived table.
"""
from __future__ import annotations
from dataclasses import dataclass
from importlib import resources
from pathlib import Path
from typing import Any, Mapping, Sequence
import yaml
from pfs.codetables import FamilyRow
ROLES = ("base", "add-on", "predecessor", "successor", "member")
KINDS = ("add-on", "modifier", "prolonged-add-on")
@dataclass(frozen=True)
class CuratedMember:
code: str
role: str
since: int | None
until: int | None
item_key: str
p_id: int
page: int
rvu_year: int
@dataclass(frozen=True)
class CuratedLink:
kind: str
target: str
since: int | None
until: int | None
item_key: str
p_id: int
page: int
rvu_year: int
@dataclass(frozen=True)
class CuratedFamily:
key: str
name: str
synonyms: tuple[str, ...]
members: tuple[CuratedMember, ...]
links: tuple[CuratedLink, ...]
@property
def codes(self) -> tuple[str, ...]:
return tuple(sorted({m.code for m in self.members}))
def _cite(entry: Any, where: str) -> tuple[str, int, int, int]:
cite = entry.get("cite") if isinstance(entry, dict) else None
if not isinstance(cite, dict):
raise ValueError(f"{where}: missing cite")
keys = set(cite)
if keys == {"item_key", "p_id"}:
return str(cite["item_key"]), int(cite["p_id"]), 0, 0
if keys == {"item_key", "page"}:
return str(cite["item_key"]), 0, int(cite["page"]), 0
if keys == {"rvu_last_year"}:
return "", 0, 0, int(cite["rvu_last_year"])
raise ValueError(f"{where}: ambiguous cite {sorted(keys)}")
def _year(entry: Mapping[str, Any], field: str) -> int | None:
v = entry.get(field)
return None if v is None else int(v)
def _parse(key: str, raw: Mapping[str, Any]) -> CuratedFamily:
from pfs.families import CODE_RE # lazy: families imports this module
members: list[CuratedMember] = []
for m in raw.get("members") or ():
code = str(m.get("code", "")).strip().upper()
where = f"{key} member {code or m!r}"
if not CODE_RE.fullmatch(code):
raise ValueError(f"{where}: not a CPT/HCPCS code")
role = m.get("role")
if role not in ROLES:
raise ValueError(f"{where}: unknown role {role!r}")
members.append(
CuratedMember(
code, role, _year(m, "since"), _year(m, "until"), *_cite(m, where)
)
)
links: list[CuratedLink] = []
for ln in raw.get("links") or ():
target = str(ln.get("target", "")).strip().upper()
where = f"{key} link {target or ln!r}"
kind = ln.get("kind")
if kind not in KINDS:
raise ValueError(f"{where}: unknown kind {kind!r}")
links.append(
CuratedLink(
kind, target, _year(ln, "since"), _year(ln, "until"), *_cite(ln, where)
)
)
synonyms = tuple(str(s).strip().lower() for s in raw.get("synonyms") or ())
return CuratedFamily(key, str(raw["name"]), synonyms, tuple(members), tuple(links))
def load_curated(path: Path | None = None) -> dict[str, CuratedFamily]:
from pfs.families import normalize_key # lazy: families imports this module
src = path or resources.files("pfs").joinpath("curated.yaml")
data = yaml.safe_load(src.read_text(encoding="utf-8")) or {}
out: dict[str, CuratedFamily] = {}
for raw_key, raw in data.items():
key = normalize_key(str(raw_key))
out[key] = _parse(key, raw)
return out
def curated_rows(families: Mapping[str, CuratedFamily]) -> list[FamilyRow]:
return [
FamilyRow(
f.key, f.name, m.code, m.role, m.since, m.until, m.item_key, m.p_id, ""
)
for f in families.values()
for m in f.members
]
def apply_curated(
derived: Sequence[FamilyRow], curated: Mapping[str, CuratedFamily]
) -> list[FamilyRow]:
claimed = {m.code for f in curated.values() for m in f.members}
kept = [r for r in derived if r.code not in claimed]
return sorted([*kept, *curated_rows(curated)], key=lambda r: (r.key, r.code))

31
src/pfs/curated.yaml Normal file
View File

@@ -0,0 +1,31 @@
# Curated code families: membership with a citation per fact.
# cite is exactly one of {item_key, p_id} | {item_key, page} | {rvu_last_year}.
HOME-VISITS:
name: Home or Residence Services
synonyms: [home visit, home visits, home or residence, residence visit, domiciliary, rest home visit, house call, house calls]
members:
- {code: '99341', role: base, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99342', role: base, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99344', role: base, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99345', role: base, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99347', role: base, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99348', role: base, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99349', role: base, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99350', role: base, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99343', role: predecessor, until: 2022, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99324', role: predecessor, until: 2022, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99325', role: predecessor, until: 2022, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99326', role: predecessor, until: 2022, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99327', role: predecessor, until: 2022, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99328', role: predecessor, until: 2022, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99334', role: predecessor, until: 2022, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99335', role: predecessor, until: 2022, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99336', role: predecessor, until: 2022, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99337', role: predecessor, until: 2022, cite: {item_key: PETM225D, p_id: 1672}}
- {code: '99339', role: predecessor, until: 2022, cite: {rvu_last_year: 2022}}
- {code: '99340', role: predecessor, until: 2022, cite: {rvu_last_year: 2022}}
links:
- {kind: add-on, target: G2211, since: 2026, cite: {item_key: NHRGIHGD, p_id: 1469}}
- {kind: modifier, target: B1, since: 2027, cite: {item_key: JCWARTJD, p_id: 1168}}
- {kind: modifier, target: B2, since: 2027, cite: {item_key: JCWARTJD, p_id: 1205}}
- {kind: prolonged-add-on, target: G0318, since: 2023, cite: {item_key: PETM225D, p_id: 1694}}

View File

@@ -8,6 +8,7 @@ DuckDB, no narwhals — it must import inside the ``llm`` container.
from __future__ import annotations
import functools
import logging
import re
import threading
@@ -85,6 +86,9 @@ class Family:
#: for something else ("cardiac contractility modulation" for CCM);
#: the chat drops such excerpts from a question about this family.
conflicts: tuple[str, ...] = ()
#: True for a family whose membership is curated by hand with a
#: citation per member (``pfs/curated.yaml``).
curated: bool = False
HAND_FAMILIES: dict[str, Family] = {
@@ -140,6 +144,30 @@ HAND_FAMILIES: dict[str, Family] = {
#: registry from its first request onward, not hand families only.
FAMILIES: dict[str, Family] = dict(HAND_FAMILIES)
def _load_curated_families() -> dict[str, Family]:
# Lazy: ``pfs.curated`` imports names from this module.
from pfs.curated import load_curated
return {
k: Family(k, c.name, c.codes, c.synonyms, curated=True)
for k, c in load_curated().items()
}
@functools.cache
def _curated_registry() -> dict[str, Any]:
from pfs.curated import load_curated
return load_curated()
def curated_family(key: str) -> Any:
"""The curated registry entry (members, links, cites) for *key*, or
``None`` when the family is not curated."""
return _curated_registry().get(normalize_key(key))
#: Guards the swap of ``FAMILIES``/``_PHRASE_RE``/``_PHRASE_INDEX``/
#: ``_CODE_INDEX`` in ``refresh_from`` — the chat runs each turn in a
#: threadpool worker, and a reader must never see a half-updated index.
@@ -242,7 +270,9 @@ def _build_registry_index(
code_families.setdefault(code, set()).add(key)
def _key_order(k: str) -> tuple[int, str]:
return (0, k) if k in HAND_FAMILIES else (1, k)
if k in HAND_FAMILIES:
return (0, k)
return (1, k) if families[k].curated else (2, k)
code_index = {
code: tuple(sorted(keys, key=_key_order))
@@ -269,7 +299,13 @@ def rebuild_index() -> None:
_PHRASE_RE, _PHRASE_INDEX, _CODE_INDEX = _build_registry_index(FAMILIES)
rebuild_index() # seed the index from HAND_FAMILIES
#: Curated families (``pfs/curated.yaml``): seeded into ``FAMILIES`` at
#: import and re-applied by ``refresh_from`` so a derived key never
#: replaces one. Built here, after every name ``pfs.curated`` imports exists.
CURATED_FAMILIES: dict[str, Family] = _load_curated_families()
FAMILIES.update(CURATED_FAMILIES)
rebuild_index() # seed the index from HAND_FAMILIES + CURATED_FAMILIES
def family_of(code: str) -> Family | None:
@@ -1009,6 +1045,7 @@ def refresh_from(con: Any) -> int:
return 0
merged = dict(HAND_FAMILIES)
merged.update(derived)
merged.update(CURATED_FAMILIES)
phrase_re, phrase_index, code_index = _build_registry_index(merged)
global _PHRASE_RE, _PHRASE_INDEX, _CODE_INDEX
with _REGISTRY_LOCK:

View File

@@ -446,8 +446,9 @@ class TestFamilies:
# No pfs.cpt_* rows seeded in this test — the summary line must
# still print, with cpt-named at 0 (I4: read-only-tolerant path
# also applies to the write path when the CPT tables are empty).
assert "families: total 2, multi-code 1, cpt-named 0, hand 1, other 1" in (
res.output
assert (
"families: total 3, multi-code 2, cpt-named 0, hand 1, curated 1, other 1"
in (res.output)
)
def test_verbose_prints_the_per_family_dump(self, con):
@@ -1199,3 +1200,21 @@ class TestUtilization:
assert "no utilization table yet" in res.output
finally:
bare.close()
class TestFamiliesCurated:
def test_families_write_applies_curated(self, con, monkeypatch):
from pfs.codetables import FamilyRow
derived = [
FamilyRow(
"NEW-PATIENT", "New Patient", "99341", "base", 2015, None, "", 0, ""
)
]
monkeypatch.setattr(pfs_cli, "_derive_rows", lambda c: derived)
res = runner.invoke(app, ["pfs", "families", "--write"])
assert res.exit_code == 0, res.output
fams = read_families(con)
assert [r.key for r in fams if r.code == "99341"] == ["HOME-VISITS"]
assert len([r for r in fams if r.key == "HOME-VISITS"]) == 20
assert "curated 1" in res.output

119
tests/pfs/test_curated.py Normal file
View File

@@ -0,0 +1,119 @@
"""pfs.curated — the hand-curated, cited family registry."""
from __future__ import annotations
import pytest
from pfs.codetables import FamilyRow
from pfs.curated import apply_curated, curated_rows, load_curated
def _write(tmp_path, body):
p = tmp_path / "c.yaml"
p.write_text(body)
return p
def test_packaged_home_visits_loads():
fam = load_curated()["HOME-VISITS"]
assert len(fam.codes) == 20 and "99343" in fam.codes and "G2211" not in fam.codes
assert {(link.kind, link.target) for link in fam.links} >= {
("add-on", "G2211"),
("modifier", "B1"),
("modifier", "B2"),
("prolonged-add-on", "G0318"),
}
m = next(m for m in fam.members if m.code == "99343")
assert (m.role, m.until, m.item_key, m.p_id) == (
"predecessor",
2022,
"PETM225D",
1672,
)
g = next(link for link in fam.links if link.target == "G0318")
assert (g.item_key, g.p_id, g.since) == ("PETM225D", 1694, 2023)
old = next(m for m in fam.members if m.code == "99339")
assert (old.item_key, old.p_id, old.rvu_year) == ("", 0, 2022)
def test_page_cite_and_key_normalised(tmp_path):
p = _write(
tmp_path,
"fam-x:\n name: X\n synonyms: [' Foo Bar ']\n members:\n"
" - {code: g0318, role: member, cite: {item_key: K, page: 7}}\n",
)
fam = load_curated(p)["FAM-X"]
assert fam.synonyms == ("foo bar",)
m = fam.members[0]
assert (m.code, m.page, m.p_id, m.since, m.until) == ("G0318", 7, 0, None, None)
assert fam.links == ()
@pytest.mark.parametrize(
"member, needle",
[
("{code: '99341', role: base}", "missing cite"),
("{code: '99341', role: base, cite: {item_key: K}}", "ambiguous cite"),
(
"{code: '99341', role: base, cite: {item_key: K, p_id: 1, page: 2}}",
"ambiguous",
),
("{code: '99341', role: bogus, cite: {rvu_last_year: 2022}}", "unknown role"),
("{code: 'ABC', role: base, cite: {rvu_last_year: 2022}}", "not a CPT"),
],
)
def test_bad_member_rejected(tmp_path, member, needle):
p = _write(tmp_path, f"F:\n name: F\n members:\n - {member}\n")
with pytest.raises(ValueError, match=needle) as e:
load_curated(p)
assert "F member" in str(e.value)
def test_bad_link_rejected(tmp_path):
p = _write(
tmp_path,
"F:\n name: F\n links:\n - {kind: nope, target: B1, cite: {rvu_last_year: 1}}\n",
)
with pytest.raises(ValueError, match="F link .B1.: unknown kind"):
load_curated(p)
def test_empty_file_is_empty(tmp_path):
assert load_curated(_write(tmp_path, "")) == {}
def test_curated_rows_carry_cite():
rows = curated_rows(load_curated())
r = next(r for r in rows if r.code == "99343")
assert (r.key, r.role, r.until, r.item_key, r.p_id, r.note) == (
"HOME-VISITS",
"predecessor",
2022,
"PETM225D",
1672,
"",
)
assert len(rows) == 20
def test_apply_curated_claims_codes():
derived = [
FamilyRow(
"NEW-PATIENT",
"New Patient",
"99341",
"base",
2015,
None,
"",
0,
"E/M > Home",
),
FamilyRow(
"NEW-PATIENT", "New Patient", "99202", "base", 2015, None, "", 0, "E/M"
),
]
rows = apply_curated(derived, load_curated())
assert [r.key for r in rows if r.code == "99341"] == ["HOME-VISITS"]
assert [r.key for r in rows if r.code == "99202"] == ["NEW-PATIENT"]
assert rows == sorted(rows, key=lambda r: (r.key, r.code))

View File

@@ -77,7 +77,7 @@ class TestRegistry:
assert family_of("00000") is None
def test_all_families_present(self):
assert set(FAMILIES) == {"ACP", "CCM", "PCM", "TCM", "APCM"}
assert set(FAMILIES) == {"ACP", "CCM", "PCM", "TCM", "APCM", "HOME-VISITS"}
class TestDetectCodes:
@@ -1460,7 +1460,7 @@ class TestLoadAndRefresh:
# the derived (superset) codes; every other hand key survives
# untouched since `refresh_from` seeds from HAND_FAMILIES
# first instead of clearing the registry outright.
assert n == len(HAND_FAMILIES)
assert n == len(HAND_FAMILIES) + len(mod.CURATED_FAMILIES)
assert set(mod.FAMILIES) >= set(HAND_FAMILIES)
assert set(mod.FAMILIES["CCM"].codes) == {"99490", "G2058"}
assert mod.FAMILIES["CCM"].name == HAND_FAMILIES["CCM"].name
@@ -1680,3 +1680,28 @@ class TestLoadAndRefresh:
load_families(con)
finally:
con.close()
class TestCurated:
def test_curated_detected_by_synonym(self, restore_families):
d = detect_codes("how have home visits been valued?")
assert "HOME-VISITS" in d.families and "99343" in d.codes
def test_curated_survives_refresh(self, restore_families, monkeypatch):
import pfs.codetables as ct
from pfs.families import curated_family, refresh_from
rows = [FamilyRow("HOME-VISITS", "Derived", "99341", "base", None, None, "", 0)]
monkeypatch.setattr(ct, "read_families", lambda con: rows)
refresh_from(object())
assert len(restore_families.FAMILIES["HOME-VISITS"].codes) == 20
assert restore_families.FAMILIES["HOME-VISITS"].curated
assert curated_family("home-visits").key == "HOME-VISITS"
assert curated_family("ACP") is None
def test_family_of_prefers_curated_over_derived(self, restore_families):
restore_families.FAMILIES["NEW-PATIENT"] = Family(
"NEW-PATIENT", "New Patient", ("99341",), ()
)
rebuild_index()
assert family_of("99341").key == "HOME-VISITS"

14
uv.lock generated
View File

@@ -1,5 +1,5 @@
version = 1
revision = 5
revision = 3
requires-python = ">=3.12"
resolution-markers = [
"python_full_version >= '3.14' and sys_platform == 'win32'",
@@ -14,7 +14,7 @@ resolution-markers = [
]
[options]
exclude-newer = "0001-01-01T00:00:00Z" # This has no effect and is included for backwards compatibility when using relative exclude-newer values.
exclude-newer = "2026-11-05T04:05:52.694508849Z"
exclude-newer-span = "P7D"
[options.exclude-newer-package]
@@ -1648,8 +1648,8 @@ name = "httpcore2"
version = "2.16.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "h11" },
{ name = "truststore" },
{ name = "h11", marker = "sys_platform != 'emscripten'" },
{ name = "truststore", marker = "sys_platform != 'emscripten'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/c0/61/afa9d6b7452f9eca73f73d45324eb0bb52f098fd5e6049bf6b8263be9b4e/httpcore2-2.16.0.tar.gz", hash = "sha256:c72cd0413563b17e1cd8354677dff887466f8ec2551679759e93126534428643", size = 69886, upload-time = "2026-10-21T07:09:45.31Z" }
wheels = [
@@ -4127,7 +4127,7 @@ name = "pyzmq"
version = "27.2.0"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "cffi", marker = "implementation_name == 'pypy'" },
{ name = "cffi", marker = "implementation_name == 'pypy' and sys_platform != 'emscripten'" },
]
sdist = { url = "https://files.pythonhosted.org/packages/e7/8d/5b3d5631c2f4b4b8862f64cd0c9eb777b5710eeb5125b4be8dd0a200a4c0/pyzmq-27.2.0.tar.gz", hash = "sha256:54d4259d1bfae24ecdb5ca79f7acc2eac6c286a02d6a0ae617797cb45f0726d3", size = 292316, upload-time = "2026-08-20T19:08:21.19Z" }
wheels = [
@@ -4824,6 +4824,7 @@ notebooks = [
{ name = "openpyxl" },
{ name = "pyarrow" },
{ name = "pydantic" },
{ name = "pyyaml" },
{ name = "sqlglot" },
]
opps = [
@@ -4853,6 +4854,7 @@ pfs = [
{ name = "narwhals" },
{ name = "pyarrow" },
{ name = "pydantic" },
{ name = "pyyaml" },
]
prisma = [
{ name = "anthropic" },
@@ -4878,6 +4880,7 @@ rec = [
{ name = "narwhals" },
{ name = "pyarrow" },
{ name = "pydantic" },
{ name = "pyyaml" },
{ name = "typer" },
]
rex = [
@@ -4984,6 +4987,7 @@ requires-dist = [
{ name = "pymupdf", specifier = ">=1.27.2,<2" },
{ name = "python-docx", specifier = ">=1.1" },
{ name = "pyyaml", marker = "extra == 'llm'", specifier = ">=6.0.0" },
{ name = "pyyaml", marker = "extra == 'pfs'", specifier = ">=6.0.0" },
{ name = "pyyaml", marker = "extra == 'prisma'", specifier = ">=6.0.0" },
{ name = "resend", marker = "extra == 'mail'", specifier = ">=2.0.0" },
{ name = "resend", marker = "extra == 'prisma'", specifier = ">=2.0.0" },