diff --git a/src/cli/pfs.py b/src/cli/pfs.py index 3bcc28b..4d1b983 100644 --- a/src/cli/pfs.py +++ b/src/cli/pfs.py @@ -1294,6 +1294,6 @@ def commenters( f"{counts['pending']} comments not yet identified; rerun to resume" ) with _batch() as bcon: - n = write_commenters(bcon, rows) + n = write_commenters(bcon, rows, docket=docket) typer.echo(f"wrote {n} commenters") _publish() diff --git a/src/pfs/codetables.py b/src/pfs/codetables.py index 3526e22..a4c0c06 100644 --- a/src/pfs/codetables.py +++ b/src/pfs/codetables.py @@ -918,8 +918,15 @@ def read_cms_summaries(con: Any, family: str) -> list[CmsSummaryRow]: return [CmsSummaryRow(*r) for r in rows] -def write_commenters(con: Any, rows: Sequence[CommenterRow]) -> int: +def write_commenters( + con: Any, rows: Sequence[CommenterRow], *, docket: str = "" +) -> int: + """Replace the rows' items. With *docket*, first drop every stored row of + that docket: a rerun that no longer selects an item (R54) must not leave + its old row behind.""" ensure_tables(con) + if docket: + con.execute("DELETE FROM pfs.commenter WHERE docket = ?", [docket]) if not rows: return 0 con.executemany( diff --git a/src/pfs/commenters.py b/src/pfs/commenters.py index 4cd0238..bdc3438 100644 --- a/src/pfs/commenters.py +++ b/src/pfs/commenters.py @@ -20,12 +20,14 @@ 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 @@ -33,7 +35,7 @@ from pfs.codetables import CommenterRow from pfs.runlog import RunLog, input_hash, run_units TASK = "commenters" -IDENTITY_PROMPT_VERSION = "identity-v2" +IDENTITY_PROMPT_VERSION = "identity-v4" ORG_TYPES = ( "specialty_society", "health_system", @@ -127,12 +129,27 @@ class MirrorUnavailable(Exception): 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: - try: - data = mirror.get_json(docket, comment_id) - attrs = data["data"]["attributes"] - except Exception as exc: # noqa: BLE001 - any read problem fails closed - raise MirrorUnavailable(type(exc).__name__) from None + 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 @@ -195,9 +212,12 @@ _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, payer, " - "patient_group, individual_clinician (a single physician or other clinician), " - "individual (a patient or member of the public), other, or unknown. " + "(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." @@ -265,23 +285,80 @@ def form_groups(texts: Mapping[str, str]) -> dict[str, tuple[str, int]]: # ── items ──────────────────────────────────────────────────────────── -def _items_sql(with_phrases: bool) -> Any: +_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, document FROM ( " - "SELECT e.cmetadata->>'item_key' AS item_key, e.document AS document, " - "COALESCE(NULLIF(e.cmetadata->>'seq', '')::int, 0) AS seq, " - "row_number() OVER (PARTITION BY e.cmetadata->>'item_key' " - "ORDER BY COALESCE(NULLIF(e.cmetadata->>'seq', '')::int, 0) ASC) AS rn " + "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"AND ({code_or_family_predicate('e')}{phrase}) " - ") t WHERE rn <= :n_chunks ORDER BY item_key, seq" + "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], @@ -291,94 +368,64 @@ def family_comment_items( 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: the - lowest-``seq`` matching chunks (up to 3) joined, at most 3,000 - characters.""" + 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, - "n_chunks": _ITEM_CHUNKS, } if phrases: params["phrase_re"] = "|".join(re.escape(p) for p in phrases) with engine.begin() as conn: - rows = conn.execute(_items_sql(bool(phrases)), params).fetchall() - parts: dict[str, list[str]] = {} - for item_key, doc in rows: - parts.setdefault(item_key, []).append(doc or "") - 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) + 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: chunk 0 (the inline comment), then the first - attachment chunks in seq order, at most 3,000 characters.""" + """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 - 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" - ) + """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( - sql, + _chunks_sql(matched=False), { "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) + own, uploaded = _own_chunks(rows) out = {} - for k, parts in docs.items(): - joined = "\n".join(parts) + 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], totals[k], is_rule_copy(joined, totals[k])) + out[k] = Opening(body[:_ITEM_CHARS], k in uploaded) return out @@ -449,21 +496,21 @@ def identify( retry_failed: bool = False, progress: Callable[[str, str], None] | None = None, ) -> tuple[list[CommenterRow], dict[str, int]]: - """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).""" + """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 ) - 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) + keys = [k for k, _ in items] + cids, regs = regs_for(store, mirror, docket, 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] + blocked = {k for k in keys if k not in regs} specialties = specialty_vocab(con) model = getattr(ask, "model", "unknown") @@ -482,10 +529,11 @@ def identify( 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 keys: + for k in hashes: if limit and calls >= limit: break try: @@ -499,25 +547,38 @@ def identify( ) except MirrorUnavailable: # the name guard could not read the mirror: fail closed - blocked += 1 - hashes.pop(k) + blocked.add(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({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", + ) + ) + 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) - gid, size = forms.get(k, ("", 0)) rows.append( CommenterRow( item_key=k, @@ -535,4 +596,4 @@ def identify( ), ) ) - return rows, {**counts, "pending": pending, "blocked": blocked} + return rows, {**counts, "pending": pending, "blocked": len(blocked)} diff --git a/tests/pfs/test_commenters.py b/tests/pfs/test_commenters.py index 6e34786..067fdbf 100644 --- a/tests/pfs/test_commenters.py +++ b/tests/pfs/test_commenters.py @@ -6,6 +6,7 @@ from types import SimpleNamespace from unittest.mock import MagicMock import duckdb +import httpx import pytest from bib.item import Source @@ -21,12 +22,10 @@ from pfs.commenters import ( IDENTITY_PROMPT_VERSION, ORG_TYPES, MirrorUnavailable, - Opening, RegsFields, family_comment_items, form_groups, identify, - is_rule_copy, item_openings, letterhead_identity, regs_fields, @@ -64,23 +63,35 @@ class FakeAsk: return self.reply -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.""" +def engine_with(rows, openings=None, extra=()): + """Fake pgvector engine that emulates the two chunk queries. *rows* are + the family-matching ``(item_key, text)`` chunks (late in the comment); + *openings* ``{item_key: [chunk texts]}`` are non-matching opening chunks of + the inline comment; *extra* are further ``(item, section, seq, doc, + matched)`` chunks. The query that binds ``keys`` is the openings query.""" engine = MagicMock() conn = engine.begin.return_value.__enter__.return_value - opened = openings if openings is not None else {k: [t] for k, t in rows} + chunks = [(k, "Inline comment", 100, t, True) for k, t in rows] + for k, parts in (openings or {}).items(): + chunks += [(k, "Inline comment", i, t, False) for i, t in enumerate(parts)] + chunks += list(extra) def execute(sql, params): - result = MagicMock() + by_sec = {} + for c in sorted(chunks, key=lambda c: c[2]): + by_sec.setdefault((c[0], c[1]), []).append(c) 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, []) - ] + scope = set(params["keys"]) else: - result.fetchall.return_value = rows + scope = {c[0] for c in chunks if c[4]} + out = [] + for secs in by_sec.values(): + for rs, c in enumerate(secs, 1): + matched = c[4] and "keys" not in params + if c[0] in scope and (rs <= 6 or matched): + out.append((c[0], c[1], c[2], c[3], rs, matched)) + result = MagicMock() + result.fetchall.return_value = sorted(out, key=lambda r: (r[0], r[2])) return result conn.execute.side_effect = execute @@ -432,7 +443,8 @@ def test_specialty_vocab(con): def test_family_comment_items_joins_chunks_and_caps(): engine, conn = engine_with( - [("B", "b1"), ("A", "a1"), ("A", "a2"), ("C", "x" * 4000), ("D", None)] + [("B", "b1"), ("A", "a1"), ("C", "x" * 4000), ("D", None)], + extra=[("A", "Inline comment", 101, "a2", True)], ) out = family_comment_items( engine, ["99341"], "home-visits", ["Home (or) residence"], docket="D1" @@ -461,6 +473,11 @@ def test_commenter_table_roundtrip(con): assert [r.item_key for r in read_commenters(con, ["K2"])] == ["K2"] assert read_commenters(con, []) == [] assert write_commenters(con, []) == 0 + # a docket rewrite drops items the rerun no longer selects + assert write_commenters(con, [row("K3")], docket="D") == 1 + assert [r.item_key for r in read_commenters(con)] == ["K3"] + assert write_commenters(con, [row("K4", d="E")], docket="E") == 1 + assert [r.item_key for r in read_commenters(con)] == ["K3", "K4"] def test_category_map_values_are_org_types_and_ambiguous_unmapped(): @@ -491,7 +508,10 @@ class FlakyMirror(FakeMirror): def test_identity_input_is_the_opening_not_the_matching_chunk(tmp_path, con, store): - opening = {"K1": ["## Inline comment", "tMED Coalition writes.", "second chunk"]} + opening = { + "K1": ["## Inline comment", "tMED Coalition writes.", "second chunk"] + + [f"filler {i}" for i in range(4)] + } engine, _ = engine_with( [("K1", "late matching chunk about 99341")], openings=opening ) @@ -507,43 +527,106 @@ def test_identity_input_is_the_opening_not_the_matching_chunk(tmp_path, con, sto log=RunLog(tmp_path / "l.jsonl"), ) sent = ask.calls[0][1] - assert sent == "tMED Coalition writes.\nsecond chunk" + 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-v2" + assert IDENTITY_PROMPT_VERSION == "identity-v4" -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" +RULE_HDR = ( + "## attachment_1.pdf DEPARTMENT OF HEALTH AND HUMAN SERVICES Centers for " + "Medicare & Medicaid Services 42 CFR Parts 405, 410, 411" +) + + +def rule_upload(key, n=20, mention="99341 home visits"): + """An attachment that is a copy of the rule: the FR header, then pages + naming the code.""" + out = [(key, "attachment_1.pdf", 0, "## attachment_1.pdf", False)] + out.append((key, "attachment_1.pdf", 1, RULE_HDR, False)) + out += [ + (key, "attachment_1.pdf", 2 + i, f"rule page {i} {mention}", True) + for i in range(n) + ] + return out + + +def test_item_openings_headers_cap_and_rule_upload_left_out(): 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], - }, + openings={"A": ["## Inline comment", "x" * 4000], "B": ["a letter"]}, + extra=rule_upload("B") + rule_upload("C"), ) 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 + assert out["A"].text == "x" * 3000 and not out["A"].rule_copy + assert out["B"].text == "a letter" and out["B"].rule_copy + assert "C" not in out and "Z" not in out # only the rule: nothing of its own 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_rule_copy_item_whose_inline_text_does_not_match_is_dropped( + tmp_path, con, store +): + engine, _ = engine_with( + [("K1", "a letter naming 99341")], + openings={"K2": ["A psychologists' form letter about medication."]}, + extra=rule_upload("K2"), ) + rows, counts = identify( + engine, + store, + con, + HOME, + docket="D", + mirror=FakeMirror(), + ask=FakeAsk(_reply()), + log=RunLog(tmp_path / "l.jsonl"), + ) + assert [r.item_key for r in rows] == ["K1"] + assert family_comment_items(engine, ["99341"], "H", [], docket="D") == [ + ("K1", "a letter naming 99341") + ] -def test_form_groups_use_openings_and_skip_rule_copies(tmp_path, con, store): +def test_rule_copy_item_whose_inline_text_names_the_code_is_kept_without_the_rule( + tmp_path, con, store +): + engine, _ = engine_with( + [("K2", "We support 99341 payment.")], + openings={"K2": ["tMED Coalition writes."]}, + extra=rule_upload("K2"), + ) + ask = FakeAsk(_reply(org_type="other")) + rows, _ = identify( + engine, + store, + con, + HOME, + docket="D", + mirror=FakeMirror(), + ask=ask, + log=RunLog(tmp_path / "l.jsonl"), + ) + assert [r.item_key for r in rows] == ["K2"] + sent = ask.calls[0][1] + assert "tMED Coalition writes." in sent and "DEPARTMENT" not in sent + assert "rule page" not in sent + # selection text carries only the inline match, never a rule page + assert family_comment_items(engine, ["99341"], "H", [], docket="D") == [ + ("K2", "We support 99341 payment.") + ] + + +def test_header_must_be_in_the_attachment_opening_not_a_late_citation(): + late = [("A", "attachment_1.pdf", i, "page", False) for i in range(4)] + late.append(("A", "attachment_1.pdf", 4, RULE_HDR, False)) + engine, _ = engine_with([], extra=late) + assert item_openings(engine, ["A"], docket="D")["A"].rule_copy is False + engine, _ = engine_with([], extra=[("B", "x", 0, "no section header here", False)]) + assert item_openings(engine, ["B"], docket="D")["B"].rule_copy is False + + +def test_form_groups_use_openings(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. " @@ -564,34 +647,84 @@ def test_form_groups_use_openings_and_skip_rule_copies(tmp_path, con, store): 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"), + + +def _status_error(code): + req = httpx.Request("GET", "https://x") + return httpx.HTTPStatusError( + "e", request=req, response=httpx.Response(code, request=req) ) - 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): +class SeqMirror: + """Raises each queued exception in turn, then serves *attrs*.""" + + def __init__(self, errors, attrs=None): + self.errors = list(errors) + self.attrs = attrs or {"category": "Individual"} + self.calls = 0 + + def get_json(self, docket, cid): + self.calls += 1 + if self.errors: + raise self.errors.pop(0) + return {"data": {"attributes": self.attrs}} + + +@pytest.fixture(autouse=True) +def no_sleep(monkeypatch): + monkeypatch.setattr("pfs.commenters.time.sleep", lambda s: None) + + +def test_mirror_retries_network_errors_and_5xx_twice(): + for errs in ( + [httpx.ConnectError("x"), httpx.ReadTimeout("y")], + [_status_error(503), _status_error(500)], + ): + m = SeqMirror(errs) + assert regs_fields(m, "D", "c").category == "Individual" and m.calls == 3 + m = SeqMirror([httpx.ConnectError("x")] * 3) + with pytest.raises(MirrorUnavailable): + regs_fields(m, "D", "c") + assert m.calls == 3 + # a 404 or a parse problem is not retried + m = SeqMirror([_status_error(404)]) + with pytest.raises(MirrorUnavailable): + regs_fields(m, "D", "c") + assert m.calls == 1 + + +def test_blocked_item_becomes_unknown_row_without_model_call_then_is_replaced( + tmp_path, con, store +): path = tmp_path / "l.jsonl" + ask = FakeAsk(_reply(org_type="payer")) + kw = dict(docket="D", ask=ask, log=RunLog(path)) rows, counts = identify( engine_with([("K1", "a")])[0], store, con, HOME, - docket="D", mirror=FakeMirror(fail=True), - ask=FakeAsk(_reply()), - log=RunLog(path), + **kw, ) - assert rows == [] and counts["blocked"] == 1 and counts["pending"] == 0 - assert not path.exists() + assert counts["blocked"] == 1 and counts["pending"] == 0 and ask.calls == [] + r = rows[0] + assert (r.item_key, r.org_name, r.org_type, r.specialty) == ( + "K1", + "", + "unknown", + "", + ) + assert r.extractor == "blocked:mirror" and not path.exists() + write_commenters(con, rows) + # the mirror reads on a later run: the row is replaced by the real one + rows, counts = identify( + engine_with([("K1", "a")])[0], store, con, HOME, mirror=FakeMirror(), **kw + ) + assert counts["blocked"] == 0 and rows[0].org_type == "payer" + write_commenters(con, rows) + 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): @@ -614,8 +747,12 @@ def test_name_guard_fails_closed_when_mirror_read_fails(tmp_path, con, store): 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 + # 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() == "" @@ -647,3 +784,14 @@ def test_government_and_other_categories_defer_to_the_model(): ) assert "Government - Federal" not in CATEGORY_MAP assert "other" not in CATEGORY_MAP.values() + + +def test_prompt_defines_vendor_and_sends_trade_associations_to_other(): + ask = FakeAsk(_reply()) + letterhead_identity("t", ask, specialties=()) + system = ask.calls[0][0] + assert ( + "vendor (only a for-profit company" in system + and "never an association" in system + ) + assert "other (including trade associations, coalitions" in system