From bc1747bc07225b24436c8d96123c00079ceb705f Mon Sep 17 00:00:00 2001 From: kert Date: Thu, 12 Nov 2026 12:21:00 -0500 Subject: [PATCH] =?UTF-8?q?fix(pfs):=20commenters=20=E2=80=94=20identity?= =?UTF-8?q?=20from=20the=20comment=20opening=20(identity-v2),=20form=20gro?= =?UTF-8?q?ups=20on=20openings=20minus=20rule=20uploads,=20--retry-failed,?= =?UTF-8?q?=20fail-closed=20name=20guard,=20narrower=20category=20map?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/cli/pfs.py | 8 +- src/pfs/commenters.py | 178 +++++++++++++++++++++++------ tests/cli/test_pfs_cli.py | 8 +- tests/pfs/test_commenters.py | 209 ++++++++++++++++++++++++++++++++++- 4 files changed, 360 insertions(+), 43 deletions(-) diff --git a/src/cli/pfs.py b/src/cli/pfs.py index 7277959..3bcc28b 100644 --- a/src/cli/pfs.py +++ b/src/cli/pfs.py @@ -1233,6 +1233,9 @@ def commenters( 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", @@ -1254,6 +1257,8 @@ def commenters( mirror = _mirror() _, regs = regs_for(_store(), mirror, docket, [k for k, _ in items]) cats = Counter(r.category for r in regs.values()) + if len(regs) < len(items): + typer.echo(f" unreadable mirror JSON: {len(items) - len(regs)}") typer.echo(f"{docket}: {len(items)} items; no model calls made") for cat, n in sorted(cats.items(), key=lambda kv: (-kv[1], kv[0])): typer.echo(f" category {cat or '(none)'}: {n}") @@ -1270,6 +1275,7 @@ def commenters( ask=_asker(), log=RunLog(ledger_path("commenters", fam.key)), limit=limit, + retry_failed=retry_failed, progress=lambda unit, status: typer.echo(f"{unit} {status}"), ) finally: @@ -1280,7 +1286,7 @@ def commenters( typer.echo( f"commenters: {len(rows)}; done {counts['done']}, skipped {counts['skipped']}, " f"failed {counts['failed']}, failed_pending {counts['failed_pending']}, " - f"pending {counts['pending']}" + f"pending {counts['pending']}, blocked {counts['blocked']}" ) if write: if counts["pending"]: diff --git a/src/pfs/commenters.py b/src/pfs/commenters.py index 0f3bd89..4cd0238 100644 --- a/src/pfs/commenters.py +++ b/src/pfs/commenters.py @@ -33,7 +33,7 @@ from pfs.codetables import CommenterRow from pfs.runlog import RunLog, input_hash, run_units TASK = "commenters" -IDENTITY_PROMPT_VERSION = "identity-v1" +IDENTITY_PROMPT_VERSION = "identity-v2" ORG_TYPES = ( "specialty_society", "health_system", @@ -80,17 +80,11 @@ CATEGORY_MAP: dict[str, str] = { "Health Plan or Association - HP010": "payer", "Private Industry - Device": "vendor", "Private Industry - Drug": "vendor", - # Neither a clinician nor a society: - "Government - Federal": "other", - "Government - Other": "other", - "Federal Government - G0005": "other", - "Attorney/Law Firm - OT010": "other", - "Academic - OT005": "other", - "Other - Academic": "other", - "Other - OT001": "other", - "Organ Procurement Organization - HPA50": "other", # Deliberately unmapped (they mix individuals and associations, or a - # society with a trade group): "Health Care Professional/Association - + # 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 - @@ -128,13 +122,20 @@ class RegsFields: 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.""" + + def _attrs(mirror: Any, docket: str, comment_id: str) -> dict: try: data = mirror.get_json(docket, comment_id) - except Exception: # noqa: BLE001 - a missing/odd mirror file is "no fields" - return {} - attrs = ((data or {}).get("data") or {}).get("attributes") - return attrs if isinstance(attrs, dict) else {} + attrs = data["data"]["attributes"] + except Exception as exc: # noqa: BLE001 - any read problem fails closed + raise MirrorUnavailable(type(exc).__name__) from None + if not isinstance(attrs, dict): + raise MirrorUnavailable("attributes") + return attrs def _norm(s: str) -> str: @@ -310,6 +311,77 @@ def family_comment_items( return [(k, "\n".join(v)[:_ITEM_CHARS]) for k, v in sorted(parts.items())] +_OPEN_CHUNKS = 6 +#: a comment with this many chunks is a whole document upload, not a letter +RULE_COPY_CHUNKS = 1000 +_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) + + +@dataclass(frozen=True) +class Opening: + """A comment's opening: chunk 0 (the inline comment), then the first + attachment chunks in seq order, at most 3,000 characters.""" + + text: str + n_chunks: int + rule_copy: bool + + +def is_rule_copy(head: str, n_chunks: int) -> bool: + """True for an upload of the rule itself: the Federal Register header + ("DEPARTMENT OF HEALTH AND HUMAN SERVICES / Centers for Medicare ... 42 + CFR Parts") in the opening chunks, or a chunk count far above any letter.""" + return n_chunks >= RULE_COPY_CHUNKS or bool(_RULE_HEADER.search(head)) + + +def item_openings( + engine: Any, keys: Sequence[str], *, docket: str +) -> dict[str, Opening]: + """The opening of each comment in *keys* (first six chunks by ``seq``, + markdown headers dropped, 3,000 characters), with its total chunk count + and whether it copies the rule.""" + sql = text( + "SELECT item_key, document, n FROM ( " + "SELECT e.cmetadata->>'item_key' AS item_key, e.document AS document, " + "COALESCE(NULLIF(e.cmetadata->>'seq', '')::int, 0) AS seq, " + "count(*) OVER (PARTITION BY e.cmetadata->>'item_key') AS n, " + "row_number() OVER (PARTITION BY e.cmetadata->>'item_key' " + "ORDER BY COALESCE(NULLIF(e.cmetadata->>'seq', '')::int, 0) ASC) AS rn " + "FROM langchain_pg_embedding e " + "WHERE e.collection_id = (SELECT uuid FROM langchain_pg_collection " + "WHERE name = :collection) " + "AND e.cmetadata->>'docket' = :docket " + "AND e.cmetadata->>'item_key' = ANY(:keys) " + ") t WHERE rn <= :n_chunks ORDER BY item_key, seq" + ) + with engine.begin() as conn: + rows = conn.execute( + sql, + { + "collection": _COMMENTS_COLLECTION, + "docket": docket, + "keys": list(keys), + "n_chunks": _OPEN_CHUNKS, + }, + ).fetchall() + docs: dict[str, list[str]] = {} + totals: dict[str, int] = {} + for item_key, doc, n in rows: + docs.setdefault(item_key, []).append(doc or "") + totals[item_key] = int(n) + out = {} + for k, parts in docs.items(): + joined = "\n".join(parts) + body = re.sub(r"\n{2,}", "\n", _MD_HEADER.sub("", joined)).strip() + out[k] = Opening(body[:_ITEM_CHARS], totals[k], is_rule_copy(joined, totals[k])) + return out + + _COMMENT_ID = re.compile(r"/comment/([^/?#\s]+)") @@ -330,11 +402,19 @@ 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).""" + 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(lambda k: regs_fields(mirror, docket, cids[k]), keys) - return cids, dict(zip(keys, got, strict=True)) + 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]: @@ -366,21 +446,33 @@ def identify( 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*. Counts are the - run counts plus ``pending`` (items with no ledger answer yet).""" + """One ``CommenterRow`` per family comment in *docket* whose mirror JSON + could be read. The family selector picks WHICH comments; the identity + input is each comment's opening (R53). Counts are the run counts plus + ``pending`` (no ledger answer yet) and ``blocked`` (mirror unreadable, + so the name guard cannot run: no ledger entry, no row).""" items = family_comment_items( engine, family.codes, family.key, family.pair_phrases, docket=docket ) - texts = dict(items) - cids, regs = regs_for(store, mirror, docket, list(texts)) + all_keys = [k for k, _ in items] + cids, regs = regs_for(store, mirror, docket, all_keys) + keys = [k for k in all_keys if k in regs] + blocked = len(all_keys) - len(keys) + openings = item_openings(engine, keys, docket=docket) + # a selected item always has chunks; guard anyway + keys = [k for k in keys if k in openings] specialties = specialty_vocab(con) model = getattr(ask, "model", "unknown") def unit(key: str) -> dict | None: letter = letterhead_identity( - texts[key], ask, specialties=specialties, reg_org=regs[key].organization + 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"]): @@ -388,20 +480,38 @@ def identify( return letter hashes = { - k: input_hash(texts[k][:_LETTERHEAD_CHARS], regs[k].organization) for k in texts + k: input_hash(openings[k].text[:_LETTERHEAD_CHARS], regs[k].organization) + for k in keys } - counts = run_units( - [(k, hashes[k], lambda k=k: unit(k)) for k in texts], - log, - model=model, - version=IDENTITY_PROMPT_VERSION, - limit=limit, - progress=progress, + counts = {"done": 0, "skipped": 0, "failed": 0, "failed_pending": 0} + calls = 0 + for k in keys: + 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 += 1 + hashes.pop(k) + continue + calls += one["done"] + one["failed"] + for name, n in one.items(): + counts[name] += n + keys = [k for k in keys if k in hashes] + forms = form_groups( + {k: openings[k].text for k in keys if not openings[k].rule_copy} ) - forms = form_groups(texts) rows: list[CommenterRow] = [] pending = 0 - for k in texts: + for k in keys: entry = log.get(k, hashes[k], model, IDENTITY_PROMPT_VERSION) letter = entry.output if entry is not None else None if entry is None: @@ -425,4 +535,4 @@ def identify( ), ) ) - return rows, {**counts, "pending": pending} + return rows, {**counts, "pending": pending, "blocked": blocked} diff --git a/tests/cli/test_pfs_cli.py b/tests/cli/test_pfs_cli.py index 2f5347e..9b0f079 100644 --- a/tests/cli/test_pfs_cli.py +++ b/tests/cli/test_pfs_cli.py @@ -1820,6 +1820,7 @@ class TestCommenters: "failed": 0, "failed_pending": 0, "pending": pending, + "blocked": 1, } monkeypatch.setattr(pfs_cli, "identify", fake) @@ -1844,6 +1845,7 @@ class TestCommenters: ("K2", "b"), ("K3", "c"), ("K4", "d"), + ("K5", "e"), ], ) regs = dict( @@ -1854,7 +1856,7 @@ class TestCommenters: "regs_for", lambda store, mirror, docket, keys: ( {}, - {k: SimpleNamespace(category=regs[k]) for k in keys}, + {k: SimpleNamespace(category=regs[k]) for k in keys if k in regs}, ), ) res = runner.invoke( @@ -1870,7 +1872,8 @@ class TestCommenters: ], ) assert res.exit_code == 0, res.output - assert "D1: 4 items; no model calls made" in res.output + assert "D1: 5 items; no model calls made" in res.output + assert "unreadable mirror JSON: 1" in res.output assert "category Individual: 2" in res.output assert "category (none): 1" in res.output assert "category Physician: 1" in res.output @@ -1901,6 +1904,7 @@ class TestCommenters: ) assert "K1 done" in res.output assert "individual: 2" in res.output and "specialty_society: 1" in res.output + assert "pending 0, blocked 1" in res.output assert "wrote 3 commenters" in res.output assert con.published == [True] assert len(read_commenters(con._real)) == 3 diff --git a/tests/pfs/test_commenters.py b/tests/pfs/test_commenters.py index a18c582..6e34786 100644 --- a/tests/pfs/test_commenters.py +++ b/tests/pfs/test_commenters.py @@ -20,10 +20,14 @@ from pfs.commenters import ( CATEGORY_MAP, IDENTITY_PROMPT_VERSION, ORG_TYPES, + MirrorUnavailable, + Opening, RegsFields, family_comment_items, form_groups, identify, + is_rule_copy, + item_openings, letterhead_identity, regs_fields, specialty_key, @@ -60,10 +64,26 @@ class FakeAsk: return self.reply -def engine_with(rows): +def engine_with(rows, n_chunks=1, openings=None): + """Fake pgvector engine: the selector query returns *rows*; the openings + query (the only one binding ``keys``) returns each key's opening.""" engine = MagicMock() conn = engine.begin.return_value.__enter__.return_value - conn.execute.return_value.fetchall.return_value = rows + opened = openings if openings is not None else {k: [t] for k, t in rows} + + def execute(sql, params): + result = MagicMock() + if "keys" in params: + result.fetchall.return_value = [ + (k, t, n_chunks if isinstance(n_chunks, int) else n_chunks[k]) + for k in params["keys"] + for t in opened.get(k, []) + ] + else: + result.fetchall.return_value = rows + return result + + conn.execute.side_effect = execute return engine, conn @@ -185,13 +205,16 @@ def test_regs_organization_with_submitter_name_is_blanked(): assert regs_fields(m, "D", "c") == RegsFields("Business", "AAFP") -def test_regs_fields_tolerates_missing_and_odd_json(): - assert regs_fields(FakeMirror(fail=True), "D", "c") == RegsFields("", "") +def test_regs_fields_fails_closed_on_unreadable_json(): + with pytest.raises(MirrorUnavailable): + regs_fields(FakeMirror(fail=True), "D", "c") odd = MagicMock() odd.get_json.return_value = {"data": {"attributes": "x"}} - assert regs_fields(odd, "D", "c") == RegsFields("", "") + with pytest.raises(MirrorUnavailable): + regs_fields(odd, "D", "c") odd.get_json.return_value = None - assert regs_fields(odd, "D", "c") == RegsFields("", "") + with pytest.raises(MirrorUnavailable): + regs_fields(odd, "D", "c") # a one-letter name never matches ("A" in "A Plus Health") m = FakeMirror({"organization": "A Plus Health", "firstName": "A"}) assert regs_fields(m, "D", "c").organization == "A Plus Health" @@ -450,3 +473,177 @@ def test_category_map_values_are_org_types_and_ambiguous_unmapped(): "Health Care Industry - PI015", ): 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"]} + engine, _ = engine_with( + [("K1", "late matching chunk about 99341")], openings=opening + ) + ask = FakeAsk(_reply(org_type="other")) + identify( + engine, + store, + con, + HOME, + docket="D", + mirror=FakeMirror(), + ask=ask, + log=RunLog(tmp_path / "l.jsonl"), + ) + sent = ask.calls[0][1] + assert sent == "tMED Coalition writes.\nsecond chunk" + assert "late matching" not in sent and "##" not in sent + assert IDENTITY_PROMPT_VERSION == "identity-v2" + + +def test_item_openings_headers_cap_and_rule_copy(): + rule = "DEPARTMENT OF HEALTH AND HUMAN SERVICES\nCenters for Medicare & Medicaid\nServices\n42 CFR Parts 410" + engine, conn = engine_with( + [], + n_chunks={"A": 4, "B": 3882, "C": 5}, + openings={ + "A": ["## Inline comment", "x" * 4000], + "B": ["a letter"], + "C": ["## attachment_1.pdf", rule], + }, + ) + out = item_openings(engine, ["A", "B", "C", "Z"], docket="D1") + assert set(out) == {"A", "B", "C"} + assert out["A"] == Opening("x" * 3000, 4, False) + assert out["B"] == Opening("a letter", 3882, True) + assert out["C"].rule_copy and out["C"].n_chunks == 5 + params = conn.execute.call_args.args[1] + assert params["keys"] == ["A", "B", "C", "Z"] and params["docket"] == "D1" + + +def test_is_rule_copy(): + assert is_rule_copy("x", 1000) and not is_rule_copy("x", 999) + hdr = "DEPARTMENT OF HEALTH AND HUMAN SERVICES Centers for Medicare & Medicaid Services 42 CFR Parts 405" + assert is_rule_copy(hdr, 3) + # a letter that merely cites the rule is not a copy + assert not is_rule_copy("We refer to 42 CFR Part 410 as proposed.", 12) + assert not is_rule_copy( + "DEPARTMENT OF HEALTH AND HUMAN SERVICES Centers for Medicare", 3 + ) + + +def test_form_groups_use_openings_and_skip_rule_copies(tmp_path, con, store): + letter = ( + "I am writing to urge CMS to protect home visits for homebound older adults. " + "These services keep patients out of the hospital and must be paid fairly. " + "Please finalize the proposed rule without cuts to the home visit codes. " + ) + keys = ["K1", "K2", "K3"] + # the matching excerpts differ; the openings are one form letter + selector = [(k, f"different excerpt {k} " * 20) for k in keys] + openings = {k: [letter + k] for k in keys} + rows, _ = identify( + engine_with(selector, openings=openings)[0], + store, + con, + HOME, + docket="D", + mirror=FakeMirror(), + ask=FakeAsk(None), + log=RunLog(tmp_path / "a.jsonl"), + ) + assert [(r.form_group, r.form_size) for r in rows] == [("K1", 3)] * 3 + # the same three, but whole-rule uploads: not a campaign + rows, _ = identify( + engine_with(selector, n_chunks=3882, openings=openings)[0], + store, + con, + HOME, + docket="D", + mirror=FakeMirror(), + ask=FakeAsk(None), + log=RunLog(tmp_path / "b.jsonl"), + ) + assert [(r.form_group, r.form_size) for r in rows] == [("", 0)] * 3 + + +def test_unreadable_mirror_at_regs_read_leaves_no_row(tmp_path, con, store): + path = tmp_path / "l.jsonl" + rows, counts = identify( + engine_with([("K1", "a")])[0], + store, + con, + HOME, + docket="D", + mirror=FakeMirror(fail=True), + ask=FakeAsk(_reply()), + log=RunLog(path), + ) + assert rows == [] and counts["blocked"] == 1 and counts["pending"] == 0 + assert not path.exists() + + +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 + assert rows == [] and counts["blocked"] == 2 and counts["done"] == 0 + 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) + ask = FakeAsk(None) + _, counts = identify(engine_with([("K1", "a")])[0], store, con, HOME, ask=ask, **kw) + assert counts["failed"] == 1 + _, counts = identify(engine_with([("K1", "a")])[0], store, con, HOME, ask=ask, **kw) + assert counts["failed_pending"] == 1 and len(ask.calls) == 1 + ask.reply = _reply(org_type="payer") + rows, counts = identify( + engine_with([("K1", "a")])[0], + store, + con, + HOME, + ask=ask, + retry_failed=True, + **kw, + ) + assert counts["done"] == 1 and rows[0].org_type == "payer" + + +def test_government_and_other_categories_defer_to_the_model(): + for cat in CATEGORY_MAP: + assert not cat.startswith( + ("Government", "Federal Government", "Other", "Academic", "Attorney") + ) + assert "Government - Federal" not in CATEGORY_MAP + assert "other" not in CATEGORY_MAP.values()