Files
stack/tests/llm/test_dossier.py
kert a60baf2a84
Some checks failed
CI / lint (push) Successful in 1m16s
CI / notebooks-smoke (push) Successful in 2m0s
Deploy / changes (push) Successful in 15s
CI / test (push) Failing after 4m21s
Infra CI / zotero (push) Successful in 17s
Infra CI / notebooks (push) Successful in 1m4s
Infra CI / docs (push) Successful in 28s
Infra CI / api (push) Successful in 1m53s
Infra CI / bcda (push) Successful in 2m55s
Infra CI / llm (push) Successful in 1m42s
Infra CI / mc (push) Successful in 26s
Package Supply Chain / pkg-supply-chain (push) Successful in 2m42s
Deploy / notebooks (push) Has been skipped
Deploy / zotero (push) Has been skipped
Deploy / docs (push) Has been skipped
Deploy / api (push) Successful in 1m49s
Deploy / bcda (push) Successful in 2m9s
Deploy / mc (push) Has been skipped
Deploy / llm (push) Successful in 1m24s
Deploy / report (push) Successful in 17s
fix(llm): dossier prompt block is question-aware and compact — summary, timeline, matched facts, one stance unit; 35% budget share; default-years valuation prompt rows
2026-11-13 00:55:29 -05:00

402 lines
14 KiB
Python

