Files
WebApi/webapi/models.py
T
alberto ec5d945f71 Cleanup of the TEA parity work: no prose in code, no hacks, everything in its place
1. No prose in code
- Remove parity-added Python comments and docstrings across the EEG, FHIR,
  execution, preview, training and run code and tests. Preserve endpoint
  descriptions as explicit FastAPI schema metadata.

2. No hacks, no glued code
- Read the declared TEA patient filters and training inputs directly and
  use the same TEA check for exposing and validating reference options.
- Give the Dagster GraphQL request one helper. Keep lock backoff and
  cancellation polling because their timing and error behavior are
  covered by run tests and they handle different Dagster states.
- Use the renamed FHIR report ID helper in the hospital test. Keep
  TEA_GATE_SLOW local to that test and preserve the test assertions.

3. Everything in its place
- Keep endpoint and run handling in WebApi and reuse Core and Persistance
  for domain rules and reads. Leave tests in the existing testpaths.
2026-11-30 13:41:49 -06:00

296 lines
11 KiB
Python

"""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."""
import mimetypes
import zipfile
from datetime import date
from pathlib import Path
from typing import Annotated, Any, Literal
from dagster_graphql import DagsterGraphQLClient
from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile
from fastapi.responses import Response
from pydantic import BaseModel, Field, WithJsonSchema
from core import tea
from core.domains import Domain, InputSpec
from persistance import bundle, cluster, inputs, registry
from persistance.cluster import Execution, Reference
from webapi.runs import dagster, execution_config, submit
router = APIRouter(prefix="/models", tags=["models"])
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]
status: Literal["champion", "retired", "candidate"]
@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}/export",
responses={200: {"content": {"application/zip": {}}}},
response_class=Response,
)
def export_models(
domain: Domain,
names: Annotated[list[str] | None, Query()] = None,
versions: bundle.Selection = "champion",
) -> Response:
try:
exported = bundle.export(domain, names, versions)
except bundle.Empty as e:
raise HTTPException(409, detail=str(e)) from e
except bundle.BundleError as e:
raise HTTPException(422, detail=str(e)) from e
return Response(
exported.data,
media_type="application/zip",
headers={
"X-Bundle-Sha256": exported.sha256,
"X-Bundle-Versions": ",".join(f"{name}/{v}" for name, v in exported.versions),
"Content-Disposition": (
f'attachment; filename="{domain}-models-{exported.sha256[:12]}.zip"'
),
},
)
@router.post("/{domain}/import")
def import_models(
domain: Domain,
sha256: Annotated[str, Query(pattern=r"^[0-9a-fA-F]{64}$")],
file: UploadFile,
client: DagsterGraphQLClient = Depends(dagster),
) -> dict[str, str]:
computed, path = bundle.stage(file.file)
if computed != sha256.lower():
path.unlink(missing_ok=True)
raise HTTPException(422, detail=f"the file's SHA-256 is {computed}, not the one given")
if not zipfile.is_zipfile(path):
path.unlink(missing_ok=True)
raise HTTPException(422, detail="not a bundle")
if not bundle.trusted(computed):
path.unlink(missing_ok=True)
raise HTTPException(
403,
detail=f"bundle {computed} is not trusted on this server: "
f"the operator adds its SHA-256 to {bundle.trusted_file()}",
)
return submit(
client,
"import_bundle",
"import_bundle_files",
{"domain": domain.value, "sha256": computed},
domain.value,
)
@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.get("/{domain}/{name}/versions/{version}/reports/{report}",
responses={200: {"content": {"application/json": {}, "application/octet-stream": {}},
"description": "the report as stored"}},
response_class=Response) # fmt: skip
def read_report(domain: Domain, name: str, version: int, report: str) -> Response:
"""A version's report: the generated ones as JSON (what the governance page draws), the
clinical validation as the file the clinical team uploaded."""
found = registry.report(f"{domain.value}.{name}", version, report)
if found is None:
raise HTTPException(404, detail=f"{domain.value}.{name} v{version} has no {report}")
filename, content = found
kind = mimetypes.guess_type(filename)[0] or "application/octet-stream"
return Response(content, media_type=kind,
headers={"Content-Disposition": f'inline; filename="{filename}"'}) # fmt: skip
@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.UnknownVersion as e:
raise HTTPException(404, detail=str(e)) from e
except ValueError as e:
raise HTTPException(409, detail=str(e)) from e
return {"champion": version}
@router.get("/{domain}/{name}/versions/{version}/checks")
def version_checks(domain: Domain, name: str, version: int) -> dict:
registered = f"{domain.value}.{name}"
try:
status = registry.status(registered, version)
except registry.UnknownVersion as e:
raise HTTPException(404, detail=str(e)) from e
checks = registry.checks(registered, version)
return {
"version": version,
"status": status,
"checks": checks,
"promotable": status != "retired" and all(check["present"] for check in checks),
}
@router.post("/{domain}/{name}/versions/{version}/retire")
def retire(domain: Domain, name: str, version: int) -> dict[str, str]:
try:
registry.retire(f"{domain.value}.{name}", version)
except registry.UnknownVersion as e:
raise HTTPException(404, detail=str(e)) from e
except ValueError as e:
raise HTTPException(409, detail=str(e)) from e
return {"status": "retired"}
@router.get("/{domain}/{name}/versions/{version}/lineage")
def lineage(domain: Domain, name: str, version: int) -> dict:
try:
return registry.lineage(f"{domain.value}.{name}", version)
except registry.UnknownVersion as e:
raise HTTPException(404, detail=str(e)) from e
def _training_inputs(domain: Domain, name: str) -> tuple[InputSpec, Path]:
declared = tea.TRAINING_INPUTS if domain == Domain.TEA else {}
spec = declared.get(name, declared.get("*"))
if spec is None:
raise HTTPException(404, detail=f"no training inputs for {domain.value}.{name}")
try:
return spec, inputs.root(spec)
except LookupError as e:
raise HTTPException(503, detail=str(e)) from e
@router.get("/{domain}/{name}/inputs")
def training_inputs(domain: Domain, name: str) -> dict:
spec, root = _training_inputs(domain, name)
return {"description": spec.description, "allowed": spec.allowed, "sets": inputs.sets(root)}
@router.post("/{domain}/{name}/inputs/{set}/files")
def upload_training_inputs(
domain: Domain,
name: str,
set: str,
files: Annotated[
list[Annotated[UploadFile, WithJsonSchema({"type": "string", "format": "binary"})]],
File(min_length=1),
],
) -> dict:
spec, root = _training_inputs(domain, name)
try:
return inputs.upload(root, set, spec.allowed, [(f.filename or "", f.file) for f in files])
except ValueError as e:
raise HTTPException(422, detail=str(e)) from e
@router.get("/{domain}/{name}/versions/{version}/curve")
def curve(domain: Domain, name: str, version: int, feature: str = "value") -> list[dict]:
if domain != Domain.TEA:
raise HTTPException(404, detail="no age curve for this model")
try:
model = registry.load(f"{domain.value}.{name}", version).unwrap_python_model()
if not hasattr(model, "curve"):
raise HTTPException(404, detail="no age curve for this model")
return model.curve(feature, range(16, 37))
except KeyError as e:
raise HTTPException(404, detail=f"no curve feature {feature!r}") from e
except LookupError as e:
raise HTTPException(404, detail=str(e)) from e
class TrainingForm(BaseModel):
as_of: date | None = Field(
None, title="Datos hasta", description="Fecha de corte de los datos (por omisión, hoy)"
)
execution: Execution | None = None
reference: Reference | None = None
class Training(TrainingForm):
models: list[str] = []
class TrainingConfig(BaseModel):
domain: str
name: str
json_schema: dict[str, Any]
defaults: dict[str, Any]
@router.get("/{domain}/{name}/training-config")
def training_config(domain: Domain, name: str) -> TrainingConfig:
json_schema = TrainingForm.model_json_schema()
defaults = {"execution": {"mode": cluster.default_mode(), "scheduler": None}}
if domain == Domain.TEA:
defaults["reference"] = {"line_hz": 50}
else:
del json_schema["properties"]["reference"]
del json_schema["$defs"]["Reference"]
return TrainingConfig(
domain=domain.value, name=name, json_schema=json_schema, defaults=defaults
)
class Analyze(BaseModel):
execution: Execution | None = None
@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 request.reference is not None and domain != Domain.TEA:
raise HTTPException(422, f"{domain.value} models take no reference cohort")
config: dict = {"domain": domain.value, "execution": execution_config(request.execution)}
if request.as_of:
config["as_of"] = request.as_of.isoformat()
if request.models:
config["models"] = request.models
if request.reference is not None:
config["reference"] = request.reference.model_dump()
return submit(client, "train", "train_models", config, domain=domain.value)
@router.post("/{domain}/analyze")
def analyze(
domain: Domain,
request: Analyze = Analyze(), # noqa: B008
client: DagsterGraphQLClient = Depends(dagster),
) -> dict[str, str]:
"""Starts analysing the studies the domain's models read whole (TEA: its EEGs); follow
it at /runs."""
config = {"domain": domain.value, "execution": execution_config(request.execution)}
return submit(client, "analyze", "analyze_studies", config, domain=domain.value)
@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."""
return submit(client, "score", "score_models", {"domain": domain.value}, domain=domain.value)