Model governance and CaCu measures as FHIR MeasureReports; Phase 2 gate

This commit is contained in:
Roberto Treviño
2026-11-25 01:16:45 -06:00
parent 1c53276b55
commit e2ed1e9dfb
4 changed files with 281 additions and 1 deletions
+144
View File
@@ -0,0 +1,144 @@
"""Phase 2 gate, CaCu: the synthetic hospital, loaded through one drawn pipeline, gives what
the current platform gives on the same hospital (the reference fixtures): its cohorts, its
indicators, and, trained by the platform's own jobs, its models' predictions. Promotion
needs the three reports. Real API, Dagster and MLflow; nothing faked.
Fixed on purpose, so compared differently:
- cin2_pim_post_colposcopy scores each patient at her post-colposcopy index; the current
one scores at her first event (its cohort's index), so only its members are compared.
- cin2_logistic's index date is the index sample's, not 1970-01-01.
"""
import json
import sqlite3
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from test_conectar import ok, wait_for
ROOT = Path(__file__).parents[2]
HOSPITAL = ROOT / "tests" / "fixtures" / "hospital"
REFERENCE = ROOT / "tests" / "fixtures" / "reference" / "cacu"
PIPELINE = ROOT / "tests" / "fixtures" / "pipelines" / "hospital_cacu.json"
REFERENCE_CUTOFF = "2026-11-23" # the current platform's cohort cut-off (follow-up ends)
CAPTURED_ON = "2026-11-25" # the day the indicators were captured: durations counted to it
PERIODS = [f"{y}-S{s}" for y in range(2021, 2027) for s in (1, 2)]
COHORTS = {
"cacu_cohort_total": "cohorte_total",
"cacu_cohort_surveillance": "cohorte_vigilancia",
"cacu_cohort_post_treatment": "cohorte_post_tratamiento",
}
CODES = { # platform code -> the current platform's
"NILM": "NORMAL", "LSIL": "LIEBG", "HSIL": "LIEAG", "carcinoma": "CARCINOMA",
"normal": "NORMAL", "no_data": "SIN_DATO", "no_biopsy": "SIN_BIOPSIA",
"post_treatment": "POST_TRATAMIENTO", "post_colposcopy": "POST_COLPOSCOPIA",
"pre_colposcopy": "PRE_COLPOSCOPIA",
} # fmt: skip
STRATA = {"age_group": "grupo_edad", "follow_up_status": "estatus_seguimiento",
"result": "citologia_alto_grado"} # fmt: skip
CATEGORY = {"CACU_EU7": "resultado", "CACU_CONFIRMACION_CITOLOGIA": "biopsia_grado"}
def _patients(q) -> dict[str, int]:
"""Each person's patient id in the hospital (for comparing only)."""
with sqlite3.connect(HOSPITAL / "hospital_cacu.db") as con:
number = {n.replace("-", ""): p for p, n in con.execute(
"select pac_id, pac_id_hospital from paciente")} # fmt: skip
rows = q("select distinct person_id, record_number from bronze.staged__identity")
return {person: number[record] for person, record in rows}
def _report(entry: dict, measure: str) -> tuple:
group = entry["resource"]["group"][0]
populations = {p["code"]["coding"][0]["code"]: p["count"] for p in group["population"]}
score = group.get("measureScore", {})
extensions = {e["url"].rsplit("/", 1)[1]: e["valueDecimal"] for e in score.get("extension", [])}
strata = {}
for s in group.get("stratifier", []):
name = s["code"][0]["text"]
name = CATEGORY.get(measure, "banda") if name == "category" else STRATA.get(name, name)
strata[name] = {CODES.get(x["value"]["text"], x["value"]["text"]): {
p["code"]["coding"][0]["code"]: p["count"] for p in x["population"]}
for x in s.get("stratum", [])} # fmt: skip
return populations, score.get("value"), extensions, {k: v for k, v in strata.items() if v}
def test_cacu_from_the_hospital_to_indicators_and_risks(api, platform):
pipeline = json.loads(PIPELINE.read_text().replace("{hospital}", str(HOSPITAL)))
ok(api.put("/ingest/pipelines/cacu", json=pipeline))
wait_for(api, ok(api.post("/ingest/pipelines/cacu/runs", json={}))["run_id"])
q = platform.query
patient = _patients(q)
# Cohorts: the same patients, indexed on the same day.
for ours, theirs in COHORTS.items():
sql = f"select person_id, index_date from gold.{ours} where excluded_by is null"
found = {(patient[p], str(d)) for p, d in q(sql)}
frame = pd.read_parquet(REFERENCE / "cohorts" / "cacu" / theirs / "dbt" / "1.parquet")
frame["fecha_indice"] = frame["fecha_indice"].astype(str)
assert found == set(frame[["pac_id", "fecha_indice"]].drop_duplicates()
.itertuples(index=False, name=None)), ours # fmt: skip
current = json.loads((REFERENCE / "models.json").read_text())
post_colposcopy = current["cin2_pim_post_colposcopy"]["version"]["metrics"]
members = q("select count(*) from gold.cacu_cohort_post_colposcopy where excluded_by is null")
assert members[0][0] == post_colposcopy["n_train"] + post_colposcopy["n_test"]
# Indicators: every measure, every semester, as the current platform answers them
# (no risk batch yet, so the risk bands are empty as they were).
reference = json.loads((REFERENCE / "indicators.json").read_text())
for measure in ok(api.get("/cacu/measures")):
params = {"periods": ",".join(PERIODS), "event_cutoff": CAPTURED_ON}
found = ok(api.get(f"/cacu/measures/{measure['id']}", params=params))["entry"]
for ours, theirs in zip(found, reference[measure["id"]]["body"]["entry"], strict=True):
a, b = _report(ours, measure["id"]), _report(theirs, measure["id"])
where = (measure["id"], ours["resource"]["period"]["start"])
assert a[0] == b[0] and a[3] == b[3], where
assert (a[1] is None) == (b[1] is None), where
assert b[1] is None or a[1] == pytest.approx(b[1], rel=1e-9), where
assert a[2] == pytest.approx(b[2]), where
# Models: one training run gives a version of each, with its two generated reports;
# none is promoted without the clinical validation.
wait_for(api, ok(api.post("/models/cacu/train", json={"as_of": REFERENCE_CUTOFF}))["run_id"])
names = ok(api.get("/models/cacu"))
assert set(names) == set(current) - {"survival"}
for name in names:
(version,) = ok(api.get(f"/models/cacu/{name}/versions"))
assert version["reports"] == ["interpretability", "technical_validation"]
for metric in ("n_train", "n_test"):
assert version["metrics"][metric] == current[name]["version"]["metrics"][metric]
assert api.post(f"/models/cacu/{name}/versions/1/promote").status_code == 409
files = {"file": ("validacion.pdf", b"%PDF-1.4 clinical validation", "application/pdf")}
ok(api.post(f"/models/cacu/{name}/versions/1/reports/clinical_validation", files=files))
assert ok(api.post(f"/models/cacu/{name}/versions/1/promote")) == {"champion": 1}
# Risks: the champions score their cohorts with the current models' predictions.
wait_for(api, ok(api.post("/models/cacu/score"))["run_id"])
for name in names:
risks = pd.DataFrame(q(
"select person_id, index_date, horizon_years, probability, ci_low, ci_high "
f"from gold.cacu_risk where model = 'cacu.{name}'"
), columns=["person_id", "index_date", "horizon_years", "probability", "ci_low",
"ci_high"]) # fmt: skip
risks["pac_id"] = risks["person_id"].map(patient)
expected = pd.read_parquet(REFERENCE / "ref" / f"{name}.parquet")
if name == "cin2_pim_post_colposcopy": # fixed: scored at her own index
cohort = q("select person_id, index_date from gold.cacu_cohort_post_colposcopy "
"where excluded_by is null") # fmt: skip
assert set(map(tuple, risks[["person_id", "index_date"]].astype(str).values)) == {
(p, str(d)) for p, d in cohort} # fmt: skip
continue
both = risks.merge(expected, left_on=["pac_id", "horizon_years"],
right_on=["pac_id", "horizonte_anios"], how="outer",
indicator=True) # fmt: skip
assert (both["_merge"] == "both").all(), name
for ours, theirs in [("probability", "probabilidad"), ("ci_low", "ic_bajo"),
("ci_high", "ic_alto")]: # fmt: skip
if theirs in both:
np.testing.assert_allclose(both[ours].astype(float), both[theirs], rtol=1e-6)
# The risk band now has the surveillance cohort's scored members.
bands = ok(api.get("/cacu/measures/CACU_RIESGO_BANDA", params={"periods": "2025-S1"}))
assert bands["entry"][0]["resource"]["group"][0]["population"][0]["count"] > 0
+3 -1
View File
@@ -1,7 +1,7 @@
from fastapi import Depends, FastAPI from fastapi import Depends, FastAPI
from core.domains import Domain from core.domains import Domain
from webapi import ingest, review, runs from webapi import ingest, measures, models, review, runs
from webapi.auth import caller from webapi.auth import caller
app = FastAPI( app = FastAPI(
@@ -13,6 +13,8 @@ app = FastAPI(
app.include_router(ingest.router) app.include_router(ingest.router)
app.include_router(review.router) app.include_router(review.router)
app.include_router(runs.router) app.include_router(runs.router)
app.include_router(models.router)
app.include_router(measures.router)
@app.get("/health") @app.get("/health")
+48
View File
@@ -0,0 +1,48 @@
"""CaCu's measures, evaluated on request over gold and served as FHIR R4B MeasureReports:
one Bundle per measure, one report per period asked for. Counting a few thousand rows is all
the request does; everything heavy was done by dbt."""
from datetime import date, datetime
from fastapi import APIRouter, HTTPException, Query
from fhir.resources.R4B.bundle import Bundle
from core import cacu
from core import measures as m
from core.domains import Domain
from persistance import measures as reads
router = APIRouter(tags=["measures"])
DOMAINS = {Domain.CACU: m.MEASURES}
@router.get("/{domain}/measures")
def measures(domain: Domain) -> list[dict[str, str]]:
found = DOMAINS.get(domain, {})
return [{"id": x.id, "title": x.title, "scoring": x.rule.kind} for x in found.values()]
@router.get("/{domain}/measures/{measure_id}")
def measure(
domain: Domain,
measure_id: str,
periods: str = Query(description="comma-separated semesters (2025-S1) or months (2025-03)"),
as_of: datetime | None = Query(None, description="count only what was known by then"),
event_cutoff: date | None = Query(None, description="durations count to this day"),
) -> dict:
"""A Bundle (searchset) with the measure's MeasureReport for each period."""
if (found := DOMAINS.get(domain, {}).get(measure_id)) is None:
raise HTTPException(404, detail=f"no {domain.value} measure {measure_id}")
try:
asked = [m.Period.parse(p.strip()) for p in periods.split(",") if p.strip()]
except ValueError as e:
raise HTTPException(422, detail=f"periods: {e}") from e
params = {"model": cacu.RISK_BAND_MODEL} if found.rows == "risk" else {}
rows = reads.rows(found.rows, **params)
reports = [
m.report(found, p, m.evaluate(found, rows, p, as_of, event_cutoff), as_of, domain.value)
for p in asked
]
bundle = Bundle(type="searchset", total=len(reports),
entry=[{"resource": r} for r in reports]) # fmt: skip
return bundle.model_dump(mode="json", exclude_none=True)
+86
View File
@@ -0,0 +1,86 @@
"""Model governance: versions and their reports (MLflow), promotion, and the training and
scoring runs (Dagster). The API starts runs and reads the registry; it never trains."""
from datetime import date
from dagster_graphql import DagsterGraphQLClient, DagsterGraphQLClientError
from fastapi import APIRouter, Depends, HTTPException, UploadFile
from pydantic import BaseModel
from core.domains import Domain
from persistance import registry
from webapi.runs import dagster
router = APIRouter(prefix="/models", tags=["models"])
JOBS = {Domain.CACU: ("train_cacu", "score_cacu")}
class Version(BaseModel):
version: int
created: int # ms since the epoch
aliases: list[str]
metrics: dict[str, float]
params: dict[str, str]
reports: list[str]
@router.get("/{domain}")
def models(domain: Domain) -> list[str]:
prefix = f"{domain.value}."
return [n.removeprefix(prefix) for n in registry.names(prefix)]
@router.get("/{domain}/{name}/versions")
def versions(domain: Domain, name: str) -> list[Version]:
if not (found := registry.versions(f"{domain.value}.{name}")):
raise HTTPException(404, detail=f"no {domain.value} model {name}")
return [Version(**v) for v in found]
@router.post("/{domain}/{name}/versions/{version}/reports/clinical_validation")
def add_clinical_validation(domain: Domain, name: str, version: int, file: UploadFile) -> dict:
"""The clinical team's validation of a version: the third report promotion needs."""
registry.add_report(f"{domain.value}.{name}", version, "clinical_validation",
file.filename or "report", file.file.read()) # fmt: skip
return {"reports": sorted(registry.reports(f"{domain.value}.{name}", version))}
@router.post("/{domain}/{name}/versions/{version}/promote")
def promote(domain: Domain, name: str, version: int) -> dict:
"""The version risk batches come from from now on; refused (409) without its three
reports: technical validation, interpretability and clinical validation."""
try:
registry.promote(f"{domain.value}.{name}", version)
except registry.MissingReports as e:
raise HTTPException(409, detail=str(e)) from e
return {"champion": version}
class Training(BaseModel):
as_of: date | None = None # the date the data are taken up to (default: today)
def _submit(client: DagsterGraphQLClient, job: str, op: str, config: dict) -> dict[str, str]:
try:
run_id = client.submit_job_execution(job, run_config={"ops": {op: {"config": config}}})
except DagsterGraphQLClientError as e:
raise HTTPException(502, detail=str(e)) from e
return {"run_id": run_id}
@router.post("/{domain}/train")
def train(domain: Domain, request: Training,
client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]: # fmt: skip
"""Starts training a new version of every model of the domain; follow it at /runs."""
if domain not in JOBS:
raise HTTPException(404, detail=f"{domain.value} has no models yet")
config = {"as_of": request.as_of.isoformat()} if request.as_of else {}
return _submit(client, JOBS[domain][0], "train_models", config)
@router.post("/{domain}/score")
def score(domain: Domain, client: DagsterGraphQLClient = Depends(dagster)) -> dict[str, str]:
"""Starts a risk batch from each model's champion; follow it at /runs."""
if domain not in JOBS:
raise HTTPException(404, detail=f"{domain.value} has no models yet")
return _submit(client, JOBS[domain][1], "score_models", {})