"""llm.dossier — the family dossier as chat evidence (Task 15)."""
from __future__ import annotations
import logging
from dataclasses import replace
import duckdb
import pytest
from llm import evidence
from llm.config import LlmConfig
from llm.dossier import (
TIMELINE_FLOOR,
DossierEvidence,
dossier_evidence,
dossier_url,
match_facts,
question_years,
)
from pfs.cite import Cite
from pfs.codetables import ensure_tables
from pfs.dossier import Dossier, Fact, TimelineEvent, write_dossier
CFG = LlmConfig(
ollama_hosts=("http://h1:11434",),
embed_model="e",
instruct_model="c",
embed_dim=768,
build_ann_index=False,
pg_host="x",
pg_port=5432,
pg_db="llm",
pg_user="llm",
duckdb_replica="/nonexistent/aco.ro.duckdb",
)
ACC = (
"Preliminary model classification, measured on a held-out set the prompt "
"was never tuned on (20 hand-coded comments, 24 positions; CMS-2025-0304): "
"it finds 79% of hand-coded positions, and the direction is right for 74% "
"of those it finds."
)
def _fact(i, kind, text, year=2023, label=None, note="", codes=("99341",)):
return Fact(
id=f"F{i}",
kind=kind,
year=year,
codes=codes,
text=text,
values={},
cite=Cite("fr", label or f"L{i}", f"https://x/{i}"),
note=note,
)
def _dossier(extra=(), accuracy=ACC):
old = ("99324", "99325")
facts = [
_fact(1, "payment", "payment row"),
_fact(2, "round", "CMS finalized work RVU 1.0 for 99341 for CY2023."),
_fact(
3,
"event",
"99324 was deleted for CY2023.",
label="DEL23",
codes=old,
),
_fact(
4,
"stance_split",
"Of 3 CY2023 commenters we classified, 2 supported and 1 opposed. " + ACC,
),
_fact(5, "cms_summary", "CMS reported that commenters supported it."),
_fact(
6,
"seat",
"Jane Doe, MD (Acme Clinic) commented on the CY2023 rule.",
label="CMS-2022-0113-0001",
),
_fact(7, "round", "flagged paraphrase", note="model paraphrase, unreviewed"),
_fact(8, "stance_split", "Of 3 CY2018 commenters we classified, 3 supported."),
_fact(9, "finding", "a finding"),
# live-shaped: far more CY2008 rounds than any cap
*(
_fact(
100 + i,
"round",
f"For CY2008, CMS finalized work RVU {i} for 99326.",
year=2008,
codes=("99326",),
)
for i in range(40)
),
*extra,
]
tl = [
TimelineEvent(
2008,
"valuation",
("99326",),
"For CY2008, CMS finalized RVUs [F100].",
("F100",),
(),
(),
),
TimelineEvent(
2023,
"deletion",
old,
"99324 and 99325 were deleted for CY2023 [F3].",
("F3",),
(),
(),
),
]
return Dossier(
family="HOME-VISITS",
name="Home or Residence Services",
codes=("99341",),
status="active",
years_active="2008-",
summary="CMS finalized it [F2][F2] and deleted codes [F3].",
timeline=tl,
rounds=[],
payment=[],
utilization=[],
stakeholders=[],
governance=[],
sources={},
gaps=["RVU files before 2015 not yet loaded."],
facts={f.id: f for f in facts},
built_at="2026-11-12T00:00:00",
check_passed=True,
extractor="template",
review=[{"fact_id": "F9", "reason": "model extract, unreviewed"}],
stance_accuracy=accuracy,
)
@pytest.fixture
def replica(tmp_path, monkeypatch):
evidence._REPLICA = None
path = tmp_path / "aco.ro.duckdb"
con = duckdb.connect(str(path))
ensure_tables(con)
write_dossier(con, _dossier())
con.close()
monkeypatch.setenv("DOMAIN", "")
yield replace(CFG, duckdb_replica=str(path))
evidence._REPLICA = None
def test_dossier_evidence_for_home_visit_question(replica):
ev = dossier_evidence("how were home visits valued?", replica)
assert ev is not None
assert ev.family == "HOME-VISITS"
assert ev.name == "Home or Residence Services"
assert ev.url == "https://lex.fhirworx.io/?family=HOME-VISITS#dossier"
assert ev.max_prompt_rows == 30
assert len(ev.facts) == 49
assert len(ev.timeline) == 2
assert ev.gaps == ("RVU files before 2015 not yet loaded.",)
def test_none_without_dossier_row(tmp_path):
evidence._REPLICA = None
path = tmp_path / "empty.duckdb"
con = duckdb.connect(str(path))
ensure_tables(con)
con.close()
cfg = replace(CFG, duckdb_replica=str(path))
assert dossier_evidence("how were home visits valued?", cfg) is None
evidence._REPLICA = None
def test_none_without_family_or_replica(replica):
assert (
dossier_evidence("what did commenters say about telehealth?", replica) is None
)
assert dossier_evidence("home visits?", CFG) is None # replica file missing
def test_unreadable_replica_is_logged_not_raised(replica, monkeypatch, caplog):
def boom(_p):
raise OSError("locked")
monkeypatch.setattr(evidence, "_connect", boom)
with caplog.at_level(logging.WARNING, logger="llm.dossier"):
assert dossier_evidence("home visits?", replica) is None
assert "dossier evidence skipped" in caplog.text
def test_first_family_curated_before_derived(replica, monkeypatch):
from types import SimpleNamespace
import llm.dossier as mod
monkeypatch.setattr(
mod,
"detect_codes",
lambda q: SimpleNamespace(
families=("AAA-DERIVED", "HOME-VISITS", "ZZZ"), explicit=(), codes=()
),
)
monkeypatch.setattr(mod, "CURATED_FAMILIES", {"HOME-VISITS": 1})
seen = []
real = mod.read_dossier
def spy(cur, fam):
seen.append(fam)
return real(cur, fam)
monkeypatch.setattr(mod, "read_dossier", spy)
ev = dossier_evidence("q", replica)
assert ev.family == "HOME-VISITS" and seen[0] == "HOME-VISITS"
def test_dossier_payload_shape_and_summary_labels(replica):
p = dossier_evidence("home visits?", replica).payload()
assert p["type"] == "dossier"
assert p["family"] == "HOME-VISITS"
assert p["url"] == "https://lex.fhirworx.io/?family=HOME-VISITS#dossier"
# [F#] became the facts' labels; the doubled cite collapsed
assert p["summary"] == "CMS finalized it [L2] and deleted codes [DEL23]."
assert {"label", "text", "url", "year", "kind", "review"} == set(p["facts"][0])
assert p["gaps"] == ["RVU files before 2015 not yet loaded."]
def test_payload_carries_only_cited_and_selected_facts(replica):
ev = dossier_evidence("home visits?", replica)
p = ev.payload()
labels = {f["label"] for f in p["facts"]}
assert {"L2", "DEL23", "L100"} <= labels # summary + timeline cites
assert "L1" not in labels # payment rows stay on the page
assert len(p["facts"]) < len(ev.facts)
assert all(f["review"] is False for f in p["facts"])
# a flagged fact cited by the timeline travels flagged
ev2 = replace(ev, flagged=("F3",))
assert [f["review"] for f in ev2.payload()["facts"] if f["label"] == "DEL23"] == [
True
]
def test_payload_unknown_fact_tag_kept(replica):
ev = dossier_evidence("home visits?", replica)
ev = replace(ev, summary="see [F999].")
assert ev.payload()["summary"] == "see [F999]."
def test_payload_names_come_from_own_records(replica):
"""Commenters are named as the public record names them (user ruling)."""
p = dossier_evidence("home visits?", replica).payload()
seat = [f for f in p["facts"] if f["kind"] == "seat"][0]
assert "Jane Doe, MD" in seat["text"]
assert seat["label"] == "CMS-2022-0113-0001"
def _ev(replica_cfg, question):
return dossier_evidence(question, replica_cfg)
def test_prompt_block_order_and_labels(replica):
ev = _ev(replica, "When were domiciliary visit codes 99324 and 99325 deleted?")
block = ev.prompt_block()
lines = block.splitlines()
assert lines[0] == (
"Dossier — cited facts about the Home or Residence Services family "
"(authoritative for its history, valuation rounds and who commented). "
"Each line ends with the label to copy:"
)
assert lines[1] == ("Summary: CMS finalized it [L2] and deleted codes [DEL23].")
# timeline, newest first, in the dossier's own prose with labels
assert lines[2] == "CY2023: 99324 and 99325 were deleted for CY2023 [DEL23]."
assert lines[3] == "CY2008: For CY2008, CMS finalized RVUs [L100]."
# then the question's matched facts, then the stance unit
assert block.index("99324 was deleted for CY2023. [DEL23]") > block.index("CY2008:")
assert block.index("Our own classification") > block.index("[DEL23]")
assert "flagged paraphrase" not in block and "a finding" not in block
assert "payment row" not in block
# every line but the stance header ends with a label
for ln in lines:
assert ln.rstrip(".").endswith("]") or ln.startswith(
("Dossier —", "Our own classification")
)
def test_deletion_question_surfaces_cy2023_over_cy2008_rounds(replica):
"""The live bug: 30 CY2008 round lines crowded out every other fact."""
block = _ev(replica, "When were 99324-99325 deleted?").prompt_block()
assert "99324 was deleted for CY2023. [DEL23]" in block
assert block.count("For CY2008, CMS finalized work RVU") < 10
def test_matching_is_question_aware(replica):
ev = _ev(replica, "How did CMS value 99326 in 2008?")
first = [f for f in ev.facts if f.id == ev.matched[0]][0]
assert first.year == 2008 and "99326" in first.codes
def test_match_facts_round_robin_newest_first_and_limit():
facts = [
_fact(1, "round", "r-old", year=2008),
_fact(2, "round", "r-new", year=2023),
_fact(3, "event", "e", year=2015),
_fact(4, "round", "r-mid", year=2015),
_fact(5, "stance_split", "s"),
_fact(6, "payment", "p"),
_fact(7, "round", "flag", note="x"),
_fact(8, "round", "elsewhere", codes=("A1",), year=2000),
]
assert match_facts(facts, (), ("99341",), ()) == ("F2", "F3", "F4", "F1")
# a named year also matches; the limit applies after interleaving
assert match_facts(facts, (), ("zzz",), {2000}, limit=1) == ("F8",)
# nothing matches -> every candidate
assert match_facts(facts, ("F2",), ("zzz",), ()) == ("F4", "F3", "F1", "F8")
def test_question_years():
assert question_years("CY2023 vs 2008, and cy 2015?") == {2023, 2008, 2015}
def test_stance_unit_has_one_header_and_no_repeated_accuracy(replica):
block = _ev(replica, "home visits?").prompt_block()
assert block.count("Preliminary model classification") == 1
head = [ln for ln in block.splitlines() if ln.startswith("Our own")][0]
assert ACC in head
for ln in block.splitlines():
if "commenters we classified" in ln:
assert "Preliminary" not in ln and ln.endswith("]")
assert block.index(head) < block.index("Of 3 CY2023 commenters")
def test_stance_header_says_unmeasured_without_accuracy():
d = _dossier(accuracy="")
ev = DossierEvidence(
d.family, d.name, "u", d.summary, tuple(d.facts.values()), (), accuracy=""
)
assert "accuracy is not yet measured" in ev.prompt_block()
def test_no_stance_facts_no_unit():
ev = DossierEvidence("F", "N", "u", "s", (), ())
assert ev.prompt_block().splitlines()[1] == "Summary: s"
assert "Our own" not in ev.prompt_block()
def test_max_rows_caps_matched_facts(replica):
ev = _ev(replica, "home visits?")
n = len(ev.prompt_block(max_rows=3).splitlines())
assert n == len(ev.prompt_block(max_rows=0).splitlines()) + 3
def test_max_chars_sheds_matched_then_stance_then_old_timeline(replica):
ev = _ev(replica, "home visits?")
full = ev.prompt_block()
no_matched = ev.prompt_block(max_rows=0)
assert "Our own" in no_matched
# a limit that only the matched facts must give way to
cut = ev.prompt_block(max_chars=len(no_matched) + 5)
assert len(cut) <= len(no_matched) + 5 and "Our own" in cut
# smaller: the whole stance unit goes (never counts without the header)
tiny = ev.prompt_block(max_chars=1)
assert "Our own" not in tiny and "commenters we classified" not in tiny
assert tiny.count("\nCY") == 2 and len(tiny) < len(full)
def test_max_chars_sheds_timeline_down_to_the_floor():
tl = tuple(
TimelineEvent(2000 + i, "k", (), f"event {i} [F1]", ("F1",), (), ())
for i in range(12)
)
ev = DossierEvidence("F", "N", "u", "s", (_fact(1, "round", "r"),), (), timeline=tl)
block = ev.prompt_block(max_chars=1)
assert block.count("\nCY") == TIMELINE_FLOOR
assert "CY2011:" in block and "CY2003:" not in block # oldest went first
assert ev.prompt_block(floor=True) == block
assert ev.prompt_block().count("\nCY") == 12
def test_dossier_url_uses_env_domain(monkeypatch):
monkeypatch.setenv("DOMAIN", "example.org")
assert dossier_url("A-B", CFG) == "https://lex.example.org/?family=A-B#dossier"
monkeypatch.delenv("DOMAIN")
assert dossier_url("A-B", replace(CFG, domain="cfg.test")) == (
"https://lex.cfg.test/?family=A-B#dossier"
)
def test_failed_dossier_query_is_logged_not_raised(replica, monkeypatch, caplog):
import llm.dossier as mod
def boom(_cur):
raise RuntimeError("bad table")
monkeypatch.setattr(mod, "dossier_families", boom)
with caplog.at_level(logging.WARNING, logger="llm.dossier"):
assert dossier_evidence("home visits?", replica) is None
assert "dossier evidence skipped (query)" in caplog.text