feat(pfs): comment stance per family event with reasons and evidence; reaction roll-up

This commit is contained in:
kert
2026-11-12 12:56:22 -05:00
parent 665b585405
commit ba0fac3ad9
7 changed files with 1238 additions and 12 deletions

View File

@@ -17,6 +17,7 @@ the read-only replica so the chat and notebooks see them.
from __future__ import annotations
import json
import logging
from collections import Counter
from pathlib import Path
@@ -26,18 +27,22 @@ import typer
from pfs.cms_summaries import summaries as cms_summaries_rows
from pfs.codetables import (
ReactionRow,
cpt_years,
ensure_tables,
is_missing_table_error,
read_all_elements,
read_all_events,
read_all_reviews,
read_commenters,
read_cpt_codes,
read_cpt_instructions,
read_cpt_sections,
read_exposures,
read_guidance,
read_reaction,
read_reviews,
read_stances,
write_cms_summaries,
write_commenters,
write_elements,
@@ -48,6 +53,7 @@ from pfs.codetables import (
write_origin,
write_reaction,
write_rounds,
write_stances,
)
from pfs.commenters import family_comment_items, identify, regs_for
from pfs.cpt_load import ingest as cpt_ingest
@@ -70,6 +76,7 @@ from pfs.origin import DEFAULT_BOOK, family_origin, origin_inventory, resolve_bo
from pfs.reaction import series as reaction_series
from pfs.rounds import family_rounds, rounds_inventory
from pfs.runlog import RunLog, ledger_path
from pfs.stance import docket_events, docket_rule_year, rollup, stances_for
from pfs.utilization import DATASETS as UTILIZATION_YEARS
from pfs.utilization import cache_path as utilization_cache_path
from pfs.utilization import cite as cite_utilization
@@ -660,6 +667,26 @@ def _reaction_targets(
return targets
def _stored(read: Any, con: Any, family: str) -> list[Any]:
"""``read(con, family)``; none when the table does not exist yet."""
try:
return read(con, family)
except Exception as exc: # noqa: BLE001 - only a missing table is tolerated
if is_missing_table_error(exc):
return []
raise
def _overlay_stances(rows: list[Any], stances: list[Any]) -> list[Any]:
"""Put the classified counts of each docket's stored stances on its row,
so a reaction rerun never zeroes them."""
out = []
for r in rows:
mine = [s for s in stances if s.docket == r.period]
out.append(rollup(mine, base=r) if r.period_kind == "docket" and mine else r)
return out
@app.command()
def reaction(
family: list[str] = typer.Option(
@@ -695,8 +722,16 @@ def reaction(
con = _read()
try:
targets = _reaction_targets(con, family, code)
stored = {key: _stored(read_stances, con, key) for key, _, _ in targets}
finally:
con.close()
if stance_sample > 0:
held = [k for k, v in stored.items() if v]
if held:
raise typer.BadParameter(
f"{', '.join(held)} already has stored stances (stack pfs stance); "
"a stance sample would be a second, weaker count"
)
# Ruling A13: the classifier and every family's series (docket
# counts, the stance sample — ~1-2s/sample — and FR pairs) all run
@@ -718,6 +753,7 @@ def reaction(
stance_sample_n=stance_sample,
name=name,
)
fam_rows = _overlay_stances(fam_rows, stored[key])
by_family[key] = fam_rows
rows.extend(fam_rows)
@@ -1297,3 +1333,113 @@ def commenters(
n = write_commenters(bcon, rows, docket=docket, family=fam.key)
typer.echo(f"wrote {n} commenters")
_publish()
@app.command("stance")
def stance(
family: str = typer.Option(..., "--family", help="Curated family key."),
docket: str = typer.Option(..., "--docket", help="regulations.gov docket id."),
limit: int = typer.Option(0, "--limit", help="Cap new model calls (0 = all)."),
retry_failed: bool = typer.Option(
False, "--retry-failed", help="Re-run ledger entries that failed."
),
dry_run: bool = typer.Option(
False, "--dry-run", help="Count commenters and events; no model."
),
write: bool = typer.Option(False, "--write"),
) -> None:
"""Each commenter's stance (support / modify / oppose / unclear) on each
family event the docket's rule touched, with a reason and a verbatim
quote (pfs.comment_stance); --write also rolls the counts up into the
docket's pfs.code_reaction row. CMS's own summaries are never used."""
fam = curated_family(normalize_key(family))
if fam is None:
raise typer.BadParameter(f"unknown curated family {family!r}")
store = _store()
found = [d for d in store.dockets() if d.id == docket]
if not found:
raise typer.BadParameter(f"unknown docket {docket!r}")
year = docket_rule_year(found[0].comment_end_date)
con = _read()
try:
events = docket_events(con, fam, year)
commenter_rows = [
c for c in read_commenters(con, family=fam.key) if c.docket == docket
]
stored = _stored(read_reaction, con, fam.key)
finally:
con.close()
if not commenter_rows:
typer.echo(f"{docket}: no commenter rows (run stack pfs commenters first)")
return
# the item set is the commenter rows, joined to the family's comment text
wanted = {c.item_key for c in commenter_rows}
texts = {
k: t
for k, t in family_comment_items(
_engine(), fam.codes, fam.key, fam.pair_phrases, docket=docket
)
if k in wanted
}
with_text = sum(1 for c in commenter_rows if c.item_key in texts)
typer.echo(
f"{docket}: {len(commenter_rows)} commenters, {with_text} with comment "
f"text, {len(events)} events"
)
for e in events:
typer.echo(f" {e.event_key}")
if dry_run:
typer.echo("no model calls made")
return
rows, counts = stances_for(
commenter_rows,
texts,
events,
_asker(),
RunLog(ledger_path("stance", fam.key)),
family=fam.key,
docket=docket,
limit=limit,
retry_failed=retry_failed,
progress=lambda unit, status: typer.echo(f"{unit} {status}"),
)
blank = ReactionRow(fam.key, docket, "docket", year, 0, 0, 0, 0, 0, 0, "[]")
rolled = rollup(rows, base=blank)
for key, n in json.loads(rolled.events_json).items():
typer.echo(
f"{key}: support {n['support']}, modify {n['modify']}, "
f"oppose {n['oppose']}, unclear {n['unclear']}"
)
typer.echo(
f"commenters classified: {len({r.item_key for r in rows})}; "
f"support {rolled.stance_support}, modify {rolled.stance_modify}, "
f"oppose {rolled.stance_oppose}, unclear {rolled.stance_unclear}"
)
typer.echo(
f"stances: {len(rows)}; done {counts['done']}, skipped {counts['skipped']}, "
f"failed {counts['failed']}, failed_pending {counts['failed_pending']}, "
f"pending {counts['pending']}, no_text {counts['no_text']}"
)
if not write:
return
if counts["pending"]:
raise typer.BadParameter(
f"{counts['pending']} comments not yet classified; rerun to resume"
)
series_rows = reaction_series(_engine(), store, fam.key, fam.codes, name=fam.name)
base = next(
(r for r in series_rows if r.period_kind == "docket" and r.period == docket),
blank,
)
new = rollup(rows, base=base)
keep = [
r
for r in (stored or series_rows)
if r.period != docket or r.period_kind != "docket"
]
with _batch() as bcon:
ensure_tables(bcon)
n = write_stances(bcon, fam.key, docket, rows)
write_reaction(bcon, fam.key, [*keep, new])
typer.echo(f"wrote {n} stances")
_publish()

View File

@@ -103,16 +103,10 @@ _docket_era_lock = threading.Lock()
def _docket_rule_year(comment_end_date: str) -> int:
"""A PFS docket's comment period closes in the second half of a
calendar year (Sept, typically) for a rule governing the NEXT
calendar year; one closing in the first half belongs to that same
year's rule. 0 when unparsable."""
try:
year = int(comment_end_date[:4])
month = int(comment_end_date[5:7])
except (ValueError, TypeError, IndexError):
return 0
return year + 1 if month >= 7 else year
"""See ``pfs.stance.docket_rule_year`` (one rule, two callers)."""
from pfs.stance import docket_rule_year
return docket_rule_year(comment_end_date)
def _docket_year(docket_id: str) -> int:

View File

@@ -166,6 +166,27 @@ class ReactionRow:
stance_modify: int
stance_unclear: int
sample_json: str
#: JSON ``{event_key: {"support": n, "modify": n, "oppose": n, "unclear": n}}``
#: from ``pfs.comment_stance`` (task 9); ``"{}"`` when none was classified
events_json: str = "{}"
@dataclass(frozen=True)
class StanceRow:
"""One commenter's position on one family event
(``pfs.comment_stance``, task 9): ``stance`` is support, modify, oppose
or unclear; ``evidence`` is a verbatim quote of the comment (or empty).
Our own classification, never merged with CMS's summaries."""
family: str
item_key: str
docket: str
event_key: str
stance: str
reason: str
evidence: str
#: ``model:<model>@<prompt version>``
extractor: str
@dataclass(frozen=True)
@@ -445,7 +466,8 @@ CREATE TABLE IF NOT EXISTS pfs.code_guidance (
CREATE TABLE IF NOT EXISTS pfs.code_reaction (
family VARCHAR, period VARCHAR, period_kind VARCHAR, year INTEGER,
n_items INTEGER, n_total INTEGER, stance_support INTEGER, stance_oppose INTEGER,
stance_modify INTEGER, stance_unclear INTEGER, sample_json VARCHAR);
stance_modify INTEGER, stance_unclear INTEGER, sample_json VARCHAR,
events_json VARCHAR);
CREATE TABLE IF NOT EXISTS pfs.cpt_section (
edition_year INTEGER, item_key VARCHAR, sec_id VARCHAR, level INTEGER, title VARCHAR,
path VARCHAR[], path_key VARCHAR, code_lo VARCHAR, code_hi VARCHAR, guideline VARCHAR);
@@ -488,6 +510,9 @@ CREATE TABLE IF NOT EXISTS pfs.commenter (
item_key VARCHAR, docket VARCHAR, comment_id VARCHAR, org_name VARCHAR,
org_type VARCHAR, specialty VARCHAR, form_group VARCHAR, form_size INTEGER,
basis VARCHAR, reg_category VARCHAR, extractor VARCHAR, family VARCHAR);
CREATE TABLE IF NOT EXISTS pfs.comment_stance (
family VARCHAR, item_key VARCHAR, docket VARCHAR, event_key VARCHAR,
stance VARCHAR, reason VARCHAR, evidence VARCHAR, extractor VARCHAR);
"""
@@ -539,6 +564,10 @@ def ensure_tables(con: Any) -> None:
# R57: pfs.commenter rows are per family. Every row written before the
# column existed came from the only family run, HOME-VISITS.
con.execute("ALTER TABLE pfs.commenter ADD COLUMN IF NOT EXISTS family VARCHAR")
# task 9: per-event stance counts
con.execute(
"ALTER TABLE pfs.code_reaction ADD COLUMN IF NOT EXISTS events_json VARCHAR"
)
con.execute("UPDATE pfs.commenter SET family = 'HOME-VISITS' WHERE family IS NULL")
@@ -688,7 +717,8 @@ def read_reaction(con: Any, family: str) -> list[ReactionRow]:
"ORDER BY period_kind, year, period",
[family],
).fetchall()
return [ReactionRow(*r) for r in rows]
# rows written before ``events_json`` existed read back NULL for it
return [ReactionRow(*r[:-1], r[-1] or "{}") for r in rows]
_CPT_TABLES = (
@@ -964,3 +994,23 @@ def read_commenters(
sql += " WHERE " + " AND ".join(where)
rows = con.execute(sql + " ORDER BY docket, item_key, family", params).fetchall()
return [CommenterRow(*r) for r in rows]
def write_stances(con: Any, family: str, docket: str, rows: Sequence[StanceRow]) -> int:
"""Replace the family's stance rows for one docket."""
ensure_tables(con)
con.execute(
"DELETE FROM pfs.comment_stance WHERE family = ? AND docket = ?",
[family, docket],
)
return _insert(con, "pfs.comment_stance", rows)
def read_stances(con: Any, family: str, docket: str | None = None) -> list[StanceRow]:
sql = "SELECT * FROM pfs.comment_stance WHERE family = ?"
params = [family]
if docket is not None:
sql += " AND docket = ?"
params.append(docket)
rows = con.execute(sql + " ORDER BY docket, item_key, event_key", params).fetchall()
return [StanceRow(*r) for r in rows]

331
src/pfs/stance.py Normal file
View File

@@ -0,0 +1,331 @@
"""Comment stance per family event (``pfs.comment_stance``, dossier task 9).
Each public comment on a family's docket is read against the family events
that docket's rule touched (valuation, coding, telehealth, a linked code,
other). The model gives, per event the comment addresses, a stance
(support / modify / oppose / unclear), a short reason and a verbatim quote.
The quote is kept only if at least six consecutive words of it occur in the
comment, and a position on an event that is not offered is dropped.
The roll-up (``rollup``) counts distinct commenters into ``pfs.code_reaction``.
It takes only our own ``StanceRow``s: CMS's summaries of comments
(``pfs.cms_comment_summary``) are a separate source and never feed it.
"""
from __future__ import annotations
import json
import re
from collections import defaultdict
from collections.abc import Mapping
from dataclasses import dataclass, replace
from typing import Any, Callable, Sequence
from pfs.codetables import (
CommenterRow,
ReactionRow,
StanceRow,
read_events,
read_rounds,
)
from pfs.runlog import RunLog, input_hash, run_units
TASK = "stance"
STANCE_PROMPT_VERSION = "stance-v1"
STANCES = ("support", "modify", "oppose", "unclear")
_EVIDENCE_WORDS = 6
_FIELD_CHARS = 200
_CODING_KINDS = ("created", "deleted", "cpt_panel", "descriptor_change")
def docket_rule_year(comment_end_date: str) -> int:
"""A PFS docket's comment period closes in the second half of a
calendar year (Sept, typically) for a rule governing the NEXT
calendar year; one closing in the first half belongs to that same
year's rule. 0 when unparsable."""
try:
year = int(comment_end_date[:4])
month = int(comment_end_date[5:7])
except (ValueError, TypeError, IndexError):
return 0
return year + 1 if month >= 7 else year
# ── events ───────────────────────────────────────────────────────────
@dataclass(frozen=True)
class EventChoice:
event_key: str
text: str
rule_year: int
def _num(x: float | None) -> str:
return f"{x:.2f}"
def docket_events(con: Any, family: Any, rule_year: int) -> list[EventChoice]:
"""The family events a docket's rule touched, always ending in ``other``."""
key = family.key
def ev(slug: str, text: str) -> EventChoice:
return EventChoice(f"{key}:{rule_year}:{slug}", text, rule_year)
out: list[EventChoice] = []
rounds = [r for r in read_rounds(con, key) if r.rule_year == rule_year]
if rounds:
parts = []
for code in sorted({r.code for r in rounds}):
mine = [r for r in rounds if r.code == code]
ruc = next(
(r.ruc_work_rvu for r in mine if r.ruc_work_rvu is not None), None
)
prop = next(
(r.proposed_work_rvu for r in mine if r.proposed_work_rvu is not None),
None,
)
bits = []
if ruc is not None:
bits.append(f"RUC recommended {_num(ruc)}")
if prop is not None:
bits.append(f"CMS proposed {_num(prop)}")
parts.append(f"{code} ({', '.join(bits)})" if bits else code)
out.append(ev("valuation", "Work RVU valuation: " + "; ".join(parts)))
events = [
e for c in family.codes for e in read_events(con, c) if e.year == rule_year
]
coding = sorted({(e.code, e.kind) for e in events if e.kind in _CODING_KINDS})
if coding:
out.append(
ev(
"coding",
"Coding changes (CPT codes created, deleted, revised or acted on by "
"the CPT Editorial Panel): "
+ "; ".join(f"{c} {k.replace('_', ' ')}" for c, k in coding),
)
)
tele = sorted({e.code for e in events if e.kind == "telehealth_list"})
if tele:
out.append(
ev("telehealth", "Medicare telehealth services list: " + ", ".join(tele))
)
for link in family.links:
if link.since == rule_year:
out.append(
ev(
link.target,
f"Linked code {link.target} ({link.kind}) introduced with "
f"this family in CY{rule_year}",
)
)
out.append(ev("other", "Any other aspect of the family or its payment"))
return out
def stance_schema(events: Sequence[EventChoice]) -> dict:
return {
"type": "object",
"properties": {
"positions": {
"type": "array",
"items": {
"type": "object",
"properties": {
"event": {
"type": "string",
"enum": [e.event_key for e in events],
},
"stance": {"type": "string", "enum": list(STANCES)},
"reason": {"type": "string", "maxLength": _FIELD_CHARS},
"evidence": {"type": "string", "maxLength": _FIELD_CHARS},
},
"required": ["event", "stance", "reason", "evidence"],
},
}
},
"required": ["positions"],
}
def _system(events: Sequence[EventChoice]) -> str:
listed = "\n".join(f"- {e.event_key}: {e.text}" for e in events)
return (
"You read one public comment on a Medicare payment rule and say what the "
"commenter's position is on each of these events, only for events the "
"comment actually addresses:\n"
f"{listed}\n"
"For each position give event (one of the keys above), stance (support, "
"modify when it asks for a change, oppose, or unclear), reason (one short "
"sentence) and evidence (an exact quote of at least six words copied from "
"the comment, or an empty string). Give no position for an event the "
"comment does not address."
)
def _words(s: str) -> list[str]:
return re.findall(r"[a-z0-9]+", (s or "").lower())
def _quoted(evidence: str, text_words: str) -> bool:
ws = _words(evidence)
return any(
f" {' '.join(ws[i : i + _EVIDENCE_WORDS])} " in text_words
for i in range(len(ws) - _EVIDENCE_WORDS + 1)
)
def classify_comment(
text: str,
events: Sequence[EventChoice],
ask: Callable,
*,
family: str,
item_key: str,
docket: str,
) -> list[StanceRow] | None:
"""Positions of one comment, or ``None`` when the model gave no usable
reply. A position on an unknown event or with an unknown stance is
dropped; ``evidence`` is kept only if >= 6 consecutive words of it occur
in *text*."""
reply = ask(_system(events), text, stance_schema(events))
if reply is None:
return None
known = {e.event_key for e in events}
hay = f" {' '.join(_words(text))} "
extractor = f"model:{getattr(ask, 'model', 'unknown')}@{STANCE_PROMPT_VERSION}"
rows = []
for p in reply.get("positions") or []:
if not isinstance(p, dict) or p.get("event") not in known:
continue
if p.get("stance") not in STANCES:
continue
evidence = str(p.get("evidence") or "")
rows.append(
StanceRow(
family,
item_key,
docket,
p["event"],
p["stance"],
str(p.get("reason") or "")[:_FIELD_CHARS],
evidence[:_FIELD_CHARS] if _quoted(evidence, hay) else "",
extractor,
)
)
return rows
# ── run ──────────────────────────────────────────────────────────────
def _as_dict(r: StanceRow) -> dict:
return {
"event": r.event_key,
"stance": r.stance,
"reason": r.reason,
"evidence": r.evidence,
}
def stances_for(
commenters: Sequence[CommenterRow],
texts: Mapping[str, str],
events: Sequence[EventChoice],
ask: Callable,
log: RunLog,
*,
family: str,
docket: str,
limit: int = 0,
retry_failed: bool = False,
progress: Callable[[str, str], None] | None = None,
) -> tuple[list[StanceRow], dict[str, int]]:
"""Classify each commenter's comment through the resumable ledger.
Counts are the run counts plus ``pending`` (no ledger answer yet) and
``no_text`` (a commenter row whose comment text is not found)."""
model = getattr(ask, "model", "unknown")
extractor = f"model:{model}@{STANCE_PROMPT_VERSION}"
ev_part = [f"{e.event_key}|{e.text}" for e in events]
keys = [c.item_key for c in commenters if c.item_key in texts]
hashes = {k: input_hash(texts[k], *ev_part) for k in keys}
def unit(k: str) -> dict | None:
rows = classify_comment(
texts[k], events, ask, family=family, item_key=k, docket=docket
)
return None if rows is None else {"positions": [_as_dict(r) for r in rows]}
counts = run_units(
[(k, hashes[k], lambda k=k: unit(k)) for k in keys],
log,
model=model,
version=STANCE_PROMPT_VERSION,
limit=limit,
retry_failed=retry_failed,
progress=progress,
)
known = {e.event_key for e in events}
rows: list[StanceRow] = []
pending = 0
for k in keys:
entry = log.get(k, hashes[k], model, STANCE_PROMPT_VERSION)
if entry is None or entry.output is None:
pending += 1
continue
rows += [
StanceRow(
family,
k,
docket,
p["event"],
p["stance"],
p["reason"],
p["evidence"],
extractor,
)
for p in entry.output["positions"]
if p["event"] in known
]
return rows, {**counts, "pending": pending, "no_text": len(commenters) - len(keys)}
# ── roll-up ──────────────────────────────────────────────────────────
def _rank(event_key: str) -> tuple[int, str]:
slug = event_key.rsplit(":", 1)[-1]
order = {"valuation": 0, "coding": 1, "telehealth": 2, "other": 99}
return order.get(slug, 3), event_key
def _first_firm(stances: Sequence[str]) -> str:
return next((s for s in stances if s != "unclear"), "unclear")
def rollup(stances: Sequence[StanceRow], *, base: ReactionRow) -> ReactionRow:
"""Distinct commenters by their first non-``unclear`` position in event
order (all ``unclear`` -> ``unclear``); ``events_json`` counts distinct
commenters per event the same way. Only our own stance rows go in."""
by_item: dict[str, dict[str, list[str]]] = defaultdict(lambda: defaultdict(list))
for s in stances:
by_item[s.item_key][s.event_key].append(s.stance)
totals = dict.fromkeys(STANCES, 0)
per_event: dict[str, dict[str, int]] = {}
for events in by_item.values():
ordered = sorted(events, key=_rank)
totals[_first_firm([_first_firm(events[e]) for e in ordered])] += 1
for e in ordered:
per_event.setdefault(e, dict.fromkeys(STANCES, 0))[
_first_firm(events[e])
] += 1
return replace(
base,
stance_support=totals["support"],
stance_modify=totals["modify"],
stance_oppose=totals["oppose"],
stance_unclear=totals["unclear"],
events_json=json.dumps(
dict(sorted(per_event.items(), key=lambda kv: _rank(kv[0])))
),
)

View File

@@ -1944,3 +1944,247 @@ class TestCommenters:
from bib.regulations_gov import Mirror
assert isinstance(pfs_cli._mirror(), Mirror)
class TestStance:
"""``stack pfs stance`` and the reaction overlay (task 9)."""
def _patch(self, con, monkeypatch, *, pending=0, seen=None):
from bib.dockets import Docket
from pfs.codetables import CommenterRow, StanceRow, write_commenters
seen = {} if seen is None else seen
write_commenters(
con._real,
[
CommenterRow(k, "D1", "C-" + k, "", "individual", "", "", 0, "regs_gov_fields", "", "regs", "HOME-VISITS")
for k in ("K1", "K2")
],
) # fmt: skip
store = type(
"S",
(),
{"dockets": lambda self: [Docket(id="D1", comment_end_date="2022-09-06")]},
)()
monkeypatch.setattr(pfs_cli, "_store", lambda: store)
monkeypatch.setattr(pfs_cli, "_engine", lambda: "ENGINE")
monkeypatch.setattr(pfs_cli, "_asker", lambda: "ASK")
monkeypatch.setattr(
pfs_cli, "ledger_path", lambda t, f: Path("/nonexistent") / f"{t}-{f}"
)
monkeypatch.setattr(
pfs_cli,
"family_comment_items",
lambda eng, codes, key, phrases, docket: [("K1", "t1"), ("K2", "t2"), ("K9", "t9")],
) # fmt: skip
def series(engine, store_, family, codes, **kw):
return [
ReactionRow(family, "D1", "docket", 2023, 2, 9, 0, 0, 0, 0, "[]"),
ReactionRow(family, "R1", "fr-pairs", 2023, 3, 7, 0, 0, 0, 0, "[]"),
]
monkeypatch.setattr(pfs_cli, "reaction_series", series)
def fake(commenters, texts, events, ask, log, **kw):
seen.update(
keys=[c.item_key for c in commenters],
texts=texts,
events=[e.event_key for e in events],
ask=ask,
**kw,
)
kw["progress"]("K1", "done")
rows = [
StanceRow("HOME-VISITS", "K1", "D1", "HOME-VISITS:2023:other", "oppose", "", "", "x"),
StanceRow("HOME-VISITS", "K2", "D1", "HOME-VISITS:2023:other", "support", "", "", "x"),
] # fmt: skip
return rows, {
"done": 2, "skipped": 0, "failed": 0, "failed_pending": 0,
"pending": pending, "no_text": 0,
} # fmt: skip
monkeypatch.setattr(pfs_cli, "stances_for", fake)
return seen
def _args(self, *extra):
return ["pfs", "stance", "--family", "home-visits", "--docket", "D1", *extra]
def test_write_replaces_docket_row_and_keeps_fr_pairs(self, con, monkeypatch):
from pfs.codetables import read_stances, write_reaction
seen = self._patch(con, monkeypatch)
write_reaction(
con._real,
"HOME-VISITS",
[
ReactionRow("HOME-VISITS", "D1", "docket", 2023, 2, 9, 0, 0, 0, 0, "[]"),
ReactionRow("HOME-VISITS", "D0", "docket", 2020, 1, 4, 0, 0, 0, 0, "[]"),
ReactionRow("HOME-VISITS", "R1", "fr-pairs", 2023, 3, 7, 0, 0, 0, 0, "[]"),
],
) # fmt: skip
res = runner.invoke(app, self._args("--limit", "3", "--write"))
assert res.exit_code == 0, res.output
assert seen["keys"] == ["K1", "K2"] and seen["texts"] == {
"K1": "t1",
"K2": "t2",
}
assert seen["events"] == ["HOME-VISITS:2023:G0318", "HOME-VISITS:2023:other"]
assert seen["limit"] == 3 and seen["ask"] == "ASK"
assert "wrote 2 stances" in res.output and "K1 done" in res.output
assert (
"HOME-VISITS:2023:other: support 1, modify 0, oppose 1, unclear 0"
in res.output
)
assert len(read_stances(con._real, "HOME-VISITS")) == 2
rows = {r.period: r for r in read_reaction(con._real, "HOME-VISITS")}
assert set(rows) == {"D1", "D0", "R1"}
assert (rows["D1"].stance_support, rows["D1"].stance_oppose) == (1, 1)
assert rows["D1"].n_items == 2 and rows["D1"].n_total == 9
assert (rows["D0"].stance_support, rows["R1"].stance_oppose) == (0, 0)
assert rows["D0"].events_json == "{}"
assert con.published == [True]
def test_write_with_no_stored_reaction_rows_uses_series(self, con, monkeypatch):
self._patch(con, monkeypatch)
res = runner.invoke(app, self._args("--write"))
assert res.exit_code == 0, res.output
assert {r.period for r in read_reaction(con._real, "HOME-VISITS")} == {
"D1",
"R1",
}
def test_write_refused_while_pending(self, con, monkeypatch):
self._patch(con, monkeypatch, pending=2)
monkeypatch.setattr(pfs_cli, "_batch", lambda: 1 / 0)
res = runner.invoke(app, self._args("--write"))
assert res.exit_code != 0 and "2 comments not yet classified" in res.output
def test_without_write_writes_nothing(self, con, monkeypatch):
self._patch(con, monkeypatch)
monkeypatch.setattr(pfs_cli, "_batch", lambda: 1 / 0)
res = runner.invoke(app, self._args())
assert res.exit_code == 0 and "stances: 2;" in res.output
def test_dry_run_makes_no_model_calls(self, con, monkeypatch):
self._patch(con, monkeypatch)
monkeypatch.setattr(pfs_cli, "_asker", lambda: 1 / 0)
monkeypatch.setattr(pfs_cli, "stances_for", lambda *a, **k: 1 / 0)
res = runner.invoke(app, self._args("--dry-run"))
assert res.exit_code == 0, res.output
assert "D1: 2 commenters, 2 with comment text, 2 events" in res.output
assert "HOME-VISITS:2023:other" in res.output
assert "no model calls made" in res.output
def test_no_commenter_rows(self, con, monkeypatch):
from pfs.codetables import write_commenters
self._patch(con, monkeypatch)
write_commenters(con._real, [], docket="D1", family="HOME-VISITS")
res = runner.invoke(app, self._args("--write"))
assert res.exit_code == 0 and "D1: no commenter rows" in res.output
def test_unknown_family_and_docket(self, con, monkeypatch):
self._patch(con, monkeypatch)
res = runner.invoke(
app, ["pfs", "stance", "--family", "NOPE", "--docket", "D1"]
)
assert res.exit_code != 0
res = runner.invoke(
app, ["pfs", "stance", "--family", "home-visits", "--docket", "ZZ"]
)
assert res.exit_code != 0 and "unknown docket" in res.output
def test_rollup_ignores_cms_summaries(self, con, monkeypatch):
from pfs.codetables import CmsSummaryRow, write_cms_summaries
self._patch(con, monkeypatch)
monkeypatch.setattr(pfs_cli, "reaction_series", lambda e, s, f, c, **kw: [
ReactionRow(f, "D1", "docket", 2023, 2, 9, 0, 0, 0, 0, "[]")
]) # fmt: skip
def counts():
r = [
x for x in read_reaction(con._real, "HOME-VISITS") if x.period == "D1"
][0]
return (
r.stance_support,
r.stance_modify,
r.stance_oppose,
r.stance_unclear,
r.events_json,
)
assert runner.invoke(app, self._args("--write")).exit_code == 0
before = counts()
write_cms_summaries(
con._real,
"HOME-VISITS",
[CmsSummaryRow("HOME-VISITS", "R1", 2023, "final", 1, 2, "99342", "a majority of commenters", "support", "finalize_as_proposed", "regex")],
) # fmt: skip
res = runner.invoke(
app, ["pfs", "reaction", "--family", "home-visits", "--write"]
)
assert res.exit_code == 0, res.output
assert counts() == before
assert runner.invoke(app, self._args("--write")).exit_code == 0
assert counts() == before == (1, 0, 1, 0, before[4])
def _reaction_patch(self, monkeypatch):
monkeypatch.setattr(pfs_cli, "_engine", lambda: "ENGINE")
monkeypatch.setattr(
pfs_cli,
"reaction_series",
lambda e, s, f, c, **kw: [
ReactionRow(f, "D1", "docket", 2023, 5, 20, 0, 0, 0, 0, "[]"),
ReactionRow(f, "D2", "docket", 2024, 4, 10, 0, 0, 0, 0, "[]"),
],
)
def test_reaction_rerun_keeps_stance_counts(self, con, monkeypatch):
from pfs.codetables import StanceRow, write_stances
self._reaction_patch(monkeypatch)
write_stances(
con._real,
"CCM",
"D1",
[
StanceRow("CCM", "K1", "D1", "CCM:2023:other", "modify", "", "", "x"),
StanceRow("CCM", "K2", "D1", "CCM:2023:other", "modify", "", "", "x"),
],
) # fmt: skip
res = runner.invoke(app, ["pfs", "reaction", "--family", "ccm", "--write"])
assert res.exit_code == 0, res.output
rows = {r.period: r for r in read_reaction(con._real, "CCM")}
assert rows["D1"].stance_modify == 2 and rows["D1"].n_items == 5
assert rows["D2"].stance_modify == 0 and rows["D2"].events_json == "{}"
def test_stance_sample_refused_when_stances_stored(self, con, monkeypatch):
from pfs.codetables import StanceRow, write_stances
self._reaction_patch(monkeypatch)
monkeypatch.setattr(pfs_cli, "_classifier", lambda **k: 1 / 0)
write_stances(
con._real, "CCM", "D1", [StanceRow("CCM", "K1", "D1", "CCM:2023:other", "modify", "", "", "x")]
) # fmt: skip
res = runner.invoke(
app, ["pfs", "reaction", "--family", "ccm", "--stance-sample", "5"]
)
assert res.exit_code != 0 and "stored stances" in res.output
def test_reaction_tolerates_a_missing_stance_table(self, con, monkeypatch):
self._reaction_patch(monkeypatch)
con._real.execute("DROP TABLE pfs.comment_stance")
res = runner.invoke(app, ["pfs", "reaction", "--family", "ccm"])
assert res.exit_code == 0, res.output
def test_stored_tolerates_only_a_missing_table(self):
import duckdb as dd
c = dd.connect(":memory:")
assert pfs_cli._stored(pfs_cli.read_stances, c, "F") == []
with pytest.raises(RuntimeError):
pfs_cli._stored(
lambda con, f: (_ for _ in ()).throw(RuntimeError("x")), c, "F"
)

View File

@@ -389,6 +389,42 @@ class TestReactionTable:
assert len(read_reaction(con, "G2211")) == 1
class TestEventsJson:
def test_events_json_roundtrip_and_null_tolerated(self, con):
ev = json.dumps(
{"F:2023:other": {"support": 1, "modify": 0, "oppose": 0, "unclear": 0}}
)
row = ReactionRow("CCM", "D1", "docket", 2023, 5, 20, 1, 0, 0, 0, "[]", ev)
write_reaction(con, "CCM", [row])
assert read_reaction(con, "CCM") == [row]
assert (
ReactionRow("CCM", "D", "docket", 1, 0, 0, 0, 0, 0, 0, "[]").events_json
== "{}"
)
# a row written before the column existed reads back "{}"
con.execute(
"INSERT INTO pfs.code_reaction (family, period, period_kind, year, n_items, "
"n_total, stance_support, stance_oppose, stance_modify, stance_unclear, "
"sample_json) VALUES ('OLD', 'D0', 'docket', 2020, 1, 2, 0, 0, 0, 0, '[]')"
)
assert read_reaction(con, "OLD")[0].events_json == "{}"
def test_ensure_tables_adds_the_column_to_an_old_table(self):
c = duckdb.connect(":memory:")
c.execute("CREATE SCHEMA pfs")
c.execute(
"CREATE TABLE pfs.code_reaction (family VARCHAR, period VARCHAR, "
"period_kind VARCHAR, year INTEGER, n_items INTEGER, n_total INTEGER, "
"stance_support INTEGER, stance_oppose INTEGER, stance_modify INTEGER, "
"stance_unclear INTEGER, sample_json VARCHAR)"
)
c.execute(
"INSERT INTO pfs.code_reaction VALUES ('A','D','docket',1,1,1,0,0,0,0,'[]')"
)
ensure_tables(c)
assert read_reaction(c, "A")[0].events_json == "{}"
class TestFrPairSpansRefactor:
def test_counts_derive_from_spans(self, store_with_pairs):
from pfs.reaction import fr_pair_spans

425
tests/pfs/test_stance.py Normal file
View File

@@ -0,0 +1,425 @@
"""pfs.stance — comment stance per family event (task 9)."""
from __future__ import annotations
import dataclasses
import json
from types import SimpleNamespace
import duckdb
import pytest
from pfs.codetables import (
CmsSummaryRow,
CommenterRow,
EventRow,
ReactionRow,
RoundRow,
StanceRow,
ensure_tables,
read_stances,
write_cms_summaries,
write_events,
write_rounds,
write_stances,
)
from pfs.curated import CuratedLink
from pfs.runlog import RunLog
from pfs.stance import (
STANCE_PROMPT_VERSION,
EventChoice,
classify_comment,
docket_events,
docket_rule_year,
rollup,
stance_schema,
stances_for,
)
TEXT = (
"We support the proposed increase in work RVUs for CPT code 99342 because "
"home visits take far longer than office visits for frail patients. "
"However we urge CMS to reconsider the new G0318 prolonged services add-on "
"code, which will be too hard to bill in practice. Sincerely, Jane Doe"
)
EV_VAL = "we support the proposed increase in work RVUs for CPT code 99342"
EV_G = "we urge CMS to reconsider the new G0318 prolonged services add-on"
FAM = SimpleNamespace(
key="HOME-VISITS",
codes=("99341", "99342"),
links=(
CuratedLink("prolonged-add-on", "G0318", 2023, None, "PETM225D", 1694, 0, 0),
CuratedLink("add-on", "G2211", 2026, None, "NHRGIHGD", 1469, 0, 0),
),
)
def _round(code="99342", year=2023):
return RoundRow(
"HOME-VISITS", code, year, "PETM225D", "final", 1, 0, "fr-para", "",
2.0, "", None, None, "", "", None, 1.9, 1.8, "refine", 0, "", "", "fr",
) # fmt: skip
def _event(code, year, kind):
return EventRow(code, year, kind, "", "", "", 0, 0, "fr", True, "")
@pytest.fixture
def con():
c = duckdb.connect(":memory:")
ensure_tables(c)
yield c
c.close()
@pytest.fixture
def events():
return [
EventChoice("HOME-VISITS:2023:valuation", "Work RVUs for 99342", 2023),
EventChoice("HOME-VISITS:2023:coding", "CPT Editorial Panel changes", 2023),
EventChoice("HOME-VISITS:2023:G0318", "New add-on G0318", 2023),
EventChoice("HOME-VISITS:2023:other", "Anything else", 2023),
]
class Ask:
model = "qwen-test"
def __init__(self, positions):
self.positions = positions
self.calls = []
def __call__(self, system, user, schema):
self.calls.append((system, user, schema))
if self.positions is None:
return None
return {"positions": self.positions}
def pos(event, stance, reason="r", evidence=""):
return {"event": event, "stance": stance, "reason": reason, "evidence": evidence}
def S(item, event, stance, docket="D1", reason="", evidence=""):
return StanceRow("HOME-VISITS", item, docket, event, stance, reason, evidence, "x")
# ── docket year ──────────────────────────────────────────────────────
def test_docket_rule_year_matches_rag():
from llm.rag import _docket_rule_year
for d in ("2022-09-06", "2023-03-01", "2023-07-01", "bad", "", None, "2023"):
assert docket_rule_year(d) == _docket_rule_year(d)
assert docket_rule_year("2022-09-06") == 2023
assert docket_rule_year("2023-03-01") == 2023
assert docket_rule_year("bad") == 0
# ── events ───────────────────────────────────────────────────────────
def test_docket_events_cy2023_home_visits(con):
write_rounds(con, "HOME-VISITS", [_round(), _round(year=2008)])
write_events(con, "99342", [_event("99342", 2023, "cpt_panel")])
got = docket_events(con, FAM, 2023)
assert [e.event_key for e in got] == [
"HOME-VISITS:2023:valuation",
"HOME-VISITS:2023:coding",
"HOME-VISITS:2023:G0318",
"HOME-VISITS:2023:other",
]
assert all(e.rule_year == 2023 for e in got)
val = got[0].text
assert "99342" in val and "RUC" in val and "2.00" in val and "1.90" in val
assert "2008" not in val
assert docket_events(con, FAM, 2023) == got # deterministic
def test_docket_events_telehealth_and_bare_year(con):
write_events(
con,
"99341",
[_event("99341", 2024, "telehealth_list"), _event("99341", 2024, "created")],
)
got = docket_events(con, FAM, 2024)
assert [e.event_key.split(":")[-1] for e in got] == [
"coding",
"telehealth",
"other",
]
assert [e.event_key for e in docket_events(con, FAM, 1999)] == [
"HOME-VISITS:1999:other"
]
def test_docket_events_round_without_values(con):
r = _round()
r = dataclasses.replace(
r, ruc_work_rvu=None, proposed_work_rvu=None, final_work_rvu=None
)
write_rounds(con, "HOME-VISITS", [r])
val = docket_events(con, FAM, 2023)[0]
assert "99342" in val.text and "RUC" not in val.text
def test_stance_schema(events):
sc = stance_schema(events)
item = sc["properties"]["positions"]["items"]
assert item["properties"]["event"]["enum"] == [e.event_key for e in events]
assert item["properties"]["stance"]["enum"] == [
"support",
"modify",
"oppose",
"unclear",
]
assert item["properties"]["reason"]["maxLength"] == 200
assert item["properties"]["evidence"]["maxLength"] == 200
assert STANCE_PROMPT_VERSION == "stance-v1"
# ── classify_comment ─────────────────────────────────────────────────
def _classify(positions, text=TEXT, events=None, ask=None):
ask = ask or Ask(positions)
return classify_comment(
text, events, ask, family="HOME-VISITS", item_key="K1", docket="D1"
)
def test_prompt_lists_events_and_comment(events):
ask = Ask([])
_classify([], events=events, ask=ask)
system, user, schema = ask.calls[0]
assert "HOME-VISITS:2023:G0318" in system and "New add-on G0318" in system
assert user == TEXT
assert schema == stance_schema(events)
def test_none_reply_is_none(events):
assert _classify(None, events=events) is None
def test_rows_carry_fields(events):
rows = _classify(
[pos("HOME-VISITS:2023:valuation", "support", "likes increase", EV_VAL)],
events=events,
)
assert rows == [
StanceRow(
"HOME-VISITS",
"K1",
"D1",
"HOME-VISITS:2023:valuation",
"support",
"likes increase",
EV_VAL,
"model:qwen-test@stance-v1",
)
]
def test_unknown_event_in_reply_dropped(events):
rows = _classify(
[pos("HOME-VISITS:2023:nope", "support"), pos(events[3].event_key, "oppose")],
events=events,
)
assert [r.event_key for r in rows] == [events[3].event_key]
def test_bad_stance_and_non_dict_dropped(events):
ask = Ask([pos(events[0].event_key, "maybe"), "junk"])
assert _classify(None, events=events, ask=ask) == []
def test_evidence_must_occur_in_text(events):
rows = _classify(
[
pos(events[0].event_key, "support", "r", EV_VAL),
pos(events[1].event_key, "oppose", "r", "this sentence was never written anywhere"),
pos(events[2].event_key, "modify", "r", "too short quote"),
pos(events[3].event_key, "unclear", "r", ""),
],
events=events,
) # fmt: skip
assert [r.evidence for r in rows] == [EV_VAL, "", "", ""]
assert [r.stance for r in rows] == ["support", "oppose", "modify", "unclear"]
def test_evidence_window_match_is_case_and_punctuation_blind(events):
ev = "WE SUPPORT, the proposed increase: in work RVUs for CPT code 99342 (and more)"
rows = _classify([pos(events[0].event_key, "support", "r", ev)], events=events)
assert rows[0].evidence == ev
def test_reason_and_evidence_truncated(events):
rows = _classify([pos(events[0].event_key, "support", "x" * 500)], events=events)
assert len(rows[0].reason) == 200
# ── stances_for (ledger) ─────────────────────────────────────────────
def _commenter(key, cid=None, org="individual"):
return CommenterRow(
key, "D1", cid or "C-" + key, "", org, "", "", 0, "regs_gov_fields", "", "regs", "HOME-VISITS"
) # fmt: skip
def _run(tmp_path, ask, commenters, texts, events, **kw):
log = RunLog(tmp_path / "stance.jsonl")
out = stances_for(
commenters,
texts,
events,
ask,
log,
family="HOME-VISITS",
docket="D1",
**kw,
)
return out, log
def test_stances_for_rows_from_ledger(tmp_path, events):
ask = Ask(
[
pos(events[0].event_key, "support", "likes it", EV_VAL),
pos(events[1].event_key, "oppose", "bad", "not a quote from the text at all"),
pos("HOME-VISITS:2023:zzz", "support"),
]
) # fmt: skip
(rows, counts), log = _run(tmp_path, ask, [_commenter("K1")], {"K1": TEXT}, events)
assert counts == {
"done": 1, "skipped": 0, "failed": 0, "failed_pending": 0,
"pending": 0, "no_text": 0,
} # fmt: skip
assert [(r.event_key, r.reason, r.evidence) for r in rows] == [
(events[0].event_key, "likes it", EV_VAL),
(events[1].event_key, "bad", ""),
]
assert rows[0].extractor == f"model:qwen-test@{STANCE_PROMPT_VERSION}"
# a second run replays the ledger without asking again
(again, _), _ = _run(tmp_path, ask, [_commenter("K1")], {"K1": TEXT}, events)
assert again == rows and len(ask.calls) == 1
def test_stances_for_resume_limit_failed(tmp_path, events):
cs = [_commenter(k) for k in ("K1", "K2", "K3", "K4", "K5")]
texts = {k: TEXT for k in ("K1", "K2", "K3", "K4")} # K5 has no text
ask = Ask([pos(events[3].event_key, "oppose")])
(rows, counts), log = _run(tmp_path, ask, cs, texts, events, limit=2)
assert counts["done"] == 2 and counts["pending"] == 2 and counts["no_text"] == 1
assert len(ask.calls) == 2 and len(rows) == 2
# resume: the two done are skipped, the rest run
(rows, counts), _ = _run(tmp_path, ask, cs, texts, events)
assert counts["skipped"] == 2 and counts["done"] == 2 and counts["pending"] == 0
assert len(rows) == 4 and len(ask.calls) == 4
# a failed reply is logged, stays pending-failed until --retry-failed
bad = Ask(None)
(rows, counts), _ = _run(tmp_path, bad, [_commenter("K9")], {"K9": TEXT}, events)
assert counts["failed"] == 1 and counts["pending"] == 1 and rows == []
(rows, counts), _ = _run(tmp_path, bad, [_commenter("K9")], {"K9": TEXT}, events)
assert counts["failed_pending"] == 1 and len(bad.calls) == 1
good = Ask([pos(events[3].event_key, "support")])
(rows, counts), _ = _run(
tmp_path, good, [_commenter("K9")], {"K9": TEXT}, events, retry_failed=True
)
assert counts["done"] == 1 and len(rows) == 1
def test_stances_for_event_change_reruns(tmp_path, events):
ask = Ask([pos(events[3].event_key, "support")])
c, t = [_commenter("K1")], {"K1": TEXT}
_run(tmp_path, ask, c, t, events)
other = [*events[:3], EventChoice(events[3].event_key, "different text", 2023)]
(_rows, counts), _ = _run(tmp_path, ask, c, t, other)
assert counts["done"] == 1
def test_stances_for_progress(tmp_path, events):
seen = []
ask = Ask([])
_run(
tmp_path, ask, [_commenter("K1")], {"K1": TEXT}, events,
progress=lambda u, s: seen.append((u, s)),
) # fmt: skip
assert seen == [("K1", "done")]
# ── table ────────────────────────────────────────────────────────────
def test_stance_table_roundtrip(con):
a = S("K1", "HOME-VISITS:2023:other", "support", reason="r", evidence="e")
b = S("K2", "HOME-VISITS:2023:other", "oppose", docket="D2")
c = StanceRow("OTHER", "K3", "D1", "OTHER:2023:other", "modify", "", "", "x")
write_stances(con, "HOME-VISITS", "D1", [a])
write_stances(con, "HOME-VISITS", "D2", [b])
write_stances(con, "OTHER", "D1", [c])
assert read_stances(con, "HOME-VISITS") == [a, b]
assert read_stances(con, "HOME-VISITS", docket="D2") == [b]
write_stances(con, "HOME-VISITS", "D1", []) # replaces just that docket
assert read_stances(con, "HOME-VISITS") == [b]
assert read_stances(con, "OTHER") == [c]
# ── rollup ───────────────────────────────────────────────────────────
def _base(**kw):
d = dict(
family="HOME-VISITS", period="D1", period_kind="docket", year=2023,
n_items=9, n_total=40, stance_support=0, stance_oppose=0,
stance_modify=0, stance_unclear=0, sample_json='[{"k": 1}]',
) # fmt: skip
return ReactionRow(**{**d, **kw})
def test_rollup_counts_distinct_commenters():
v, c, g, o = (
f"HOME-VISITS:2023:{s}" for s in ("valuation", "coding", "G0318", "other")
)
rows = [
# K1: valuation unclear, coding support -> first non-unclear = support
S("K1", v, "unclear"), S("K1", c, "support"), S("K1", g, "oppose"),
# K2: G0318 comes before other in event order, so modify wins
S("K2", o, "oppose"), S("K2", o, "support"), S("K2", g, "modify"),
# K3: all unclear
S("K3", v, "unclear"), S("K3", o, "unclear"),
# K4: same stance on several events counts once
S("K4", v, "oppose"), S("K4", g, "oppose"),
] # fmt: skip
got = rollup(rows, base=_base())
assert (
got.stance_support,
got.stance_modify,
got.stance_oppose,
got.stance_unclear,
) == (1, 1, 1, 1)
assert got.sample_json == '[{"k": 1}]' and got.n_items == 9 and got.period == "D1"
ev = json.loads(got.events_json)
assert ev[v] == {"support": 0, "modify": 0, "oppose": 1, "unclear": 2}
assert ev[c] == {"support": 1, "modify": 0, "oppose": 0, "unclear": 0}
assert ev[g] == {"support": 0, "modify": 1, "oppose": 2, "unclear": 0}
assert ev[o] == {"support": 0, "modify": 0, "oppose": 1, "unclear": 1}
def test_rollup_empty_is_zero():
got = rollup([], base=_base(stance_support=3))
assert got.stance_support == 0 and got.events_json == "{}"
def test_rollup_ignores_cms_summaries(con):
write_cms_summaries(
con,
"HOME-VISITS",
[CmsSummaryRow("HOME-VISITS", "R1", 2023, "final", 1, 2, "99342", "a majority of commenters", "support", "finalize_as_proposed", "regex")],
) # fmt: skip
rows = [S("K1", "HOME-VISITS:2023:other", "oppose")]
assert rollup(rows, base=_base()) == rollup(rows, base=_base())
got = rollup(rows, base=_base())
assert (got.stance_support, got.stance_oppose) == (0, 1)