Files
stack/src/pfs/commenters.py
kert 3a7b4824b2
Some checks failed
CI / lint (push) Successful in 47s
CI / notebooks-smoke (push) Successful in 2m6s
Deploy / changes (push) Successful in 17s
CI / test (push) Failing after 4m11s
Infra CI / zotero (push) Successful in 21s
Infra CI / notebooks (push) Successful in 1m31s
Infra CI / api (push) Successful in 1m31s
Infra CI / docs (push) Successful in 1m44s
Infra CI / llm (push) Successful in 56s
Infra CI / mc (push) Successful in 22s
Deploy / notebooks (push) Has been skipped
Deploy / zotero (push) Has been skipped
Deploy / docs (push) Has been skipped
Infra CI / bcda (push) Successful in 1m44s
Deploy / api (push) Successful in 1m20s
Deploy / bcda (push) Successful in 1m48s
Deploy / mc (push) Has been skipped
Deploy / llm (push) Successful in 1m11s
Deploy / report (push) Successful in 18s
fix(pfs): commenter rows carry their family; a docket rewrite touches only that family
2026-11-12 12:41:25 -05:00

602 lines
23 KiB
Python

"""Who wrote each public comment on a family (``pfs.commenter``, dossier
task 8): organization, organization type, specialty and form-letter
campaign.
Privacy is the hard constraint. A person's name is never stored, logged
or put in a ledger. Individual commenters are only ever an organization
type (``individual`` / ``individual_clinician``). Two guards enforce it:
* regulations.gov's ``firstName`` / ``lastName`` are read only inside
``regs_fields`` and ``_org_names_submitter``, each of which lets a
boolean or a blanked organization leave and nothing else (R51);
* a letterhead organization is kept only if the model says the letter is
written on behalf of an organization that is not a person, the name
occurs in the letter's first 1,200 characters (or the regulations.gov
organization), and it does not contain the submitter's own name.
regulations.gov's own fields win over the letterhead model.
"""
from __future__ import annotations
import re
import time
from collections import Counter
from collections.abc import Mapping
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
from typing import Any, Callable, Sequence
import httpx
from sqlalchemy import text
from pfs.anchors import code_or_family_predicate
from pfs.codetables import CommenterRow
from pfs.runlog import RunLog, input_hash, run_units
TASK = "commenters"
IDENTITY_PROMPT_VERSION = "identity-v4"
ORG_TYPES = (
"specialty_society",
"health_system",
"vendor",
"payer",
"patient_group",
"individual_clinician",
"individual",
"other",
"unknown",
)
_PERSON_TYPES = ("individual", "individual_clinician")
_LETTERHEAD_CHARS = 1200
_ITEM_CHARS = 3000
_ITEM_CHUNKS = 3
_COMMENTS_COLLECTION = "comments"
#: regulations.gov ``category`` -> org type. An ambiguous category maps to
#: ``""`` and defers to the letterhead. Extended from the live dry runs.
CATEGORY_MAP: dict[str, str] = {
"Individual": "individual",
"Physician": "individual_clinician",
"Insurance": "payer",
"Consumer Group": "patient_group",
# extended from the live dry runs over every PFS docket (2026-11-12).
# Single-clinician categories:
"Physician - HC005": "individual_clinician",
"Nurse - HC065": "individual_clinician",
"Nurse Practitioner - HC015": "individual_clinician",
"Physical Therapist - HC045": "individual_clinician",
"Occupational Therapist - HC050": "individual_clinician",
# Facilities and providers:
"Hospital - HPA35": "health_system",
"Home Health Facility - HPA25": "health_system",
"Hospice - HPA30": "health_system",
"Rural Health Clinic - HPA65": "health_system",
"Health Care Provider/Association - Hospital": "health_system",
"Health Care Provider/Association - Hospice": "health_system",
"Health Care Provider/Association - Home Health Facility": "health_system",
"Health Care Provider/Association - Long-term Care": "health_system",
"Health Care Provider/Association - Rural Health Clinic": "health_system",
# Payers and industry:
"Health Plan or Association": "payer",
"Health Plan or Association - HP010": "payer",
"Private Industry - Device": "vendor",
"Private Industry - Drug": "vendor",
# Deliberately unmapped (they mix individuals and associations, or a
# society with a trade group; every "Government - ..." category, "Other -
# ...", "Academic - ...", "Attorney/Law Firm" and the organ procurement
# category too: real organizations of every type file under them, e.g. a
# physician society as "Government - Federal"): "Health Care Professional/Association -
# *", "Health Care Professional or Association - HC001", "Association -
# *", "Other Association - AS020", "Health Care Industry - PI015",
# "Private Industry - Health Care", "Other Health Care Provider -
# HPA70", "Other Health Care Professional - HC075", "Health Care
# Provider/Association - Other", and no category at all. They defer to
# the letterhead.
}
# ── specialties ──────────────────────────────────────────────────────
def specialty_key(name: str) -> str:
"""Upper-case, ``&`` -> ``AND``, non-alphanumerics -> one space."""
s = (name or "").upper().replace("&", " AND ")
return re.sub(r"[^A-Z0-9]+", " ", s).strip()
def specialty_vocab(con: Any) -> tuple[str, ...]:
rows = con.execute(
"SELECT DISTINCT specialty_description "
"FROM terminology.cms_acceptable_provider_specialty_codes "
"WHERE specialty_description IS NOT NULL"
).fetchall()
keys = {specialty_key(r[0]) for r in rows} - {""}
return tuple(sorted(keys | {"MULTISPECIALTY"}))
# ── regulations.gov fields ───────────────────────────────────────────
@dataclass(frozen=True)
class RegsFields:
category: str
organization: str
class MirrorUnavailable(Exception):
"""The mirror JSON could not be read, so the submitter's name cannot be
checked. Fails closed (R53): the item gets no ledger entry and no row."""
_RETRIES = 2
def _transient(exc: Exception) -> bool:
"""A network error or a 5xx answer: worth another try (R55)."""
if isinstance(exc, httpx.HTTPStatusError):
return exc.response.status_code >= 500
return isinstance(exc, httpx.TransportError)
def _attrs(mirror: Any, docket: str, comment_id: str) -> dict:
for attempt in range(_RETRIES + 1):
try:
data = mirror.get_json(docket, comment_id)
attrs = data["data"]["attributes"]
break
except Exception as exc: # noqa: BLE001 - any read problem fails closed
if _transient(exc) and attempt < _RETRIES:
time.sleep(0.5 * (attempt + 1))
continue
raise MirrorUnavailable(type(exc).__name__) from None
if not isinstance(attrs, dict):
raise MirrorUnavailable("attributes")
return attrs
def _norm(s: str) -> str:
return re.sub(r"[^a-z0-9]+", " ", (s or "").lower()).strip()
def _mentions(org: str, names: Sequence[str]) -> bool:
hay = f" {_norm(org)} "
return any(f" {n} " in hay for n in (_norm(x) for x in names) if len(n) >= 2 and n)
def regs_fields(mirror: Any, docket: str, comment_id: str) -> RegsFields:
"""``category`` and ``organization`` of one comment. The submitter's
first/last name are compared against the organization inside this
call (R51) and never leave it: an organization that contains either
is returned blank."""
attrs = _attrs(mirror, docket, comment_id)
org = str(attrs.get("organization") or "").strip()
if _mentions(
org, (str(attrs.get("firstName") or ""), str(attrs.get("lastName") or ""))
):
org = ""
return RegsFields(str(attrs.get("category") or "").strip(), org)
def _org_names_submitter(mirror: Any, docket: str, comment_id: str, org: str) -> bool:
"""True if *org* contains the submitter's own first or last name (R51).
Only the boolean leaves this call."""
attrs = _attrs(mirror, docket, comment_id)
return _mentions(
org, (str(attrs.get("firstName") or ""), str(attrs.get("lastName") or ""))
)
# ── letterhead model ─────────────────────────────────────────────────
def _schema(specialties: Sequence[str]) -> dict:
return {
"type": "object",
"properties": {
"organization": {"type": "string", "maxLength": 160},
"org_type": {"type": "string", "enum": list(ORG_TYPES)},
"specialty": {"type": "string", "enum": [*specialties, "NONE"]},
"on_behalf_of_organization": {"type": "boolean"},
},
"required": [
"organization",
"org_type",
"specialty",
"on_behalf_of_organization",
],
}
_SYSTEM = (
"You read the opening of a public comment letter to a Medicare payment rule "
"and say who wrote it. organization: the organization named in the letterhead "
"or signature, copied exactly, or an empty string. org_type: specialty_society "
"(a medical specialty association), health_system, vendor (only a for-profit company "
"selling products or services; never an association, coalition, council, "
"institute or advocacy, policy or legal center, whatever its topic), payer, patient_group, individual_clinician (a single physician or other clinician), "
"individual (a patient or member of the public), other (including trade "
"associations, coalitions, advocacy groups, management or policy "
"organizations and law centers not tied to one specialty), or unknown. "
"specialty: the medical specialty the author or organization represents, or NONE. "
"on_behalf_of_organization: true only if the letter is written for an organization. "
"Never put a person's name in organization."
)
def _squash(s: str) -> str:
return re.sub(r"\s+", " ", s or "").strip().lower()
def letterhead_identity(
text: str, ask: Callable, *, specialties: Sequence[str], reg_org: str = ""
) -> dict | None:
"""Ask who wrote the letter from its first 1,200 characters. The
organization is blanked unless the letter is on behalf of an
organization, the type is not a person, and the name occurs in the
text or the regulations.gov organization."""
head = (text or "")[:_LETTERHEAD_CHARS]
reply = ask(_SYSTEM, head, _schema(specialties))
if reply is None:
return None
org = str(reply.get("organization") or "").strip()
on_behalf = bool(reply.get("on_behalf_of_organization"))
org_type = reply.get("org_type")
if org_type not in ORG_TYPES:
org_type = "unknown"
spec = reply.get("specialty")
if spec not in specialties:
spec = "NONE"
needle = _squash(org)
keep = (
bool(needle)
and on_behalf
and org_type not in _PERSON_TYPES
and (needle in _squash(head) or needle in _squash(reg_org))
)
return {
"organization": org if keep else "",
"org_type": org_type,
"specialty": spec,
"on_behalf_of_organization": on_behalf,
}
# ── campaigns ────────────────────────────────────────────────────────
def form_groups(texts: Mapping[str, str]) -> dict[str, tuple[str, int]]:
"""item_key -> (group id, size) for groups of at least
``FORM_LETTER_MIN_SIZE`` near-identical letters."""
# imported here: ``rex`` pulls optional lake dependencies at import time
# and ``stack`` must start without them
from rex.comments.coordination import (
FORM_LETTER_MIN_SIZE,
find_groups,
form_letter_groups,
)
groups = find_groups(dict(texts))
keep = form_letter_groups(groups, min_size=FORM_LETTER_MIN_SIZE)
sizes = Counter(g for g in groups.values() if g in keep)
return {k: (g, sizes[g]) for k, g in groups.items() if g in keep}
# ── items ────────────────────────────────────────────────────────────
_OPEN_CHUNKS = 6
_HEADER_CHUNKS = 3
#: the Federal Register header of an uploaded copy of the rule
_RULE_HEADER = re.compile(
r"DEPARTMENT OF HEALTH AND HUMAN SERVICES\s+Centers for Medicare"
r"[\s\S]{0,400}?\b42 CFR (?:Parts?|Chapter)",
re.I,
)
_MD_HEADER = re.compile(r"^## .*$", re.M)
# (item_key, section, seq, document, rs[, matched]): ``rs`` is the chunk's
# 1-based position inside its section (an attachment or the inline comment)
Chunk = tuple
def _chunks_sql(*, matched: bool, with_phrases: bool = False) -> Any:
"""Per item: every chunk of the first ``_OPEN_CHUNKS`` of each section
(to read the opening and spot an uploaded rule), plus, for the selector,
every chunk that matches the family."""
pred = code_or_family_predicate("e")
phrase = " OR e.document ~* :phrase_re" if with_phrases else ""
flag = f"({pred}{phrase})" if matched else "false"
scope = (
"AND e.cmetadata->>'item_key' IN (SELECT e2.cmetadata->>'item_key' "
"FROM langchain_pg_embedding e2 "
"WHERE e2.collection_id = (SELECT uuid FROM langchain_pg_collection "
"WHERE name = :collection) AND e2.cmetadata->>'docket' = :docket "
f"AND ({code_or_family_predicate('e2')}"
f"{phrase.replace('e.', 'e2.')})) "
if matched
else "AND e.cmetadata->>'item_key' = ANY(:keys) "
)
seq = "COALESCE(NULLIF(e.cmetadata->>'seq', '')::int, 0)"
# ``section`` metadata is only the last heading in a chunk, so an
# attachment is found by its own "## attachment_N" marker chunk: every
# chunk after a marker (until the next one) belongs to that attachment
marker = (
f"max(CASE WHEN e.document ~ ('(^|' || chr(10) || ')## attachment_') "
f"THEN {seq} END) OVER (PARTITION BY e.cmetadata->>'item_key' "
f"ORDER BY {seq})"
)
return text(
"SELECT item_key, section, seq, document, rs, matched FROM ( "
"SELECT item_key, section, seq, document, matched, "
"row_number() OVER (PARTITION BY item_key, section ORDER BY seq) AS rs "
"FROM ( "
"SELECT e.cmetadata->>'item_key' AS item_key, "
f"{marker} AS section, e.document AS document, {seq} AS seq, "
f"{flag} AS matched "
"FROM langchain_pg_embedding e "
"WHERE e.collection_id = (SELECT uuid FROM langchain_pg_collection "
"WHERE name = :collection) AND e.cmetadata->>'docket' = :docket "
f"{scope}"
") u ) t "
f"WHERE rs <= {_OPEN_CHUNKS} OR matched ORDER BY item_key, seq"
)
def _own_chunks(rows: Sequence[Chunk]) -> tuple[dict[str, list[Chunk]], set[str]]:
"""Per item the chunks that are the commenter's own words: every chunk of
an attachment that opens with the Federal Register header (an uploaded
copy of the rule) is dropped. Also the set of items that had one."""
uploads: set[tuple[str, str | None]] = {
(r[0], r[1])
for r in rows
if r[4] <= _HEADER_CHUNKS and _RULE_HEADER.search(r[3] or "")
}
own: dict[str, list[Chunk]] = {}
for r in rows:
if (r[0], r[1]) not in uploads:
own.setdefault(r[0], []).append(r)
return own, {k for k, _ in uploads}
def family_comment_items(
engine: Any,
codes: Sequence[str],
family_key: str,
phrases: Sequence[str],
*,
docket: str,
) -> list[tuple[str, str]]:
"""``(item_key, text)``, one row per comment in *docket* that names a
family code, belongs to the family, or contains a pair phrase *in its own
words*: an attachment that is a copy of the rule is ignored (R54), so a
comment matches only through its inline text and other attachments. The
text is the lowest-``seq`` matching chunks (up to 3) joined, at most
3,000 characters."""
params: dict[str, Any] = {
"codes": [c.upper() for c in codes],
"family_key": family_key.upper(),
"collection": _COMMENTS_COLLECTION,
"docket": docket,
}
if phrases:
params["phrase_re"] = "|".join(re.escape(p) for p in phrases)
with engine.begin() as conn:
rows = conn.execute(
_chunks_sql(matched=True, with_phrases=bool(phrases)), params
).fetchall()
own, _ = _own_chunks(rows)
out = []
for k in sorted(own):
hit = sorted((r for r in own[k] if r[5]), key=lambda r: r[2])[:_ITEM_CHUNKS]
if hit:
out.append((k, "\n".join(r[3] or "" for r in hit)[:_ITEM_CHARS]))
return out
@dataclass(frozen=True)
class Opening:
"""A comment's opening in its own words: chunk 0 (the inline comment),
then the first attachment chunks in seq order, markdown headers dropped,
at most 3,000 characters. ``rule_copy`` says an uploaded copy of the rule
was left out."""
text: str
rule_copy: bool
def item_openings(
engine: Any, keys: Sequence[str], *, docket: str
) -> dict[str, Opening]:
"""The opening of each comment in *keys*, without any attachment that is a
copy of the rule."""
with engine.begin() as conn:
rows = conn.execute(
_chunks_sql(matched=False),
{
"collection": _COMMENTS_COLLECTION,
"docket": docket,
"keys": list(keys),
},
).fetchall()
own, uploaded = _own_chunks(rows)
out = {}
for k, chunks in own.items():
first = sorted(chunks, key=lambda r: r[2])[:_OPEN_CHUNKS]
joined = "\n".join(r[3] or "" for r in first)
body = re.sub(r"\n{2,}", "\n", _MD_HEADER.sub("", joined)).strip()
out[k] = Opening(body[:_ITEM_CHARS], k in uploaded)
return out
_COMMENT_ID = re.compile(r"/comment/([^/?#\s]+)")
def _comment_id(store: Any, item_key: str) -> str:
try:
m = _COMMENT_ID.search(getattr(store.get(item_key), "url", "") or "")
except KeyError:
return ""
return m.group(1) if m else ""
# ── identify ─────────────────────────────────────────────────────────
_WORKERS = 8
def regs_for(
store: Any, mirror: Any, docket: str, keys: Sequence[str]
) -> tuple[dict[str, str], dict[str, RegsFields]]:
"""Comment id and regulations.gov fields per item key (a few threads:
one mirror GET each). An item whose mirror JSON cannot be read is left
out of the fields (R53: fail closed)."""
cids = {k: _comment_id(store, k) for k in keys}
def one(k: str) -> RegsFields | None:
try:
return regs_fields(mirror, docket, cids[k])
except MirrorUnavailable:
return None
with ThreadPoolExecutor(_WORKERS) as pool:
got = pool.map(one, keys)
return cids, {k: r for k, r in zip(keys, got, strict=True) if r is not None}
def _combine(regs: RegsFields, letter: dict | None) -> tuple[str, str, str, str]:
"""(org_name, org_type, specialty, basis). regulations.gov wins; "both"
when its category and the letterhead agree."""
mapped = CATEGORY_MAP.get(regs.category, "")
lh_type = letter["org_type"] if letter else ""
if mapped:
org_type, basis = mapped, ("both" if lh_type == mapped else "regs_gov_fields")
elif lh_type:
org_type, basis = lh_type, "letterhead_model"
else:
org_type, basis = "unknown", "regs_gov_fields"
org = regs.organization or (letter["organization"] if letter else "")
if org_type in _PERSON_TYPES:
org = ""
spec = letter["specialty"] if letter else "NONE"
return org, org_type, "" if spec == "NONE" else spec, basis
def identify(
engine: Any,
store: Any,
con: Any,
family: Any,
*,
docket: str,
mirror: Any,
ask: Callable,
log: RunLog,
limit: int = 0,
retry_failed: bool = False,
progress: Callable[[str, str], None] | None = None,
) -> tuple[list[CommenterRow], dict[str, int]]:
"""One ``CommenterRow`` per family comment in *docket*. The family
selector picks WHICH comments (in the commenter's own words, never an
uploaded copy of the rule); the identity input is each comment's opening
(R53). A comment whose mirror JSON cannot be read (so the name guard
cannot run) becomes a ``blocked:mirror`` row, org type ``unknown``, no
model call and no ledger entry (R55); a later run replaces it. Counts are
the run counts plus ``pending`` (no ledger answer yet) and ``blocked``."""
items = family_comment_items(
engine, family.codes, family.key, family.pair_phrases, docket=docket
)
keys = [k for k, _ in items]
cids, regs = regs_for(store, mirror, docket, keys)
openings = item_openings(engine, keys, docket=docket)
keys = [k for k in keys if k in openings]
blocked = {k for k in keys if k not in regs}
specialties = specialty_vocab(con)
model = getattr(ask, "model", "unknown")
def unit(key: str) -> dict | None:
letter = letterhead_identity(
openings[key].text,
ask,
specialties=specialties,
reg_org=regs[key].organization,
)
if letter and letter["organization"]:
if _org_names_submitter(mirror, docket, cids[key], letter["organization"]):
letter["organization"] = ""
return letter
hashes = {
k: input_hash(openings[k].text[:_LETTERHEAD_CHARS], regs[k].organization)
for k in keys
if k in regs
}
counts = {"done": 0, "skipped": 0, "failed": 0, "failed_pending": 0}
calls = 0
for k in hashes:
if limit and calls >= limit:
break
try:
one = run_units(
[(k, hashes[k], lambda k=k: unit(k))],
log,
model=model,
version=IDENTITY_PROMPT_VERSION,
retry_failed=retry_failed,
progress=progress,
)
except MirrorUnavailable:
# the name guard could not read the mirror: fail closed
blocked.add(k)
continue
calls += one["done"] + one["failed"]
for name, n in one.items():
counts[name] += n
forms = form_groups({k: openings[k].text for k in keys})
rows: list[CommenterRow] = []
pending = 0
for k in keys:
gid, size = forms.get(k, ("", 0))
if k in blocked:
rows.append(
CommenterRow(
k,
docket,
cids[k],
"",
"unknown",
"",
gid,
size,
"regs_gov_fields",
"",
"blocked:mirror",
family.key,
)
)
continue
entry = log.get(k, hashes[k], model, IDENTITY_PROMPT_VERSION)
letter = entry.output if entry is not None else None
if entry is None:
pending += 1
org, org_type, spec, basis = _combine(regs[k], letter)
rows.append(
CommenterRow(
item_key=k,
docket=docket,
comment_id=cids[k],
org_name=org,
org_type=org_type,
specialty=spec,
form_group=gid,
form_size=size,
basis=basis,
reg_category=regs[k].category,
extractor=(
f"model:{model}@{IDENTITY_PROMPT_VERSION}" if letter else "regs"
),
family=family.key,
)
)
return rows, {**counts, "pending": pending, "blocked": len(blocked)}