feat: redesign around phenotype-driven triage, not variant filtering

A table with filters made the user do the work. Rare disease triage is a different task:
which few variants could explain *this* patient's phenotype, and why. The app now answers
that, and lets a reviewer act on the answer.

Domain
- a case is a proband: a VCF plus the HPO terms observed in the patient (samples -> cases)
- HPO's gene-to-phenotype annotations are loaded as reference data (scripts/load-hpo.py)
- each candidate can be shortlisted or dismissed with a reason and a note

Ranking (app/services/triage.py, 21 tests)
- weighted sum of phenotype match, rarity, consequence severity and the model's score,
  with every component shown next to the candidate
- rarity and consequence filter; phenotype only ranks, because a real diagnosis can sit in
  a gene nobody has annotated yet and filtering on it would hide exactly that case
- ClinVar is deliberately not an input: it appears beside the result as independent
  confirmation, so nothing ranks highly merely because ClinVar already said pathogenic

UI
- the funnel is the headline: variants called -> rare -> coding candidates -> phenotype-matched
- ranked candidates with evidence chips, not a grid of everything; filters are demoted
- a variant panel showing the score breakdown, the matched HPO terms, the raw VEP record and
  links out to Ensembl/gnomAD/ClinVar, with the decision controls
- a printable case report: phenotype, funnel, shortlisted variants with reasons, provenance

API: /cases with phenotypes, /cases/{id}/candidates (funnel + ranked + weights),
/variants/{id}, /variants/{id}/decision, /cases/{id}/report, /phenotypes for the picker.
Scoring moved under the case and now answers 503 with the reason when no model registry is
reachable, instead of a 500.

Verified end to end on a simulated proband (scripts/make-demo-case.sh: real GIAB HG002
background + one real ClinVar 2-star pathogenic NF2 variant). 13 variants called -> 1 coding
candidate, and the planted variant ranks first at 0.80 on phenotype 1.00, rarity 1.00 and
consequence 1.00, with ClinVar agreeing afterwards.

