Files
stack/tests/llm/test_policy_live.py

274 lines
8.7 KiB
Python

"""Live acceptance of the policy API against the real replica and bib (lex S1
Task 4). Skipped only when the data files are absent; with the data present
every check must pass."""
from __future__ import annotations
import json
import re
from pathlib import Path
import duckdb
import pytest
ROOT = Path(__file__).resolve().parents[2]
REPLICA = ROOT / "data" / "replica" / "aco.ro.duckdb"
BIB = ROOT / "data" / "bib.sqlite"
pytestmark = pytest.mark.skipif(
not (REPLICA.exists() and BIB.exists()), reason="live replica / bib not present"
)
FAMILY = "HOME-VISITS"
VIEW_SECTIONS = ("header", "timeline", "valuation", "payment", "politics")
@pytest.fixture(scope="module", autouse=True)
def _restore_registry():
"""Opening the live replica loads its 8,662-family registry into
``pfs.families`` (and caches the handle); put both back afterwards so
neighbouring tests see the registry they expect."""
from llm import evidence
from pfs import families
saved = (
dict(families.FAMILIES),
families._PHRASE_RE,
families._PHRASE_INDEX,
families._CODE_INDEX,
)
prior = evidence._REPLICA
yield
with families._REGISTRY_LOCK:
families.FAMILIES.clear()
families.FAMILIES.update(saved[0])
(
families._PHRASE_RE,
families._PHRASE_INDEX,
families._CODE_INDEX,
) = saved[1:]
if evidence._REPLICA is not prior:
if evidence._REPLICA is not None:
evidence._REPLICA[2].close()
evidence._REPLICA = prior
@pytest.fixture(scope="module")
def cfg():
from llm import config
return config.load()
@pytest.fixture(scope="module")
def bib():
from bib.store import Store
return lambda: Store(str(BIB))
@pytest.fixture(scope="module")
def slices(cfg, bib):
from llm import policy
from llm.policy_slices import SECTIONS
policy.clear_cache()
return {s: policy.load_slice(cfg, FAMILY, s, bib=bib) for s in SECTIONS}
@pytest.fixture(scope="module")
def dossier(cfg):
from llm import evidence
from pfs.dossier import read_dossier
cur = evidence._connect(evidence._replica_path(cfg)).cursor()
try:
d = read_dossier(cur, FAMILY)
finally:
cur.close()
assert d is not None
return d
def test_live_every_fact_served_in_home_view(slices, dossier):
from llm.policy_slices import SECTION_OF_VIEW
ids = {f["id"] for f in slices["facts"]["facts"]}
assert ids == set(dossier.facts)
for f in slices["facts"]["facts"]:
section = SECTION_OF_VIEW[f["view"]]
assert f["id"] in slices[section]["facts"], (f["id"], f["view"])
def _cites(slices):
for sect in VIEW_SECTIONS:
for f in slices[sect]["facts"].values():
yield f["id"], f["cite"]
for c in f["also"]:
yield f["id"], c
def test_live_citations_resolve(slices, bib):
store = bib()
con = store._con()
n = 0
for fid, c in _cites(slices):
n += 1
url = c["url"]
if not url:
assert c["kind"] == "cpt_book" and c["locator"], (fid, c["kind"])
continue
assert url.startswith("https://") and not re.search(r"\s", url), (fid, url)
m = re.search(r"#p-(\d+)$", url)
if c["kind"] == "fr_para" and m:
row = con.execute(
"SELECT 1 FROM fr_anchors WHERE item_key = ? AND p_id = ?",
(c["item_key"], int(m.group(1))),
).fetchone()
assert row is not None, (fid, c["item_key"], m.group(1))
assert n > 0
@pytest.fixture(scope="session")
def ama_index():
"""8-word runs of the licensed CPT text on file: code descriptor, stem,
tail and elements, plus section guidelines. Built once per session."""
from market.edgar import AmaIndex
# SELECT DISTINCT: the runs are the same, far fewer rows to tokenize
con = duckdb.connect(str(REPLICA), read_only=True)
try:
texts = [
t
for (t,) in con.execute(
"SELECT DISTINCT t FROM ("
"SELECT descriptor AS t FROM pfs.cpt_code UNION ALL "
"SELECT stem FROM pfs.cpt_code UNION ALL "
"SELECT tail FROM pfs.cpt_code UNION ALL "
"SELECT unnest(elements) FROM pfs.cpt_code UNION ALL "
"SELECT guideline FROM pfs.cpt_section)"
).fetchall()
if t
]
finally:
con.close()
assert texts, "pfs.cpt_code is empty; nothing to guard against"
# AmaIndex.of builds the runs; a plain frozenset copy is what the checks
# intersect with, because set.isdisjoint on the frozenset *subclass* takes
# a slow generic path (about 60 ms per call against 181k runs).
return frozenset(AmaIndex.of(texts))
def _strings(x):
if isinstance(x, str):
yield x
elif isinstance(x, dict):
for v in x.values():
yield from _strings(v)
elif isinstance(x, list):
for v in x:
yield from _strings(v)
#: A list of code numbers ("99324, 99325, ... 99336") is a run of 8 words to
#: the tokenizer and also appears in the CPT code tables as a bare list. It is
#: not descriptor text, so text is split at code numbers and each segment of
#: prose is checked on its own (a run of words never spans a code number).
CODE_NUMBER = re.compile(r"\b(?:\d{4}[0-9FTU]|[A-Z]\d{4})\b")
def _prose_segments(text):
return CODE_NUMBER.split(text)
def test_live_no_eight_word_cpt_runs(cfg, slices, ama_index):
"""No served string shares an 8-word run with licensed CPT text."""
from llm import policy
from market.edgar import _WORD
def shares_run(text, n=8): # same tokenization as market.edgar.shares_ama_run
w = _WORD.findall(text.lower())
return not {tuple(w[i : i + n]) for i in range(len(w) - n + 1)}.isdisjoint(
ama_index
)
served = {**slices, "contents": policy.load_contents(cfg)}
hits = []
for name, body in served.items():
for text in _strings(body):
if any(shares_run(seg) for seg in _prose_segments(text)):
hits.append(name)
break
assert not hits, f"8-word CPT run shared in slices {hits}"
def test_live_no_cpt_descriptor_text(cfg, slices, dossier, bib):
from llm import policy
codes = sorted({r["code"] for r in slices["payment"]["rows"]})
con = duckdb.connect(str(REPLICA), read_only=True)
try:
rows = []
for table in ("pfs.rvu", "pfs.rvu_proposed"):
rows += con.execute(
f"SELECT DISTINCT hcpcs, description FROM {table} "
"WHERE hcpcs IN (SELECT unnest(?::VARCHAR[])) "
"AND length(description) >= 10",
[codes],
).fetchall()
finally:
con.close()
assert rows, "no descriptors found to guard against"
contents = policy.load_contents(cfg)
blob = re.sub(
r"\s+", " ", json.dumps([slices, contents], ensure_ascii=False)
).casefold()
bad = sorted(
{code for code, text in rows if re.sub(r"\s+", " ", text).casefold() in blob}
)
assert not bad, f"descriptor text served for codes {bad}"
def test_live_politics_counts_carry_accuracy(slices):
from llm.policy_slices import ACCURACY_MARK
pol = slices["politics"]
assert pol["panels"]
for p in pol["panels"]:
assert ACCURACY_MARK in p["accuracy"], p["docket"]
splits = [f for f in pol["facts"].values() if f["kind"] == "stance_split"]
assert splits
for f in splits:
assert ACCURACY_MARK in f["text"] + f.get("accuracy", ""), f["id"]
def test_live_sources_urls_well_formed(slices):
for doc in slices["sources"]["documents"]:
for u in (doc["url"], doc["viewer_url"], *(c["url"] for c in doc["cites"])):
if u:
assert u.startswith("https://") and not re.search(r"\s", u), doc["key"]
if not doc["url"]:
assert doc["group"] == "Books (licensed)", doc["key"]
for c in doc["cites"]:
if not c["url"]:
assert doc["group"] == "Books (licensed)" and c["locator"], doc["key"]
def test_live_review_items_all_served(slices, dossier):
assert len(slices["header"]["review"]) == len(dossier.review) > 0
def test_live_sources_and_contents_shape(slices, cfg):
from llm import policy
s = slices["sources"]
assert s["documents"] and sum(s["counts"].values()) == len(s["documents"])
for doc in s["documents"]:
if doc["group"] == "Books (licensed)":
assert doc["url"] == "" and doc["viewer_url"] == ""
if doc["viewer_url"]:
assert doc["status"] == "full text on file"
c = policy.load_contents(cfg)
assert FAMILY in {e["family"] for e in c["families"]}
assert c["machine"] is None or c["machine"]["derived"] > 0