Files
stack/src/pfs/extract.py
kert e14f12e18e perf(pfs,cli): elements --all-payable in one inverted pass, not two fr_anchors scans per code (refs #698)
`stack pfs elements --all-payable` targeted ~8.7k A/R/T codes and ran two
full scans of the unindexed 193k-row `fr_anchors` table per code — the
`LIKE '%CODE%'` descriptor-stem query plus a follow-up query per stem —
on top of three per-code replica queries. ~15-25 minutes of SQL before
the first model call, which is why the command had never been run end to
end.

Invert the loop, the way `lineage --all-payable` already does:

- `pfs.descriptors.descriptor_runs_bucketed` streams `fr_anchors` once in
  `(item_key, p_id)` order — the order the per-code follow-up query walks
  — keeping each stem's run open until a paragraph fails
  `is_element_paragraph`, closes with a parenthesis, or hits the element
  cap. Stems are found with one `_stem_pattern_any` regex over all target
  codes instead of one compiled pattern per code.
- `hcpcs_long_descriptions` / `rvu_descriptions_bucketed` /
  `_cpt_elements_bucketed` fetch every target code's row in one query
  each, keeping the same newest-row picks as `QUALIFY row_number()`.
- `pfs.extract._assemble` becomes the single home of the precedence rules
  (FR > CPT > HCPCS/RVU with `confirmed_by` cross-checks), shared by the
  per-code `extract_code` and the new `extract_codes`, so the two paths
  cannot drift.

`uv run stack pfs elements --all-payable --no-llm --dry-run` now finishes
in ~12s for 8,689 codes, and all 17 hand-family codes extract identical
rows and reviews on the live corpus. Drop the "experimental" wording and
the "~20 min of SQL" warning; `_codes_for` keeps its signature and still
logs the target count under `warn_slow`.

No index on `fr_anchors.text`: the inverted pass never does a text LIKE,
so an FTS5/trigram index would be write-path cost for nothing.
2026-09-11 18:16:56 -04:00

314 lines
12 KiB
Python

"""Element extraction for one code: deterministic parse first, the local
model second (closed vocabulary only), a review queue for the rest.
``extract_run`` works on an FR descriptor run (stem + element
paragraphs); ``extract_text`` on a flat descriptor (HCPCS long
description, RVU short description); ``extract_code`` gathers every
source for a code — FR, then the newest CPT codebook edition's own
``pfs.cpt_code`` row (stem + tail, then each required-elements list
item), then HCPCS, then RVU — with FR rows winning over CPT and CPT
winning over HCPCS/RVU on a duplicate ``(type, value, detail)``. The
losing source isn't just dropped: it's recorded on the winning row's
``confirmed_by`` as a ``source:item_key`` token (#703) — an independent
transcription of the same element cross-checks the winner without
doubling the row count. ``extract_codes`` is ``extract_code`` for a whole
target list with the source lookups inverted — one pass over the corpus
rather than one per code (#698). No I/O here beyond what the caller hands
in.
"""
from __future__ import annotations
from dataclasses import dataclass, replace
from typing import Any, Callable, Sequence
from pfs.codetables import ElementRow, ReviewRow, is_missing_table_error
from pfs.descriptors import (
IN_TARGETS,
DescriptorRun,
Para,
descriptor_runs,
descriptor_runs_bucketed,
hcpcs_long_description,
hcpcs_long_descriptions,
rvu_descriptions,
rvu_descriptions_bucketed,
)
from pfs.elements import VOCAB, Element, ElementType, parse_descriptor
Classifier = Callable[[str, Sequence[str]], "str | None"]
#: Types the classifier may assign to a free-standing element line.
_CLASSIFIABLE = (ElementType.ACTIVITY, ElementType.POPULATION, ElementType.BILLING)
_CHOICES: tuple[str, ...] = tuple(v for t in _CLASSIFIABLE for v in VOCAB[t])
_TYPE_OF: dict[str, ElementType] = {v: t for t in _CLASSIFIABLE for v in VOCAB[t]}
@dataclass(frozen=True)
class Extraction:
code: str
rows: tuple[ElementRow, ...]
reviews: tuple[ReviewRow, ...]
def _merge_or_confirm(
merged: dict[tuple[str, str, str], ElementRow], r: ElementRow
) -> None:
"""Add *r* to *merged*, keyed by ``(type, value, detail)``. A first
sighting of a key is just kept. A later row for a key already held by
a *different* source (#703) doesn't replace the winner — FR still
beats CPT, CPT still beats HCPCS/RVU, and the row count doesn't grow
— it cross-checks it: ``r``'s ``source:item_key`` is appended to the
kept row's ``confirmed_by`` (deduped, so re-running the same source
twice, or a code with more than one CPT hit, doesn't repeat a token).
A later row from the *same* source as the one already kept is a
same-source duplicate (e.g. two FR rule years naming the same
element), not a second, independent source — it's dropped exactly as
before, uncounted as confirmation."""
key = (r.type, r.value, r.detail)
existing = merged.get(key)
if existing is None:
merged[key] = r
return
if r.source == existing.source:
return
token = f"{r.source}:{r.item_key}"
tokens = [t for t in existing.confirmed_by.split(",") if t]
if token in tokens:
return
tokens.append(token)
merged[key] = replace(existing, confirmed_by=",".join(tokens))
def _row(code: str, e: Element, para: Para, *, year: int, source: str) -> ElementRow:
return ElementRow(
code,
year,
e.type.value,
e.value,
e.detail,
para.text,
para.item_key,
para.p_id,
para.page,
source,
)
def extract_run(
run: DescriptorRun, *, classify: Classifier | None = None
) -> Extraction:
rows: dict[Element, ElementRow] = {}
reviews: list[ReviewRow] = []
# 1. deterministic, per element paragraph (anchors to that paragraph)
for para in run.elements:
found = parse_descriptor(para.text)
for e in found:
rows.setdefault(e, _row(run.code, e, para, year=run.rule_year, source="fr"))
if found:
continue
# 2. classifier for lines nothing matched
choice = classify(para.text, _CHOICES) if classify else None
if choice is not None and choice in _TYPE_OF:
e = Element(_TYPE_OF[choice], choice)
rows.setdefault(e, _row(run.code, e, para, year=run.rule_year, source="fr"))
else:
reviews.append(
ReviewRow(run.code, para.text, "", "", para.item_key, para.p_id, "fr")
)
# 3. deterministic on the stem (and anything the whole text reveals)
for e in parse_descriptor(run.text):
rows.setdefault(e, _row(run.code, e, run.stem, year=run.rule_year, source="fr"))
ordered = sorted(rows.values(), key=lambda r: (r.type, r.value, r.detail))
return Extraction(run.code, tuple(ordered), tuple(reviews))
def extract_text(code: str, text: str, *, year: int, source: str) -> Extraction:
rows = [
ElementRow(code, year, e.type.value, e.value, e.detail, text, "", 0, 0, source)
for e in parse_descriptor(text)
]
return Extraction(code, tuple(rows), ())
def _cpt_row(
code: str, edition_year: int, item_key: str, e: Element, text: str
) -> ElementRow:
return ElementRow(
code, edition_year, e.type.value, e.value, e.detail, text, item_key, 0, 0, "cpt"
)
def _cpt_elements(
con: Any, code: str, *, classify: Classifier | None = None
) -> tuple[list[ElementRow], list[ReviewRow]]:
"""The newest CPT codebook edition's own row for *code*: one pass of
``parse_descriptor`` over ``stem + " " + tail`` (anchored to the
stem), then one pass per required-elements list item (each item's
trailing ``,``/``;`` stripped first) — an item nothing can place goes
to *classify* if given, else to the review queue. The ``parent``
code's stem/elements already apply to add-on rows (the CPT parser
inherits them onto the child's own ``pfs.cpt_code`` row), so nothing
extra is done here for add-ons. A replica with no ``pfs.cpt_code``
table yet (CPT ingestion hasn't run) is not a bug — it just yields no
CPT rows/reviews (I4, shared with the CLI's read-only paths via
``is_missing_table_error``)."""
try:
row = con.execute(
"SELECT edition_year, item_key, stem, elements, tail FROM pfs.cpt_code "
"WHERE code = ? ORDER BY edition_year DESC LIMIT 1",
[code],
).fetchone()
except Exception as exc:
if is_missing_table_error(exc):
return [], []
raise
if row is None:
return [], []
return _cpt_elements_of_row(code, row, classify=classify)
def _cpt_elements_of_row(
code: str,
row: Sequence[Any],
*,
classify: Classifier | None = None,
) -> tuple[list[ElementRow], list[ReviewRow]]:
"""The parsing half of ``_cpt_elements``, over one already-fetched
``(edition_year, item_key, stem, elements, tail)`` row, so the
per-code query and the bucketed one share it exactly."""
edition_year, item_key, stem, elements, tail = row
stem_text = (stem or "").strip()
tail_text = (tail or "").strip()
rows: list[ElementRow] = []
for e in parse_descriptor(f"{stem_text} {tail_text}".strip()):
rows.append(_cpt_row(code, edition_year, item_key, e, stem_text))
reviews: list[ReviewRow] = []
for raw in elements or ():
text = raw.strip()
if text.endswith((",", ";")):
text = text[:-1].strip()
if not text:
continue
found = parse_descriptor(text)
if found:
for e in found:
rows.append(_cpt_row(code, edition_year, item_key, e, text))
continue
choice = classify(text, _CHOICES) if classify else None
if choice is not None and choice in _TYPE_OF:
e = Element(_TYPE_OF[choice], choice)
rows.append(_cpt_row(code, edition_year, item_key, e, text))
else:
reviews.append(ReviewRow(code, text, "", "", item_key, 0, "cpt"))
return rows, reviews
def _cpt_elements_bucketed(
con: Any, codes: Sequence[str], *, classify: Classifier | None = None
) -> dict[str, tuple[list[ElementRow], list[ReviewRow]]]:
"""``_cpt_elements`` for every one of *codes* in one query — the same
newest-edition pick (the per-code ``ORDER BY edition_year DESC LIMIT
1``, expressed as a ``QUALIFY row_number()``) and the same
missing-``pfs.cpt_code`` tolerance (I4)."""
targets = sorted({c.upper() for c in codes})
if not targets:
return {}
try:
rows = con.execute(
"SELECT code, edition_year, item_key, stem, elements, tail "
f"FROM pfs.cpt_code WHERE code {IN_TARGETS} QUALIFY row_number() OVER "
"(PARTITION BY code ORDER BY edition_year DESC) = 1",
[targets],
).fetchall()
except Exception as exc:
if is_missing_table_error(exc):
return {}
raise
return {r[0]: _cpt_elements_of_row(r[0], r[1:], classify=classify) for r in rows}
def _assemble(
code: str,
runs: Sequence[DescriptorRun],
cpt: tuple[list[ElementRow], list[ReviewRow]],
long_desc: str,
years: Sequence[tuple[int, str, str]],
*,
classify: Classifier | None = None,
) -> Extraction:
"""Merge one code's already-fetched sources into an ``Extraction``.
The single home of the precedence rules (FR > CPT > HCPCS/RVU, the
loser recorded on the winner's ``confirmed_by``), shared by the
per-code ``extract_code`` and the bucketed ``extract_codes`` so the
two paths cannot drift apart (#698)."""
merged: dict[tuple[str, str, str], ElementRow] = {}
reviews: list[ReviewRow] = []
for run in runs:
x = extract_run(run, classify=classify)
for r in x.rows:
_merge_or_confirm(merged, r)
reviews.extend(x.reviews)
cpt_rows, cpt_reviews = cpt
for r in cpt_rows:
_merge_or_confirm(merged, r)
reviews.extend(cpt_reviews)
if long_desc:
y = years[-1][0] if years else 0
for r in extract_text(code, long_desc, year=y, source="hcpcs").rows:
_merge_or_confirm(merged, r)
for year, _status, desc in years:
for r in extract_text(code, desc, year=year, source="rvu").rows:
_merge_or_confirm(merged, r)
ordered = sorted(merged.values(), key=lambda r: (r.type, r.value, r.detail))
return Extraction(code, tuple(ordered), tuple(reviews))
def extract_code(
store: Any, con: Any, code: str, *, classify: Classifier | None = None
) -> Extraction:
"""All sources for *code*; FR rows win over CPT, and CPT wins over
HCPCS/RVU rows for the same element — each source contributes its own
year."""
code = code.upper()
return _assemble(
code,
descriptor_runs(store, code),
_cpt_elements(con, code, classify=classify),
hcpcs_long_description(con, code),
rvu_descriptions(con, code),
classify=classify,
)
def extract_codes(
store: Any, con: Any, codes: Sequence[str], *, classify: Classifier | None = None
) -> dict[str, Extraction]:
"""``extract_code`` for every one of *codes*, with the source lookups
inverted: ONE streaming pass over ``fr_anchors`` and ONE query each
over ``pfs.cpt_code``, ``terminology.hcpcs_level_2`` and ``pfs.rvu``,
instead of two unindexed ``fr_anchors`` scans plus three replica
queries per code (#698). ``extract_codes(store, con, [c])[c] ==
extract_code(store, con, c)``: the bucketed lookups select the same
rows per code, and ``_assemble`` does the merging for both paths.
Keyed in ``sorted(set(...))`` order, one entry per distinct code — a
code no source mentions still gets an empty ``Extraction``."""
targets = sorted({c.upper() for c in codes})
runs = descriptor_runs_bucketed(store, targets)
cpt = _cpt_elements_bucketed(con, targets, classify=classify)
long_descs = hcpcs_long_descriptions(con, targets)
years = rvu_descriptions_bucketed(con, targets)
return {
code: _assemble(
code,
runs.get(code, ()),
cpt.get(code, ([], [])),
long_descs.get(code, ""),
years.get(code, ()),
classify=classify,
)
for code in targets
}