Tests: api 75, ml 18, loader 16, web 27; ruff, mypy, svelte-check, terraform validate, both
kustomize overlays and the Nextflow stub run all clean.
This commit is contained in:
Kemal Yaylali
2026-09-12 08:30:44 +01:00
parent abde5ec6e4
commit 07a01715fd
47 changed files with 2159 additions and 539 deletions
+137
View File
@@ -0,0 +1,137 @@
"""The triage workflow: a case with a phenotype, ranked candidates, decisions, a report."""
import uuid
import pytest
from factories import seed_case
from httpx import AsyncClient
NF2_TERMS = [("HP:0000365", "Hearing impairment"), ("HP:0009592", "Vestibular schwannoma")]
CASE_TERMS = [*NF2_TERMS, ("HP:0002321", "Vertigo")]
async def a_case_with_candidates() -> tuple[uuid.UUID, uuid.UUID]:
return await seed_case(
phenotypes=CASE_TERMS,
gene_terms={"NF2": NF2_TERMS},
variants=[
{"id": 1, "gene": "NF2", "pos": 1000, "impact": "HIGH", "score": 0.94,
"clinvar_sig": "pathogenic"},
{"id": 2, "gene": "CHEK2", "pos": 2000, "impact": "MODERATE", "gnomad_af": 0.0004,
"score": 0.55},
{"id": 3, "gene": "TTN", "pos": 3000, "impact": "MODIFIER", "gnomad_af": None},
{"id": 4, "gene": "APOE", "pos": 4000, "impact": "HIGH", "gnomad_af": 0.3},
],
)
@pytest.mark.usefixtures("db")
async def test_a_case_keeps_its_phenotype(client: AsyncClient) -> None:
body = {
"name": "PROBAND-01",
"vcf_uri": "gs://bucket/proband.vcf.gz",
"phenotypes": [{"hpo_id": h, "label": lab} for h, lab in NF2_TERMS],
}
r = await client.post("/api/cases", json=body)
assert r.status_code == 201, r.text
assert [p["label"] for p in r.json()["phenotypes"]] == [lab for _, lab in NF2_TERMS]
listed = (await client.get("/api/cases")).json()
assert listed[0]["name"] == "PROBAND-01"
assert listed[0]["shortlisted"] == 0
@pytest.mark.usefixtures("db")
async def test_the_funnel_shows_the_narrowing(client: AsyncClient) -> None:
case_id, _ = await a_case_with_candidates()
page = (await client.get(f"/api/cases/{case_id}/candidates")).json()
# 4 variants -> 3 rare -> 2 rare and coding -> 1 of those in a phenotype-matched gene
assert page["funnel"] == {"total": 4, "rare": 3, "candidates": 2, "phenotype_matched": 1}
@pytest.mark.usefixtures("db")
async def test_the_phenotype_matched_variant_ranks_first_with_its_reasons(
client: AsyncClient,
) -> None:
case_id, _ = await a_case_with_candidates()
page = (await client.get(f"/api/cases/{case_id}/candidates")).json()
assert [c["variant"]["gene"] for c in page["items"]] == ["NF2", "CHEK2"]
top = page["items"][0]
assert [t["label"] for t in top["matched_terms"]] == ["Hearing impairment", "Vestibular schwannoma"]
assert top["components"]["phenotype"] == pytest.approx(2 / 3, abs=1e-4)
assert top["components"]["rarity"] == 1.0
assert page["weights"]["phenotype"] == 0.35
# ClinVar is evidence, not an input to the rank.
assert top["variant"]["clinvar_sig"] == "pathogenic"
@pytest.mark.usefixtures("db")
async def test_a_reviewer_decides_and_the_decision_sticks(client: AsyncClient) -> None:
case_id, _ = await a_case_with_candidates()
variant_id = (await client.get(f"/api/cases/{case_id}/candidates")).json()["items"][0]["variant"]["id"]
r = await client.post(
f"/api/variants/{variant_id}/decision",
json={"state": "shortlisted", "reason": "fits the phenotype", "note": "confirm by Sanger"},
)
assert r.status_code == 200, r.text
# Changing your mind replaces the decision rather than failing.
r = await client.post(f"/api/variants/{variant_id}/decision", json={"state": "dismissed"})
assert r.status_code == 200
detail = (await client.get(f"/api/variants/{variant_id}")).json()
assert detail["decision"]["state"] == "dismissed"
assert (await client.get("/api/cases")).json()[0]["shortlisted"] == 0
@pytest.mark.usefixtures("db")
async def test_the_variant_panel_carries_the_evidence(client: AsyncClient) -> None:
case_id, _ = await a_case_with_candidates()
variant_id = (await client.get(f"/api/cases/{case_id}/candidates")).json()["items"][0]["variant"]["id"]
detail = (await client.get(f"/api/variants/{variant_id}")).json()
assert detail["variant"]["hgvsp"] is None or isinstance(detail["variant"]["hgvsp"], str)
assert detail["score"] > 0
assert [t["hpo_id"] for t in detail["matched_terms"]] == [h for h, _ in NF2_TERMS]
assert "annotations" in detail
@pytest.mark.usefixtures("db")
async def test_the_report_is_the_decision_trail(client: AsyncClient) -> None:
case_id, _ = await a_case_with_candidates()
items = (await client.get(f"/api/cases/{case_id}/candidates")).json()["items"]
await client.post(f"/api/variants/{items[0]['variant']['id']}/decision",
json={"state": "shortlisted", "reason": "fits the phenotype"})
await client.post(f"/api/variants/{items[1]['variant']['id']}/decision",
json={"state": "dismissed", "reason": "gene unrelated to phenotype"})
report = (await client.get(f"/api/cases/{case_id}/report")).json()
assert report["funnel"]["candidates"] == 2
assert [v["variant"]["gene"] for v in report["shortlisted"]] == ["NF2"]
assert report["shortlisted"][0]["decision"]["reason"] == "fits the phenotype"
assert [v["variant"]["gene"] for v in report["dismissed"]] == ["CHEK2"]
assert report["provenance"]["vep_version"] == "113.0"
@pytest.mark.usefixtures("db")
async def test_candidates_can_still_be_filtered(client: AsyncClient) -> None:
case_id, _ = await a_case_with_candidates()
page = (await client.get(f"/api/cases/{case_id}/candidates", params={"gene": "chek2"})).json()
assert [c["variant"]["gene"] for c in page["items"]] == ["CHEK2"]
# The funnel still describes the whole case, not the filtered view.
assert page["funnel"]["total"] == 4
@pytest.mark.usefixtures("db")
async def test_phenotype_search_backs_the_picker(client: AsyncClient) -> None:
await seed_case(gene_terms={"NF2": NF2_TERMS}, variants=[])
found = (await client.get("/api/phenotypes", params={"q": "vestibular"})).json()
assert found == [{"hpo_id": "HP:0009592", "label": "Vestibular schwannoma"}]
@pytest.mark.usefixtures("db")
async def test_candidates_before_the_pipeline_has_run(client: AsyncClient) -> None:
r = await client.post("/api/cases", json={"name": "empty", "vcf_uri": "gs://bucket/x.vcf.gz"})
page = (await client.get(f"/api/cases/{r.json()['id']}/candidates")).json()
assert page["items"] == []
assert page["funnel"]["total"] == 0