feat(pfs): commenters carry the submitter name as posted (R60), org names no longer blanked, identity-v5
Some checks failed
CI / lint (push) Successful in 47s
CI / notebooks-smoke (push) Successful in 2m0s
Deploy / changes (push) Successful in 18s
CI / test (push) Failing after 3m29s
Infra CI / zotero (push) Successful in 29s
Infra CI / notebooks (push) Successful in 1m43s
Infra CI / api (push) Successful in 2m24s
Infra CI / docs (push) Successful in 3m26s
Infra CI / llm (push) Successful in 1m40s
Infra CI / mc (push) Successful in 20s
Deploy / notebooks (push) Has been skipped
Deploy / zotero (push) Has been skipped
Infra CI / bcda (push) Successful in 2m59s
Deploy / docs (push) Successful in 1m18s
Deploy / api (push) Successful in 2m31s
Deploy / bcda (push) Successful in 3m11s
Deploy / mc (push) Has been skipped
Deploy / llm (push) Successful in 2m16s
Deploy / report (push) Successful in 1m12s

This commit is contained in:
kert
2026-11-12 16:14:41 -05:00
parent e1913ac89b
commit 6c4587d0be
4 changed files with 130 additions and 155 deletions

View File

@@ -1347,8 +1347,8 @@ def commenters(
write: bool = typer.Option(False, "--write"),
) -> None:
"""Who wrote each family comment (pfs.commenter): organization, type,
specialty and form-letter campaign. Names of people are never stored
or printed; individuals are only an organization type."""
specialty, form-letter campaign and the submitter name as the
regulations.gov record posts it (official public record)."""
fam = curated_family(normalize_key(family))
if fam is None:
raise typer.BadParameter(f"unknown curated family {family!r}")

View File

@@ -400,8 +400,8 @@ class CmsSummaryRow:
class CommenterRow:
"""Who wrote one public comment (``pfs.commenter``, task 8): the
organization, its type, the specialty and the form-letter campaign.
No person's name is ever stored; an individual is only an
``org_type`` with a blank ``org_name``. ``basis`` is
``submitter_name`` is the regulations.gov first and last name exactly
as that comment posted them (official public record, R60). ``basis`` is
``regs_gov_fields``, ``letterhead_model`` or ``both`` (regulations.gov
category and letterhead agree)."""
@@ -419,6 +419,7 @@ class CommenterRow:
extractor: str
#: the curated family whose comment set this row belongs to (R57)
family: str = ""
submitter_name: str = ""
ORIGIN_KINDS = (
@@ -533,7 +534,8 @@ CREATE TABLE IF NOT EXISTS pfs.cms_comment_summary (
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);
basis VARCHAR, reg_category VARCHAR, extractor VARCHAR, family VARCHAR,
submitter_name 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,
@@ -589,6 +591,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")
# R60: the commenter's name as posted
con.execute(
"ALTER TABLE pfs.commenter ADD COLUMN IF NOT EXISTS submitter_name VARCHAR"
)
# task 9: per-event stance counts
con.execute(
"ALTER TABLE pfs.code_reaction ADD COLUMN IF NOT EXISTS events_json VARCHAR"
@@ -614,6 +620,9 @@ def ensure_tables(con: Any) -> None:
"DEFAULT false"
)
con.execute("UPDATE pfs.commenter SET family = 'HOME-VISITS' WHERE family IS NULL")
con.execute(
"UPDATE pfs.commenter SET submitter_name = '' WHERE submitter_name IS NULL"
)
def _insert(con: Any, table: str, rows: Sequence[Any]) -> int:

View File

@@ -2,17 +2,14 @@
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.
Commenter names are official federal public record (ruling R60): each
row carries ``submitter_name``, the regulations.gov first and last name
exactly as THAT comment posted them, read from its own mirror record and
never from a model, another comment or the bib title. The risk guarded
against is misattribution. A letterhead organization is kept only if the
model says the letter is written on behalf of an organization that is not
a person and the name occurs in the letter's first 1,200 characters (or
the regulations.gov organization).
regulations.gov's own fields win over the letterhead model.
"""
@@ -35,7 +32,7 @@ from pfs.codetables import CommenterRow
from pfs.runlog import RunLog, input_hash, run_units
TASK = "commenters"
IDENTITY_PROMPT_VERSION = "identity-v4"
IDENTITY_PROMPT_VERSION = "identity-v5"
ORG_TYPES = (
"specialty_society",
"health_system",
@@ -122,11 +119,12 @@ def specialty_vocab(con: Any) -> tuple[str, ...]:
class RegsFields:
category: str
organization: str
submitter_name: 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."""
"""The mirror JSON could not be read, so the comment's own regulations.gov
fields (and its posted name) are unknown. Fails closed (R53): the item gets no ledger entry and no row."""
_RETRIES = 2
@@ -155,35 +153,23 @@ def _attrs(mirror: Any, docket: str, comment_id: str) -> dict:
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."""
"""``category``, ``organization`` and the posted submitter name (first
and last name joined by one space, stripped) of one comment, all from
that comment's own mirror record."""
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 ""))
name = " ".join(
p
for p in (
str(attrs.get("firstName") or "").strip(),
str(attrs.get("lastName") or "").strip(),
)
if p
)
return RegsFields(
str(attrs.get("category") or "").strip(),
str(attrs.get("organization") or "").strip(),
name,
)
@@ -219,8 +205,7 @@ _SYSTEM = (
"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."
"on_behalf_of_organization: true only if the letter is written for an organization."
)
@@ -501,8 +486,8 @@ def identify(
"""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
(R53). A comment whose mirror JSON cannot be read (so the category,
organization and submitter name are unknown) 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(
@@ -517,16 +502,12 @@ def identify(
model = getattr(ask, "model", "unknown")
def unit(key: str) -> dict | None:
letter = letterhead_identity(
return 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)
@@ -538,19 +519,14 @@ def identify(
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
one = run_units(
[(k, hashes[k], lambda k=k: unit(k))],
log,
model=model,
version=IDENTITY_PROMPT_VERSION,
retry_failed=retry_failed,
progress=progress,
)
calls += one["done"] + one["failed"]
for name, n in one.items():
counts[name] += n
@@ -574,6 +550,7 @@ def identify(
"",
"blocked:mirror",
family.key,
"",
)
)
continue
@@ -598,6 +575,7 @@ def identify(
f"model:{model}@{IDENTITY_PROMPT_VERSION}" if letter else "regs"
),
family=family.key,
submitter_name=regs[k].submitter_name,
)
)
return rows, {**counts, "pending": pending, "blocked": len(blocked)}

View File

@@ -145,41 +145,59 @@ def _reply(**kw):
return {**base, **kw}
def test_no_person_names_survive(tmp_path, con, store, capsys):
mirror = FakeMirror(
{
"category": "Physician",
"organization": "",
"firstName": "Jane",
"lastName": "Doe",
}
)
ask = FakeAsk(
_reply(
organization="Jane Doe MD",
org_type="individual_clinician",
specialty="FAMILY PRACTICE",
)
)
path = tmp_path / "l.jsonl"
rows, _ = identify(
engine_with([("K1", "Dear Administrator ... Sincerely, Jane Doe, MD")])[0],
def _run(tmp_path, con, store, mirror, ask, rows, key="K1"):
return identify(
engine_with(rows)[0],
store,
con,
HOME,
docket="CMS-2022-0113",
mirror=mirror,
ask=ask,
log=RunLog(path),
log=RunLog(tmp_path / "l.jsonl"),
)
assert "Doe" not in repr(rows) and "Jane" not in repr(rows)
def test_submitter_name_is_the_comments_own_posted_name(tmp_path, con, store):
mirror = FakeMirror(
{
"category": "Physician",
"organization": "",
"firstName": " Jane ",
"lastName": "Doe",
}
)
ask = FakeAsk(_reply(org_type="individual_clinician", specialty="FAMILY PRACTICE"))
rows, _ = _run(tmp_path, con, store, mirror, ask, [("K1", "Sincerely, Jane Doe")])
assert rows[0].submitter_name == "Jane Doe"
assert (rows[0].org_type, rows[0].org_name) == ("individual_clinician", "")
assert rows[0].specialty == "FAMILY PRACTICE"
assert "Doe" not in path.read_text()
assert "Jane" not in capsys.readouterr().out
write_commenters(con, rows)
assert read_commenters(con)[0].submitter_name == "Jane Doe"
def test_submitter_name_in_org_is_blanked_type_kept(tmp_path, con, store, capsys):
def test_two_comments_never_swap_names(tmp_path, con, store):
# the fake store gives K1 .../CMS-X-0 and K2 .../CMS-X-1
mirror = FakeMirror(
per_id={
"CMS-X-0": {"category": "Individual", "firstName": "Ann", "lastName": "A"},
"CMS-X-1": {"category": "Individual", "firstName": "Bob", "lastName": "B"},
}
)
ask = FakeAsk(_reply(org_type="individual"))
rows, _ = _run(
tmp_path, con, store, mirror, ask, [("K1", "letter one"), ("K2", "letter two")]
)
assert {r.item_key: r.submitter_name for r in rows} == {
"K1": "Ann A",
"K2": "Bob B",
}
assert {r.item_key: r.comment_id for r in rows} == {
"K1": "CMS-X-0",
"K2": "CMS-X-1",
}
def test_solo_practice_keeps_org_name(tmp_path, con, store):
mirror = FakeMirror(
{"category": "", "organization": "", "firstName": "Jane", "lastName": "Doe"}
)
@@ -190,30 +208,42 @@ def test_submitter_name_in_org_is_blanked_type_kept(tmp_path, con, store, capsys
on_behalf_of_organization=True,
)
)
path = tmp_path / "l.jsonl"
rows, _ = identify(
engine_with([("K1", "Letter of Doe Family Medicine PLLC about visits")])[0],
store,
rows, _ = _run(
tmp_path,
con,
HOME,
docket="D",
mirror=mirror,
ask=ask,
log=RunLog(path),
store,
mirror,
ask,
[("K1", "Letter of Doe Family Medicine PLLC about visits")],
)
assert (rows[0].org_name, rows[0].org_type) == ("", "health_system")
assert (rows[0].org_name, rows[0].org_type) == (
"Doe Family Medicine PLLC",
"health_system",
)
assert rows[0].submitter_name == "Jane Doe"
assert rows[0].basis == "letterhead_model"
assert "Doe" not in repr(rows) and "Doe" not in path.read_text()
assert "Doe" not in capsys.readouterr().out
def test_regs_organization_with_submitter_name_is_blanked():
def test_regs_organization_is_kept_even_with_submitter_name():
m = FakeMirror(
{"category": "Individual", "organization": "Doe Clinic", "lastName": "Doe"}
{
"category": "Individual",
"organization": "Doe Clinic",
"firstName": "Jane",
"lastName": "Doe",
}
)
assert regs_fields(m, "D", "c") == RegsFields(
"Individual", "Doe Clinic", "Jane Doe"
)
def test_missing_name_is_blank():
for attrs in ({}, {"firstName": None, "lastName": ""}, {"firstName": " "}):
assert regs_fields(FakeMirror(attrs), "D", "c").submitter_name == ""
assert (
regs_fields(FakeMirror({"lastName": "Doe"}), "D", "c").submitter_name == "Doe"
)
assert regs_fields(m, "D", "c") == RegsFields("Individual", "")
m = FakeMirror({"category": "Business", "organization": "AAFP", "lastName": "Doe"})
assert regs_fields(m, "D", "c") == RegsFields("Business", "AAFP")
def test_regs_fields_fails_closed_on_unreadable_json():
@@ -500,21 +530,6 @@ def test_category_map_values_are_org_types_and_ambiguous_unmapped():
assert CATEGORY_MAP.get(ambiguous, "") == ""
class FlakyMirror(FakeMirror):
"""Reads fine for regs fields (first call per id), fails on the second:
the name guard's re-read."""
def __init__(self, attrs):
super().__init__(attrs)
self.seen = set()
def get_json(self, docket, cid):
if cid in self.seen:
raise RuntimeError("503")
self.seen.add(cid)
return super().get_json(docket, cid)
def test_identity_input_is_the_opening_not_the_matching_chunk(tmp_path, con, store):
opening = {
"K1": ["## Inline comment", "tMED Coalition writes.", "second chunk"]
@@ -537,7 +552,7 @@ def test_identity_input_is_the_opening_not_the_matching_chunk(tmp_path, con, sto
sent = ask.calls[0][1]
assert sent.startswith("tMED Coalition writes.\nsecond chunk\nfiller 0")
assert "late matching" not in sent and "##" not in sent
assert IDENTITY_PROMPT_VERSION == "identity-v4"
assert IDENTITY_PROMPT_VERSION == "identity-v5"
RULE_HDR = (
@@ -735,35 +750,6 @@ def test_blocked_item_becomes_unknown_row_without_model_call_then_is_replaced(
assert [r.org_type for r in read_commenters(con)] == ["payer"]
def test_name_guard_fails_closed_when_mirror_read_fails(tmp_path, con, store):
path = tmp_path / "l.jsonl"
ask = FakeAsk(
_reply(
organization="Acme Society",
org_type="specialty_society",
on_behalf_of_organization=True,
)
)
mirror = FlakyMirror({"category": "", "firstName": "Jane", "lastName": "Doe"})
rows, counts = identify(
engine_with([("K1", "Acme Society writes"), ("K2", "Acme Society too")])[0],
store,
con,
HOME,
docket="D",
mirror=mirror,
ask=ask,
log=RunLog(path),
)
# the first read per comment id succeeds, the guard's re-read fails: the
# item is a blocked row and no name-bearing org was stored or ledgered
assert counts["blocked"] == 2 and counts["done"] == 0
assert [(r.org_name, r.org_type, r.extractor) for r in rows] == [
("", "unknown", "blocked:mirror")
] * 2
assert not path.exists() or path.read_text() == ""
def test_retry_failed_reasks_failed_entries(tmp_path, con, store):
log = RunLog(tmp_path / "l.jsonl")
kw = dict(docket="D", mirror=FakeMirror(), log=log)
@@ -844,6 +830,8 @@ def test_legacy_commenter_table_is_migrated_to_home_visits():
)
ensure_tables(c)
assert [r.family for r in read_commenters(c)] == ["HOME-VISITS"]
# the name column is added too, blank for rows written before it existed
assert [r.submitter_name for r in read_commenters(c)] == [""]
def test_identify_sets_family(tmp_path, con, store):