Files
stack/tests/pfs/test_dossier.py
kert 481cd3f2e5 feat(pfs): dossier assembly — cited facts, computed gaps, model prose behind a sentence-level citation check
pfs.cite (Cite + builders; rule_label moved from llm.lineage and re-exported),
pfs.citecheck (sentence split, number normalization, check_prose; plus
grounding_problems: words, codes and CMS-vs-ours attribution of model prose),
pfs.dossier (facts with resolved cites from every Task 1-12 table, timeline,
stakeholder panels with names from pfs.commenter, stance accuracy beside every
count, computed coverage gaps, ledgered model prose with template fallback,
pfs.dossier table), llm.search item_keys filter, `stack pfs dossier`.
Lineage rows reach the dossier only when a final rule's own plain sentence
states them. HOME-VISITS live: 558 facts, 28 timeline events, check passed,
prose model:qwen2.5:14b+template (8 of 29 units on templates).
2026-11-12 23:07:03 -05:00

1865 lines
59 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""pfs.dossier — the cited, checked dossier of one code family (task 13)."""
from __future__ import annotations
import dataclasses
import json
import re
import duckdb
import pytest
from pfs import dossier as dos
from pfs.cite import Cite
from pfs.citecheck import check_prose
from pfs.codetables import (
EventRow,
GuidelineFactRow,
ImpactRow,
OriginRow,
RoundRow,
SeatRow,
ensure_tables,
write_events,
write_guideline_facts,
write_origin,
write_rounds,
write_seats,
write_specialty_impacts,
)
from pfs.dossier import (
Dossier,
Excerpt,
Fact,
TimelineEvent,
build_dossier,
cms_summary_text,
collect_facts,
coverage,
dossier_families,
event_fact_text,
governance_excerpts,
link_text,
read_dossier,
round_text,
stance_split_text,
template_event_line,
template_summary,
timeline,
write_dossier,
write_prose,
)
from pfs.runlog import RunLog
from tests.pfs.home_visits_fixture import FakeAsk
def _by_kind(facts):
out = {}
for f in facts:
out.setdefault(f.kind, []).append(f)
return out
def _texts(facts, kind):
return [f.text for f in facts if f.kind == kind]
# ── fixed template copy ──────────────────────────────────────────────
def test_round_template_copy():
assert (
round_text(2023, "99341", ruc=1.0, final=1.0, decision="accept")
== "For CY2023, the RUC recommended a work RVU of 1.00 for 99341 and CMS "
"finalized 1.00 (accept)."
)
assert (
round_text(2023, "99341", proposed=1.0)
== "For CY2023, CMS proposed a work RVU of 1.00 for 99341."
)
assert (
round_text(2008, "99326", ruc=2.27, final=2.63, decision="")
== "For CY2008, the RUC recommended a work RVU of 2.27 for 99326 and CMS "
"finalized 2.63."
)
assert (
round_text(2008, "99326", final=2.63)
== "For CY2008, CMS finalized a work RVU of 2.63 for 99326."
)
assert (
round_text(2008, "99326", ruc=2.27)
== "For CY2008, the RUC recommended a work RVU of 2.27 for 99326."
)
assert round_text(2008, "99326") == ""
@pytest.mark.parametrize(
"q,stance,want",
[
(
"majority",
"support",
"CMS reported that a majority of commenters supported the proposal (CY2023 final rule).",
),
(
"many",
"modify",
"CMS reported that many commenters asked for changes (CY2023 final rule).",
),
(
"several",
"oppose",
"CMS reported that several commenters opposed the proposal (CY2023 final rule).",
),
(
"some",
"mixed",
"CMS reported that some commenters were divided (CY2023 final rule).",
),
(
"few",
"unclear",
"CMS reported that a few commenters commented (CY2023 final rule).",
),
(
"all",
"support",
"CMS reported that all commenters supported the proposal (CY2023 final rule).",
),
(
"unspecified",
"support",
"CMS reported that commenters supported the proposal (CY2023 final rule).",
),
(
"one",
"support",
"CMS reported that one commenter supported the proposal (CY2023 final rule).",
),
(
"one",
"mixed",
"CMS reported that one commenter gave a mixed view (CY2023 final rule).",
),
],
)
def test_cms_summary_template(q, stance, want):
assert cms_summary_text(q, stance, 2023, "final") == want
def test_stance_split_template():
assert (
stance_split_text(12, 2023, "the work RVU valuation", 6, 2, 3, 1)
== "Of 12 CY2023 commenters we classified on the work RVU valuation, 6 "
"supported, 2 asked for modifications, 3 opposed and 1 were unclear."
)
@pytest.mark.parametrize(
"kind,want",
[
("deleted", "99343 was deleted for CY2023."),
("cpt_panel", "99343 was acted on by the CPT Editorial Panel for CY2023."),
("disappeared", "99343 no longer appears in the PFS RVU file from CY2023."),
("misvalued", "99343 was named as potentially misvalued for CY2023."),
("created", "99343 was created for CY2023."),
(
"telehealth_list",
"99343 is named in a telehealth-list paragraph of the CY2023 rule.",
),
("appeared", "99343 first appears in the PFS RVU file in CY2023."),
(
"descriptor_change",
"99343's short descriptor in the PFS RVU file changed for CY2023.",
),
("bundled", "99343 was bundled for CY2023."),
],
)
def test_event_templates(kind, want):
assert event_fact_text(kind, "99343", 2023) == want
def test_directional_and_noted_event_templates():
assert (
event_fact_text("replaced_by", "G2211", 2027, to=("99212", "99215"))
== "G2211 was replaced by 99212 and 99215 for CY2027."
)
assert event_fact_text("replaces", "99341", 2023, from_=("99343",)) == (
"99341 replaced 99343 for CY2023."
)
assert event_fact_text("crosswalk", "G2211", 2026, to=("90785",)) == (
"G2211 was crosswalked to 90785 for CY2026."
)
assert event_fact_text("revalued", "99344", 2023, note="-18.3%") == (
"99344's non-facility total RVUs changed by -18.3% in the CY2023 RVU file."
)
assert event_fact_text("status_change", "G2211", 2024, note="B→A") == (
"G2211's payment status changed (B→A) in the CY2024 RVU file."
)
assert event_fact_text("telehealth_list", "99341", 2027).startswith(
"99341 is named in a telehealth-list paragraph"
)
def test_link_template():
assert (
link_text(2026, "G2211", "add-on")
== "From CY2026, G2211 can be reported with this family (add-on)."
)
# ── facts over the fixture ───────────────────────────────────────────
def test_every_fact_has_cite_url_or_locator(home_fixture):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
assert len(facts) > 60
assert [f.id for f in facts] == [f"F{i}" for i in range(1, len(facts) + 1)]
for f in facts:
assert f.cite.url or f.cite.locator, f
assert f.kind in dos.FACT_KINDS
# ids follow (year, kind order, code)
keys = [dos._order_key(f) for f in facts]
assert keys == sorted(keys)
def test_facts_by_kind(home_fixture):
con, store, family, _ask = home_fixture
by = _by_kind(collect_facts(con, store, family))
assert {
"origin",
"formation",
"event",
"round",
"cms_summary",
"stance_split",
"link",
"payment",
"impact",
"money",
"seat",
} <= set(by)
rounds = _texts(by["round"], "round")
# golden values from the FR text: Table 14 (CY2008) and ¶1676/¶1685 (CY2023)
assert (
"For CY2008, the RUC recommended a work RVU of 2.27 for 99326 and CMS "
"finalized 2.63 (refine)." in rounds
)
assert (
"For CY2023, the RUC recommended a work RVU of 1.00 for 99341 and CMS "
"finalized 1.00 (accept)." in rounds
)
assert "For CY2023, CMS proposed a work RVU of 3.60 for 99350." in rounds
assert (
"For CY2023, the RUC recommended the survey median value for 99350." in rounds
)
assert (
"For CY2023, the RUC recommended the survey 25th percentile value for 99341."
in rounds
)
assert "For CY2008, commenters requested a work RVU of 2.85 for 99326." in rounds
events = _texts(by["event"], "event")
assert "99343 was deleted for CY2023." in events
assert "99343 no longer appears in the PFS RVU file from CY2023." in events
# identical facts deduped: one per code and kind
assert events.count("99343 was deleted for CY2023.") == 1
def test_final_value_cites_the_finalizing_paragraph(home_fixture):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
f = next(
f
for f in facts
if f.kind == "round"
and f.text.startswith(
"For CY2023, the RUC recommended a work RVU of 1.00 for 99341"
)
)
assert (f.cite.item_key, f.cite.p_id) == ("PETM225D", 1685)
assert ("PETM225D", 1676) in {(c.item_key, c.p_id) for c in f.also}
t14 = next(
f
for f in facts
if f.text.startswith(
"For CY2008, the RUC recommended a work RVU of 2.27 for 99326"
)
)
assert t14.cite.kind == "fr_page"
assert t14.cite.label == "CY2008 PFS final 72 FR 66361 Table 14"
deleted = next(f for f in facts if f.text == "99343 was deleted for CY2023.")
assert (deleted.cite.item_key, deleted.cite.p_id) == ("PETM225D", 1672)
def test_proposed_rule_events_never_state_a_change(home_fixture):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
# G2211's CY2027 "replaced_by" event rests on the proposed rule (5ITGVDJV)
assert not [f for f in facts if f.kind == "event" and "G2211" in f.codes]
assert not [f for f in facts if f.cite.item_key == "MZ24MX5S" and f.kind == "event"]
def test_link_facts_cite_the_finalization(home_fixture):
con, store, family, _ask = home_fixture
links = [f for f in collect_facts(con, store, family) if f.kind == "link"]
g = next(f for f in links if f.text.startswith("From CY2023, G0318"))
assert (
g.text
== "From CY2023, G0318 can be reported with this family (prolonged-add-on)."
)
assert (g.cite.item_key, g.cite.p_id) == ("PETM225D", 1694)
alias = next(f for f in links if "GXXX3" in f.text)
assert (
alias.text
== "In the CY2023 proposed rule, G0318 was the placeholder code GXXX3."
)
assert (alias.cite.item_key, alias.cite.p_id) == ("MZ24MX5S", 880)
def test_link_target_events_before_since_excluded(home_fixture):
con, store, family, _ask = home_fixture
write_events(
con,
"G0318",
[
# R92: an ESRD-era G0318 in CY2007, before the link's since (2023)
EventRow(
"G0318",
2007,
"crosswalk",
"",
"99341",
"PETM225D",
1694,
69610,
"fr",
True,
"",
),
# ¶1694: "we are finalizing our proposal to create new code G0318"
EventRow(
"G0318",
2023,
"created",
"",
"",
"PETM225D",
1694,
69610,
"fr",
True,
"",
),
# ¶1694 says nothing about the telehealth list
EventRow(
"G0318",
2023,
"telehealth_list",
"",
"",
"PETM225D",
1694,
69610,
"fr",
True,
"",
),
],
)
events = [
f
for f in collect_facts(con, store, family)
if f.kind == "event" and f.codes == ("G0318",)
]
assert [f.text for f in events] == ["G0318 was created for CY2023."]
assert events[0].values["event_kind"] == "created"
def _add_paragraph(store, p_id, text):
"""A test-only paragraph in the CY2023 final rule (invented wording)."""
store._con().execute(
"INSERT INTO fr_anchors (item_key, p_id, page, ordinal, text) "
"VALUES ('PETM225D', ?, 69700, 1, ?)",
(p_id, text),
)
store._con().commit()
def test_event_wording_checks(home_fixture):
con, store, family, _ask = home_fixture
_add_paragraph(
store, 99001, "We are adding 99341 to the Medicare Telehealth Services List."
)
_add_paragraph(store, 99002, "We replaced code 99342 with a new code.")
_add_paragraph(store, 99003, "Code 99344 was replaced by 99345 for this year.")
_add_paragraph(store, 99004, "We crosswalked 99347 to 84571 for this year.")
write_events(
con,
"99347",
# 84571 is an FR page number, not a code: a crosswalk to nothing
[
EventRow(
"99347",
2023,
"crosswalk",
"",
"84571",
"PETM225D",
99004,
69700,
"fr",
True,
"",
)
],
)
write_events(
con,
"99341",
[
EventRow(
"99341",
2023,
"telehealth_list",
"",
"",
"PETM225D",
99001,
69700,
"fr",
True,
"",
)
],
)
write_events(
con,
"99342",
[
EventRow(
"99342",
2023,
"replaced_by",
"",
"99345",
"PETM225D",
99002,
69700,
"fr",
True,
"",
)
],
)
write_events(
con,
"99344",
[
EventRow(
"99344",
2023,
"replaced_by",
"",
"99345",
"PETM225D",
99003,
69700,
"fr",
True,
"",
)
],
)
texts = _texts(collect_facts(con, store, family), "event")
assert "99341 is named in a telehealth-list paragraph of the CY2023 rule." in texts
# the sentence names no replacement code: nothing stated
assert not [t for t in texts if t.startswith("99342 was replaced")]
assert "99344 was replaced by 99345 for CY2023." in texts
assert not [t for t in texts if "crosswalked" in t]
def test_comment_paragraph_events_are_dropped(home_fixture):
con, store, family, _ask = home_fixture
write_events(
con,
"99341",
[
EventRow(
"99341",
2023,
"created",
"",
"",
"PETM225D",
1681,
69609,
"fr",
True,
"",
)
],
)
assert "99341 was created for CY2023." not in _texts(
collect_facts(con, store, family), "event"
)
def test_cfr_typo_dropped(home_fixture):
con, store, family, _ask = home_fixture
write_origin(
con,
family.key,
[
OriginRow(
family.key,
"99341",
"regulation",
"42 CFR 25.400(c)(1)(vi)",
None,
"CMS guidance for 99341 points to 42 CFR 25.400(c)(1)(vi).",
"cfr",
"PETM225D",
3607,
"",
"42 CFR 25.400(c)(1)(vi)",
"guidance",
),
OriginRow(
family.key,
"99341",
"regulation",
"42 CFR 425.400",
None,
"CMS guidance for 99341 points to 42 CFR 425.400.",
"cfr",
"PETM225D",
3607,
"",
"42 CFR 425.400",
"guidance",
),
],
)
texts = _texts(collect_facts(con, store, family), "origin")
assert not [t for t in texts if "25.400(c)(1)(vi)" in t]
assert "CMS guidance for 99341 points to 42 CFR 425.400." in texts
def test_origin_rows_consolidate_codes(home_fixture):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
statute = [
f for f in facts if f.kind == "origin" and "primary care services" in f.text
]
assert len(statute) == 1
assert statute[0].codes == (
"99341",
"99342",
"99344",
"99345",
"99347",
"99348",
"99349",
"99350",
)
assert (
statute[0].also and statute[0].also[0].p_id == 2818
) # the reference paragraph
panel = [
f
for f in facts
if f.kind == "formation"
and f.text.startswith("The CPT Editorial Panel deleted 99324")
]
assert panel[0].text == (
"The CPT Editorial Panel deleted 99324–99328, 99334–99337 and 99343, "
"effective CY2023."
)
guidance = next(f for f in facts if "100-04 ch.26" in f.text)
assert guidance.cite.kind == "iom" and guidance.cite.locator == "100-04 ch.26"
cfr = next(f for f in facts if "42 CFR 425.400" in f.text)
assert cfr.cite.url.startswith("https://www.ecfr.gov/")
def test_guideline_facts(home_fixture):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
texts = [f.text for f in facts]
assert (
"In the CPT 2022 codebook, 99341 is selected on history, examination and "
"medical decision making, with straightforward medical decision making and a "
"typical time of 20 minutes." in texts
)
change = next(
f for f in facts if f.text.startswith("In the CPT 2024 codebook, 99341")
)
assert change.kind == "event"
assert "medical decision making or total time" in change.text
assert "a time threshold of 15 minutes" in change.text
assert change.cite.label == "CPT 2024 p. 29"
deleted = next(f for f in facts if f.text.startswith("CPT deleted"))
assert deleted.text == (
"CPT deleted 99324 and 99343 in its 2023 code set (last listed in the "
"2022 edition)."
)
assert deleted.cite.label == "CPT 2023 p. 48"
scope = next(
f for f in facts if f.text.startswith("Fixture paraphrase: these visits")
)
assert scope.note == "model paraphrase, unreviewed"
panel = next(f for f in facts if "merged the domiciliary codes" in f.text)
assert panel.note == "model paraphrase, unreviewed"
assert panel.cite.label.endswith("tab 10, PDF p. 4")
def test_cms_summary_and_stance_split_are_separate_facts(home_fixture):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
cms = [f for f in facts if f.kind == "cms_summary"]
ours = [f for f in facts if f.kind == "stance_split"]
assert (
"CMS reported that a majority of commenters supported the proposal (CY2023 final rule)."
in [f.text for f in cms]
)
majority = next(f for f in cms if "majority" in f.text)
assert (majority.cite.item_key, majority.cite.p_id) == ("PETM225D", 1679)
val = next(f for f in ours if "work RVU valuation" in f.text)
assert val.text.startswith(
"Of 3 CY2023 commenters we classified on the work RVU valuation, 1 supported, "
"1 asked for modifications, 1 opposed and 0 were unclear."
)
# CMS's characterization and our counts never share a fact or a cite
assert not {f.id for f in cms} & {f.id for f in ours}
assert all(f.cite.kind == "fr_para" for f in cms)
assert all(f.cite.kind == "dataset" for f in ours)
assert all("CMS reported" not in f.text for f in ours)
assert all("we classified" not in f.text for f in cms)
def test_stance_accuracy_beside_every_count(home_fixture):
con, store, family, _ask = home_fixture
ours = [f for f in collect_facts(con, store, family) if f.kind == "stance_split"]
assert len(ours) == 5 # four events and the docket
for f in ours:
assert "held-out set the prompt was never tuned on" in f.text
assert "79%" in f.text and "74%" in f.text
assert "CMS-2025-0304" in f.text and "CMS-2026-2377" in f.text
assert f.values["recall"] == 0.792
docket = next(f for f in ours if "docket" in f.text.split(".")[0])
assert docket.text.startswith(
"Of 6 CY2023 commenters on this family in docket CMS-2022-0113, we "
"classified 4 with a firm position: 2 supported, 1 asked for modifications "
"and 1 opposed; 1 more was unclear."
)
# the unclassified docket is "not classified", never 0/0
assert not [f for f in ours if "CMS-2025-0304," in f.text.split("(")[0]]
def test_stance_accuracy_line_variants():
tuned = dos.stance_accuracy_line(
{
"recall": 0.5,
"direction": 0.75,
"n_items": 20,
"n_positions": 27,
"docket": "CMS-2022-0113",
"in_sample": True,
}
)
assert "on the tuning set" in tuned and "CMS-2022-0113" in tuned
assert (
dos.stance_accuracy_line(None)
== "Preliminary model classification; its accuracy is not yet measured."
)
def test_money_facts(home_fixture):
con, store, family, _ask = home_fixture
money = [f for f in collect_facts(con, store, family) if f.kind == "money"]
texts = [f.text for f in money]
assert (
"For CY2023, the family gained new payment through G0318 (new, amount n/a)."
in texts
)
np_ = [t for t in texts if t.startswith("For CY2023, NURSE PRACTITIONER")]
assert np_ and "at least 100 of the family's services" in np_[0]
assert "(CMS suppresses lines under 11 services)" in np_[0]
assert not [t for t in texts if "$-" in t or "at least $-" in t]
assert all("new, amount n/a" not in t for t in texts if "billed" in t)
def test_lower_bound_cut_wording():
assert dos.money_change(-1234.4, lower_bound=True) == "a cut of at least $1,234"
assert (
dos.money_change(1234.4, lower_bound=True) == "an increase of at least $1,234"
)
assert dos.money_change(-5.0, lower_bound=False) == "a cut of $5"
assert dos.money_change(0.0, lower_bound=False) == "no change"
assert dos.money_change(None, lower_bound=False) == ""
def test_seat_facts_use_the_prior_year_roster(home_fixture):
con, store, family, _ask = home_fixture
seats = [f.text for f in collect_facts(con, store, family) if f.kind == "seat"]
assert (
"On the 2022 RUC roster (the RUC that valued CY2023 met in 2022), FAMILY "
"PRACTICE held 1 permanent and 0 rotating seats." in seats
)
assert (
"On the 2022 RUC roster, the Primary Care Rotating Seat is a rotating seat."
in seats
)
assert any(
t.startswith(
"The 2026 CPT Editorial Panel roster lists 12 seats for national medical specialty societies"
)
for t in seats
)
def test_roster_year_falls_back_to_the_rule_year():
assert dos.roster_year({2023}, 2023) == (
2023,
" (the roster of CY2023 itself; the 2022 roster is not captured)",
)
assert dos.roster_year({2022, 2023}, 2023) == (
2022,
" (the RUC that valued CY2023 met in 2022)",
)
assert dos.roster_year(set(), 2023) == (None, "")
def test_impact_facts(home_fixture):
con, store, family, _ask = home_fixture
impact = [f.text for f in collect_facts(con, store, family) if f.kind == "impact"]
assert (
"CMS estimated the CY2023 final rule's combined impact on allowed charges "
"for Family Practice at 1%." in impact
)
assert not [t for t in impact if "Portable X-Ray" in t]
def test_payment_facts_and_rows(home_fixture):
con, store, family, _ask = home_fixture
d = build_dossier(con, store, family)
pay = [f for f in d.facts.values() if f.kind == "payment"]
assert pay and all(f.cite.kind == "rvu_file" for f in pay)
assert any(
f.text.startswith("For CY2027, CMS proposed a national non-facility payment")
for f in pay
)
assert all("description" not in row for row in d.payment)
years_99343 = sorted({r["year"] for r in d.payment if r["code"] == "99343"})
assert years_99343[-1] == 2022
def test_coverage_notes_from_data(home_fixture):
con, store, family, _ask = home_fixture
notes = coverage(con, store, family)
assert "Federal Register PFS rules before CY2002 not yet captured." in notes
assert "RVU files before 2015 not yet loaded." in notes
assert "Public comment dockets before the CY2023 rule not yet captured." in notes
assert "Governance literature not yet ingested." in notes
assert (
"Specialty impact rows not matched to a specialty: Portable X-Ray Supplier."
in notes
)
assert (
"RUC rosters captured 2022–2023 (2018–2019 not captured); "
"CPT Panel rosters captured 2026." in notes
)
assert "RUC roster notes: 2024: parsed 31 seats, the page says 32 members." in notes
assert (
"Comment stance classified for 1 of 2 dockets with family commenters (CMS-2022-0113)."
in notes
)
assert not [n for n in notes if n.startswith("No conversion factor")]
def test_coverage_lines_without_data():
con = duckdb.connect(":memory:")
try:
ensure_tables(con)
con.execute("CREATE TABLE pfs.rvu (hcpcs VARCHAR, mod VARCHAR, year INTEGER)")
con.execute("INSERT INTO pfs.rvu VALUES ('99341', NULL, 1990)")
from pfs.curated import load_curated
fam = load_curated()["HOME-VISITS"]
from bib.store import Store
store = Store(":memory:")
try:
notes = coverage(con, store, fam)
finally:
store.close()
assert "Federal Register PFS rules not yet captured." in notes
assert "RUC/CPT Panel seat data not captured." in notes
assert "No conversion factor on file for 1990; payment not computed." in notes
assert "RVU files before 1990 not yet loaded." in notes
finally:
con.close()
def test_commenter_names_come_from_own_record(home_fixture):
con, store, family, _ask = home_fixture
d = build_dossier(con, store, family)
blob = d.to_json()
# the bib title says "Jane Doe: CMS-2022-0113-0001"; the comment's own
# regulations.gov record (pfs.commenter.submitter_name) says Mary Major
assert "Doe" not in blob and "Roe" not in blob and "Poe" not in blob
names = {
name
for panel in d.stakeholders
for unit in panel["units"]
for name in unit["names"]
}
own = {
r[0] or r[1] or "individual commenter"
for r in con.execute(
"SELECT CASE WHEN org_type IN ('individual','individual_clinician') "
"THEN submitter_name ELSE org_name END, org_name FROM pfs.commenter"
).fetchall()
}
assert "Mary Major" in names
assert "American Academy of Home Care Medicine" in names
assert names <= own
def test_stakeholders_pair_new_payment_with_the_link_event(home_fixture):
con, store, family, _ask = home_fixture
d = build_dossier(con, store, family)
by_event = {p["event_key"]: p for p in d.stakeholders}
g = by_event["HOME-VISITS:2023:G0318"]
val = by_event["HOME-VISITS:2023:valuation"]
fp_g = next(
u
for u in g["units"]
if u["specialty"] == "FAMILY PRACTICE" and u["org_type"] == "specialty_society"
)
fp_v = next(
u
for u in val["units"]
if u["specialty"] == "FAMILY PRACTICE" and u["org_type"] == "specialty_society"
)
assert (
fp_g["expected"] == "support"
and "new payment (G0318)" in fp_g["expected_reason"]
)
assert "new payment" not in fp_v["expected_reason"]
assert val["accuracy"].startswith("Preliminary model classification")
assert val["roster_year"] == 2022
assert val["seats"]["FAMILY PRACTICE"]["ruc_permanent"] == 1
lines = dos.stakeholder_lines(d)
assert any("Mary Major" in line for line in lines)
def test_timeline(home_fixture):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
events = timeline(facts)
assert all(isinstance(e, TimelineEvent) for e in events)
years = [e.year for e in events]
assert years == sorted(years)
assert {2008, 2023, 2026, 2027} <= set(years)
by = {(e.year, e.kind): e for e in events}
val23 = by[(2023, "valuation")]
assert val23.stance_fact_ids and val23.cms_summary_fact_ids
ids = {f.id: f for f in facts}
assert all(ids[i].kind == "stance_split" for i in val23.stance_fact_ids)
assert all(ids[i].kind == "cms_summary" for i in val23.cms_summary_fact_ids)
g = by[(2023, "link:G0318")]
assert any("G0318" in ids[i].text for i in g.stance_fact_ids)
deleted = by[(2023, "deleted")]
assert deleted.what_changed.startswith(
"99324–99328, 99334–99337, 99339, 99340 and 99343 were deleted for CY2023 [F"
)
for e in events:
assert check_prose(e.what_changed, ids) == [], e
def test_template_lines_pass_the_check(home_fixture):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
ids = {f.id: f for f in facts}
events = timeline(facts)
for e in events:
assert check_prose(template_event_line(e, ids), ids) == []
assert dos.grounding_problems(template_event_line(e, ids), ids) == []
summary = template_summary(facts, events)
assert 1 <= len(re.findall(r"\[F\d+", summary)) and check_prose(summary, ids) == []
assert len(dos.split_sentences(summary)) <= 5
def _echo(system, user):
"""A well-behaved model: restates the first fact line of the prompt."""
m = re.search(r"^\[(F\d+)\] (.+)$", user, re.M)
return {"text": f"{m.group(2).rstrip('.')} [{m.group(1)}]."}
def test_model_prose_accepted(home_fixture):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
events = timeline(facts)
ask = FakeAsk(default=_echo)
summary, lines, extractor, ok = write_prose(facts, events, ask)
assert ok is True and extractor == "model:fake-14b"
assert len(lines) == len(events)
ids = {f.id: f for f in facts}
assert check_prose(summary, ids) == []
assert all(check_prose(line, ids) == [] for line in lines.values())
assert len(ask.calls) == len(events) + 1
# unreviewed paraphrases never reach the model
assert "Fixture paraphrase" not in "".join(u for _s, u in ask.calls)
def test_prose_rejected_twice_falls_back_to_templates(home_fixture):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
events = timeline(facts)
ask = FakeAsk(default={"text": "CMS accepted the RUC values."})
summary, lines, extractor, ok = write_prose(facts, events, ask)
assert extractor == "template" and ok is True
assert summary == template_summary(facts, events)
ids = {f.id: f for f in facts}
assert lines == {i: template_event_line(e, ids) for i, e in enumerate(events)}
assert len(ask.calls) == 2 * (len(events) + 1) # one retry each
retry = ask.calls[1][1]
assert "uncited" in retry
def test_retry_with_problems_listed_can_succeed(home_fixture):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
events = timeline(facts)[:1]
answers = iter([{"text": "No tag here."}, None])
def first_bad(system, user):
nxt = next(answers, None)
return nxt if nxt is not None or "Problems" not in user else _echo(system, user)
ask = FakeAsk(default=first_bad)
summary, lines, extractor, ok = write_prose(facts, events, ask)
assert extractor.startswith("model:fake-14b")
assert ok
def test_mixed_prose_extractor(home_fixture):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
events = timeline(facts)[:2]
def only_summary(system, user):
return _echo(system, user) if "summary" in system.lower() else {"text": "x"}
summary, lines, extractor, ok = write_prose(
facts, events, FakeAsk(default=only_summary)
)
assert extractor == "model:fake-14b+template"
def test_no_model_means_templates(home_fixture):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
events = timeline(facts)
summary, lines, extractor, ok = write_prose(facts, events, None)
assert (extractor, ok) == ("template", True)
def test_prose_ledger_resumes_and_replays(home_fixture, tmp_path):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
events = timeline(facts)[:3]
log = RunLog(tmp_path / "prose.jsonl")
ask = FakeAsk(default=_echo)
first = write_prose(facts, events, ask, log=log, limit=2)
assert len(ask.calls) == 2
assert first[2] == "model:fake-14b+template"
second = write_prose(facts, events, ask, log=RunLog(tmp_path / "prose.jsonl"))
assert len(ask.calls) == 4 # the two not yet logged
replay = write_prose(
facts,
events,
None,
log=RunLog(tmp_path / "prose.jsonl"),
replay_model="fake-14b",
)
assert replay == second
assert len(ask.calls) == 4
def test_unchecked_model_text_is_never_returned(home_fixture):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
events = timeline(facts)[:1]
# numbers no cited fact carries
ask = FakeAsk(
default=lambda s, u: {"text": f"99341 was paid $999.99 [{facts[0].id}]."}
)
summary, lines, extractor, ok = write_prose(facts, events, ask)
assert "999.99" not in summary and "999.99" not in lines[0]
assert extractor == "template"
# ── assembly, storage, governance ────────────────────────────────────
def test_build_dossier(home_fixture):
con, store, family, _ask = home_fixture
exc = Excerpt(
"A finding about the RUC.",
dos.Cite("study", "Study p. 3", "https://x", "S1", 0, 3),
)
d = build_dossier(con, store, family, excerpts=[exc])
assert d.family == "HOME-VISITS" and d.name == "Home or Residence Services"
assert d.check_passed is True and d.extractor == "template"
assert d.codes == family.codes
assert d.years_active == "CY2008–CY2027"
assert "8 active" in d.status and "12 deleted" in d.status
assert d.governance == [exc]
assert [f for f in d.facts.values() if f.kind == "finding"]
assert d.sources["study"][0]["label"] == "Study p. 3"
assert d.review and all(
r["reason"] == "model paraphrase, unreviewed" for r in d.review
)
assert d.utilization == []
assert d.rounds and all(
"url" in r["cites"]["final_work_rvu"] for r in d.rounds if "final_work_rvu" in r
)
r = next(
r
for r in d.rounds
if r["code"] == "99341" and r["rule_year"] == 2023 and r["rule_kind"] == "final"
)
assert (
"comparators" not in r and "survey_intra_min" not in r
) # never an empty field
assert r["rationale"]["url"].endswith("#p-1685")
assert d.timeline and d.summary
assert d.stance_accuracy.startswith("Preliminary model classification")
def test_json_roundtrip(home_fixture):
con, store, family, _ask = home_fixture
d = build_dossier(con, store, family, ask=FakeAsk(default=_echo))
back = Dossier.from_json(d.to_json())
assert back == d
assert isinstance(back.facts["F1"], Fact)
assert isinstance(back.timeline[0], TimelineEvent)
def test_write_read_dossier(home_fixture):
con, store, family, _ask = home_fixture
assert dossier_families(con) == ()
d = build_dossier(con, store, family)
write_dossier(con, d)
write_dossier(con, d) # delete-then-insert
assert con.execute("SELECT count(*) FROM pfs.dossier").fetchone()[0] == 1
assert dossier_families(con) == ("HOME-VISITS",)
assert read_dossier(con, "HOME-VISITS") == d
assert read_dossier(con, "NOPE") is None
def test_dossier_families_missing_table():
con = duckdb.connect(":memory:")
try:
assert dossier_families(con) == ()
assert read_dossier(con, "X") is None
finally:
con.close()
class _Broken:
def execute(self, *a):
raise RuntimeError("disk on fire")
with pytest.raises(RuntimeError):
dossier_families(_Broken())
with pytest.raises(RuntimeError):
read_dossier(_Broken(), "X")
def test_governance_excerpts(home_fixture, monkeypatch):
_con, store, _family, _ask = home_fixture
assert (
governance_excerpts(object(), object(), store, "Home or Residence Services")
== []
)
from bib.item import Source
key = store.create(
Source(title="RUC study", url="https://example.org/ruc"),
tags=["source:governance-lit"],
)
calls = []
def fake_search(q, *, cfg, pool, collection, item_keys, limit):
calls.append((q, collection, tuple(item_keys), limit))
return [
{
"label": f"RUC study p. 3 [{q[:4]}]",
"url": "https://example.org/ruc#3",
"item_key": key,
"page": "3",
"text": "word " * 100,
},
{
"label": "dup",
"url": "",
"item_key": key,
"page": "",
"text": "short finding",
},
]
monkeypatch.setattr("llm.search.search", fake_search)
got = governance_excerpts(
object(), object(), store, "Home or Residence Services", k=3
)
assert len(got) == 3
assert calls[0] == ("Home or Residence Services valuation", "corpus", (key,), 3)
assert len(calls) == 5
assert all(len(e.text) <= 300 for e in got)
assert got[0].cite.kind == "study" and got[0].cite.page == 3
assert got[0].text.endswith("…")
def test_split_sentences_reexported():
assert dos.split_sentences("A [F1]. B [F2].") == ["A [F1].", "B [F2]."]
def test_fact_dataclass_is_frozen():
f = Fact("F1", "round", 2023, ("99341",), "t", {}, dos.Cite("fr_para", "l", "u"))
with pytest.raises(dataclasses.FrozenInstanceError):
f.text = "x" # type: ignore[misc]
assert json.loads(json.dumps(dos._fact_dict(f)))["id"] == "F1"
# ── edges: every branch of the assembly ──────────────────────────────
def _round(**kw):
base = dict(
family="HOME-VISITS",
code="99341",
rule_year=2020,
item_key="PETM225D",
rule_kind="proposed",
p_id=0,
page=0,
source="fr-para",
table_title="",
ruc_work_rvu=None,
ruc_percentile="",
survey_intra_min=None,
survey_total_min=None,
comparators="",
surveying_societies="",
requested_work_rvu=None,
proposed_work_rvu=None,
final_work_rvu=None,
decision="",
rationale_p_id=0,
rationale_quote="",
pe_note="",
extractor="regex",
final_p_id=0,
ruc_p_id=0,
field_cites="",
)
base.update(kw)
return RoundRow(**base)
def test_rows_reraises_other_errors():
def boom(*a):
raise RuntimeError("not a catalog error")
with pytest.raises(RuntimeError):
dos._rows(boom)
def test_round_edges(home_fixture):
con, store, family, _ask = home_fixture
write_rounds(
con,
family.key,
[
# a proposed-rule RUC value with no final round: its own fact
_round(
code="99342",
ruc_work_rvu=1.65,
proposed_work_rvu=1.6,
p_id=1676,
survey_total_min=97.0,
survey_intra_min=40.0,
comparators="99215",
pe_note="none of note; finalizing removal of supplies",
field_cites=json.dumps({"pe_note": [1677, 1683]}),
),
# no paragraph anywhere: cited to the FR page (table row)
_round(code="99343", ruc_work_rvu=2.0, page=69608),
# a final row with the RUC value only
_round(
code="99344",
rule_kind="final",
ruc_work_rvu=2.87,
p_id=1676,
pe_note="x" * 300,
),
# a correction notice yields nothing
_round(code="99345", rule_kind="correction", final_work_rvu=9.0),
# a final row with nothing to say
_round(code="99347", rule_kind="final"),
],
)
facts = collect_facts(con, store, family)
texts = [f.text for f in facts]
assert "For CY2020, CMS proposed a work RVU of 1.60 for 99342." in texts
assert "For CY2020, the RUC recommended a work RVU of 1.65 for 99342." in texts
assert "For CY2020, the RUC survey total time for 99342 was 97 minutes." in texts
assert (
"For CY2020, the RUC survey intra-service time for 99342 was 40 minutes."
in texts
)
assert "For CY2020, the comparator codes named for 99342 were 99215." in texts
assert "For CY2020, the RUC recommended a work RVU of 2.87 for 99344." in texts
assert not [t for t in texts if "9.00" in t]
page = next(f for f in facts if "2.00 for 99343" in f.text)
assert page.cite.kind == "fr_page" and page.cite.page == 69608
pe = [f for f in facts if f.kind == "pe"]
assert {f.note for f in pe} == {dos.UNREVIEWED_EXTRACT}
pe342 = next(f for f in pe if f.codes == ("99342",))
assert (
pe342.text
== "CY2020 proposed rule, direct PE inputs for 99342: finalizing removal of supplies."
)
assert (pe342.cite.p_id, pe342.also[0].p_id) == (1677, 1683)
pe344 = next(f for f in pe if f.codes == ("99344",))
assert len(pe344.text) < 300
def test_guideline_edges(home_fixture):
con, store, family, _ask = home_fixture
write_guideline_facts(
con,
family.key,
[
GuidelineFactRow(
family.key, "99341", 2021, "addon", "true", "K", "p. 2", "cpt-book"
),
GuidelineFactRow(
family.key, "99341", 2021, "mdm_level", "low", "K", "p. 2", "cpt-book"
),
GuidelineFactRow(
family.key,
"99350",
2021,
"selection_basis",
"other_basis",
"K",
"p. 2",
"cpt-book",
),
GuidelineFactRow(
family.key,
"99341",
2021,
"scope_point",
"A single-code point.",
"K",
"p. 2",
"m",
),
GuidelineFactRow(
family.key,
"99342",
2021,
"scope_point",
"A single-code point.",
"K",
"p. 2",
"m",
),
GuidelineFactRow(
family.key,
"G9999",
2021,
"scope_point",
"Off-family.",
"K",
"p. 2",
"m",
),
GuidelineFactRow(
family.key,
"99341",
2021,
"deleted_in_edition",
"n/a",
"K",
"p. 3",
"cpt-book",
),
],
)
facts = collect_facts(con, store, family)
texts = [f.text for f in facts]
assert (
"In the CPT 2021 codebook, 99341 carries with low medical decision making and add-on status."
in texts
)
assert "In the CPT 2021 codebook, 99350 is selected on other basis." in texts
# identical paraphrases of one year collapse to one fact
assert texts.count("A single-code point.") == 1
off = next(f for f in facts if f.text == "Off-family.")
assert off.codes == ()
odd = next(f for f in facts if f.text.startswith("CPT deleted 99341"))
assert odd.text == "CPT deleted 99341 in its 2021 code set." and odd.year == 2021
def test_origin_edges(home_fixture):
con, store, family, _ask = home_fixture
write_origin(
con,
family.key,
[
OriginRow(
family.key,
"99341",
"cpt_panel",
"CPT Editorial Panel action",
2023,
"Revised the codes.",
"cpt_book",
"3ANRT854",
0,
"49",
"CPT Changes 2023, p. 49",
"model:x@origin-v1",
),
OriginRow(
family.key,
"99342",
"cpt_panel",
"CPT Editorial Panel action",
2023,
"Revised others.",
"cpt_book",
"3ANRT854",
0,
"50",
"no page here",
"model:x@origin-v1",
),
OriginRow(
family.key,
"99341",
"coverage",
"100-04 ch.12 §30.6.14.1",
2019,
"The CY2019 final rule removed a requirement in 100-04 ch.12 §30.6.14.1.",
"iom",
"PETM225D",
1685,
"69609",
"100-04 ch.12 §30.6.14.1; 87 FR 69609",
"guidance",
1684,
),
OriginRow(
family.key,
"99341",
"statute",
"section 1834(m) of the Act",
None,
"A statute about telehealth.",
"fr_para",
"PETM225D",
1672,
"69608",
"87 FR 69608, ¶1672",
"model:x@origin-v1",
1672,
),
],
)
facts = collect_facts(con, store, family)
book = next(f for f in facts if f.text == "Revised the codes.")
assert book.kind == "formation" and book.cite.label == "CPT Changes 2023 p. 49"
nopage = next(f for f in facts if f.text == "Revised others.")
assert nopage.cite.label == "no page here p. 50"
removal = next(
f for f in facts if f.text.startswith("The CY2019 final rule removed")
)
assert removal.cite.kind == "fr_para" and removal.cite.p_id == 1685
assert removal.also[0].kind == "iom" and removal.also[0].p_id == 1684
statute = next(f for f in facts if f.text == "A statute about telehealth.")
assert statute.also[-1] == Cite(
"statute",
"section 1834(m) of the Act",
"https://www.ssa.gov/OP_Home/ssact/title18/1834.htm",
locator="section 1834(m) of the Act",
)
def test_event_edges(home_fixture):
con, store, family, _ask = home_fixture
write_events(
con,
"99341",
[
# not a lineage kind the dossier states
EventRow(
"99341",
2013,
"cpt_changed",
"",
"",
"GQGTPGYV",
0,
0,
"cpt",
True,
"CPT Changes 2013",
),
# an RVU-file row of a kind the RVU file cannot state
EventRow("99341", 2016, "created", "", "", "", 0, 0, "rvu", False, ""),
# a deletion the paragraph does not read as one (¶1685 names no code)
EventRow(
"99341",
2023,
"deleted",
"",
"",
"PETM225D",
1685,
69609,
"fr",
True,
"",
),
# a deletion the sentence names but does not delete (a successor)
EventRow(
"99341",
2023,
"cpt_panel",
"",
"",
"PETM225D",
1672,
69608,
"fr",
True,
"",
),
# an unknown rule item
EventRow("99341", 2023, "created", "", "", "NOSUCH", 3, 1, "fr", True, ""),
# a crosswalk to page numbers only
EventRow(
"99341",
2023,
"crosswalk",
"",
"69608",
"PETM225D",
1672,
69608,
"fr",
True,
"",
),
# a status change keeps its note
EventRow(
"99341", 2024, "status_change", "", "", "", 0, 0, "rvu", True, "A→I"
),
],
)
write_events(
con,
"99343",
[
EventRow(
"99343",
2023,
"deleted",
"",
"",
"PETM225D",
1672,
69608,
"fr",
True,
"",
),
EventRow("99343", 2024, "disappeared", "", "", "", 0, 0, "rvu", True, ""),
EventRow("99343", 2023, "disappeared", "", "", "", 0, 0, "rvu", True, ""),
],
)
events = [f for f in collect_facts(con, store, family) if f.kind == "event"]
texts = [f.text for f in events]
assert "99341's payment status changed (A→I) in the CY2024 RVU file." in texts
assert not [t for t in texts if t.startswith("99341") and "2023" in t]
assert "99343 no longer appears in the PFS RVU file from CY2024." not in texts
assert "99343 no longer appears in the PFS RVU file from CY2023." in texts
def test_known_codes_without_rvu():
con = duckdb.connect(":memory:")
try:
from pfs.curated import load_curated
fam = load_curated()["HOME-VISITS"]
assert dos._known_codes(con, fam) >= {"99341", "G0318"}
class _Broken:
def execute(self, *a):
raise RuntimeError("boom")
with pytest.raises(RuntimeError):
dos._known_codes(_Broken(), fam)
finally:
con.close()
def test_link_edges(home_fixture):
con, store, family, _ask = home_fixture
from pfs.curated import CuratedLink
fam = dataclasses.replace(
family,
links=(
CuratedLink("add-on", "G9001", None, None, "", 0, 0, 0),
CuratedLink("add-on", "G9002", 2024, None, "54GTKR5G", 0, 66361, 0),
CuratedLink("add-on", "G9003", 2025, None, "", 0, 0, 2025),
),
)
links = [f for f in collect_facts(con, store, fam) if f.kind == "link"]
assert [f.codes for f in links] == [("G9002",), ("G9003",)]
assert links[0].cite.kind == "fr_page" and links[1].cite.kind == "rvu_file"
def test_impact_from_the_508_file(home_fixture):
con, store, family, _ask = home_fixture
from bib.item import Source
key = store.create(
Source(title="CY2023 impact file", url="https://cms.example/impact.xlsx")
)
write_specialty_impacts(
con,
2023,
"proposed",
"508",
[
ImpactRow(
2023,
"proposed",
"Family Practice",
"TOTAL",
1.0,
0,
0,
0,
0.02,
"508",
key,
0,
),
ImpactRow(
2023,
"proposed",
"Internal Medicine",
"TOTAL",
1.0,
0,
0,
0,
None,
"508",
"NOSUCH",
0,
),
ImpactRow(
2023,
"proposed",
"Family Practice",
"Facility",
1.0,
0,
0,
0,
0.5,
"508",
key,
0,
),
ImpactRow(
2023, "proposed", "TOTAL", "TOTAL", 1.0, 0, 0, 0, 0.5, "508", key, 0
),
],
)
write_specialty_impacts(
con,
2023,
"final",
"508",
[
ImpactRow(
2023,
"final",
"Family Practice",
"TOTAL",
1.0,
0,
0,
0,
0.03,
"508",
"NOSUCH",
0,
)
],
)
impact = [f for f in collect_facts(con, store, family) if f.kind == "impact"]
p = next(f for f in impact if "proposed" in f.text)
assert p.text.endswith("for Family Practice at 2%.")
assert p.cite.kind == "dataset" and p.cite.url == "https://cms.example/impact.xlsx"
nourl = next(f for f in impact if "at 3%" in f.text)
assert nourl.cite.url == ""
def test_money_edges():
from pfs.stakes import SpecialtyMoney
assert dos._money_facts(2023, [], [], None) == []
m = SpecialtyMoney("FAMILY PRACTICE", 1000.0, None, None, 0.5)
[f] = dos._money_facts(2023, [m], [], None)
assert "no final payment change is computed for those services" in f.text
# no PSPS row on file: the year before the rule year's dataset
assert f.cite.label == "Medicare Physician/Supplier Procedure Summary CY2022"
def test_specialty_vocab_reraises():
class _Broken:
def execute(self, *a):
raise RuntimeError("boom")
with pytest.raises(RuntimeError):
dos._specialty_vocab(_Broken(), set())
def test_payment_rows_without_rvu_tables():
con = duckdb.connect(":memory:")
try:
from pfs.curated import load_curated
assert dos._payment_rows(con, load_curated()["HOME-VISITS"]) == []
class _Broken:
def execute(self, *a):
raise RuntimeError("boom")
with pytest.raises(RuntimeError):
dos._payment_rows(_Broken(), load_curated()["HOME-VISITS"])
finally:
con.close()
def test_payment_fact_for_an_unpaid_status():
from pfs.valuation import ValuationRow
row = ValuationRow(
"G2211",
"",
"CY2022 final",
2022,
False,
"B",
0.33,
0.1,
0.1,
0.01,
0.44,
0.44,
34.6062,
None,
None,
"[PFS CY2022 Addendum B]",
"",
"",
)
[f] = dos._payment_facts([row])
assert (
f.text
== "For CY2022, G2211 carried payment status B, so no national payment is computed."
)
assert f.also == ()
def test_seat_log_edges(home_fixture):
con, _store, _family, _ask = home_fixture
con.execute(
"INSERT INTO cms.ingest_log (module, rule_id, source_file) VALUES "
"('pfs.seats', 'gap', 'no year here'), "
"('pfs.seats', 'note', 'https://x#2025 (a gap reason, not a note)')"
)
gaps, notes = dos._seat_log(con)
assert gaps["RUC"] == {2018, 2019}
assert notes == ["2024: parsed 31 seats, the page says 32 members"]
class _Broken:
def execute(self, *a):
raise RuntimeError("boom")
with pytest.raises(RuntimeError):
dos._seat_log(_Broken())
def test_seat_coverage_edges():
con = duckdb.connect(":memory:")
try:
ensure_tables(con)
write_seats(
con,
"RUC",
[
SeatRow(
"RUC",
2022,
"A society",
"FAMILY PRACTICE",
"permanent",
"u",
"K",
"",
)
],
)
assert dos._seat_coverage(con) == [
"RUC rosters captured 2022; CPT Panel rosters not captured."
]
assert dos._seat_log(con) == ({}, [])
finally:
con.close()
def test_coverage_without_rvu_table(home_fixture):
_con, store, family, _ask = home_fixture
con = duckdb.connect(":memory:")
try:
ensure_tables(con)
notes = coverage(con, store, family)
assert "RVU files not yet loaded." in notes
class _Broken:
def execute(self, *a):
raise RuntimeError("boom")
with pytest.raises(RuntimeError):
coverage(_Broken(), store, family)
finally:
con.close()
def _f(fid, kind, year, text, codes=(), **values):
return Fact(fid, kind, year, tuple(codes), text, values, Cite("fr_para", "l", "u"))
def test_timeline_comment_only_years_and_fallbacks():
facts = [
_f(
"F1",
"cms_summary",
2005,
"CMS reported that one commenter commented (CY2005 final rule).",
("99341",),
),
_f(
"F2",
"event",
2010,
"99341 was created for CY2010.",
("99341",),
event_kind="created",
),
_f(
"F3",
"cms_summary",
2010,
"CMS reported that commenters commented (CY2010 final rule).",
("99350",),
),
_f(
"F4",
"stance_split",
2011,
"Of 2 CY2011 commenters we classified on the coding changes, 1 supported, 1 asked for modifications, 0 opposed and 0 were unclear. Preliminary.",
event_key="X:2011:coding",
),
]
events = timeline(facts)
by = {(e.year, e.kind): e for e in events}
assert by[(2005, "comments")].cms_summary_fact_ids == ("F1",)
assert (
by[(2005, "comments")].what_changed
== "CMS reported that one commenter commented (CY2005 final rule) [F1]."
)
assert by[(2010, "created")].cms_summary_fact_ids == ("F3",)
assert by[(2011, "comments")].what_changed.startswith(
"Of 2 CY2011 commenters"
) and by[(2011, "comments")].what_changed.endswith("[F4].")
ids = {f.id: f for f in facts}
assert check_prose(template_summary(facts, events), ids) == []
def test_prose_too_long_is_a_problem(home_fixture):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
events = timeline(facts)[:1]
six = " ".join(f"{facts[0].text.rstrip('.')} [{facts[0].id}]." for _ in range(6))
ask = FakeAsk(default={"text": six})
summary, lines, extractor, ok = write_prose(facts, events, ask)
assert extractor == "template"
assert "too long: 6 sentences, at most 5" in ask.calls[1][1]
def test_in_sample_line():
assert dos._in_sample_line({"recall": 0.5}) == ""
line = dos._in_sample_line(
{
"in_sample_record": {
"recall": 0.407,
"direction": 0.818,
"n_items": 20,
"n_positions": 27,
"docket": "CMS-2022-0113",
}
}
)
assert (
line.startswith(" Tuning-set record: (20 hand-coded comments") and "41%" in line
)
def test_expand_range():
assert dos._expand_range("99341", ("99341", "99342")) == ("99341",)
assert dos._expand_range("G9999", ("99341",)) == ()
assert dos._expand_range("99341-99342", ("99343", "99342", "99341")) == (
"99341",
"99342",
)
def test_fallbacks_are_reported_per_unit(home_fixture):
con, store, family, _ask = home_fixture
facts = collect_facts(con, store, family)
events = timeline(facts)[:2]
fb: list[str] = []
write_prose(facts, events, FakeAsk(default=_echo), fallbacks=fb)
assert fb == []
write_prose(facts, events, None, fallbacks=fb)
assert fb == ["summary", *(f"CY{e.year} {e.kind}" for e in events)]
d = build_dossier(con, store, family)
assert d.fallbacks[0] == "summary" and len(d.fallbacks) == len(d.timeline) + 1