Cohorts built from dbt's rules and exported, an idempotent run command and estimate; io split by responsibility, with stored predictions moved into the registry and the ONNX check into tracking
This commit is contained in:
@@ -10,17 +10,17 @@ WebApi.
|
|||||||
| Módulo | Qué hace |
|
| Módulo | Qué hace |
|
||||||
|---|---|
|
|---|---|
|
||||||
| `__main__.py` | La línea de comandos: `python -m models <comando>`. Cada área agrega ahí sus subcomandos. |
|
| `__main__.py` | La línea de comandos: `python -m models <comando>`. Cada área agrega ahí sus subcomandos. |
|
||||||
| `io/contract.py` | `RiskEstimator`: el contrato con que se piden riesgos a un modelo (recibe el marco ancho de un armado, devuelve un `Risk` por miembro y horizonte y su `Provenance`, las llaves para conciliar con MLflow). |
|
| `io/contracts.py` | The shapes of the data: a cohort build's file (`COHORT_SCHEMA`), a cohort's rules (`ExclusionRule`, `CohortQueries`, `BuiltCohort`), an estimate's output (`ESTIMATE_COLUMNS`) and the risk contract (`Risk`, `Provenance`, `RiskEstimator`, which still takes the wide frame). |
|
||||||
| `io/training.py` | `TrainingRun`: una corrida de MLflow ligada a su armado de cohorte (`kit.armado_id`, ML-03), artefactos (ML-01) y acceso de solo lectura a los datos (ML-04); el commit de git del código que entrenó y `log_model`, que guarda el modelo con su `modelo_sha` (el hash del artefacto). En PROD solo modelos cuya clase vive en un módulo. |
|
| `io/storage.py` | Where data lives and how it's read and written: cohort and estimate Parquet files (`read_cohort`, `write_once`, `read_metadata`), dbt's manifest (`read_queries`), and Persistance repositories (`resolve_repository`, `ReadOnlyRepository`, ML-04). |
|
||||||
| `io/registry.py` | `registry`: versiones en MLflow (`<dominio>-<escenario>`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. |
|
| `io/lineage.py` | What each output came from, in one vocabulary: registered names, tag keys, the hashes of code, files, tables and models (`code_version`, `model_sha`), and `matches`, the one rule for "already done". |
|
||||||
| `io/prediction.py` | `PredictionService`: guarda cada predicción con la versión de MLflow que la produjo (MLD-4/5). |
|
| `io/tracking.py` | `TrainingRun`: an MLflow run, with its cohort link (ML-03), artifacts (ML-01), environment (ML-02), git commit and `log_model` with its `modelo_sha`. In PROD, only models whose class lives in a module. `inspect_onnx_metadata` checks an ONNX checkpoint before it's logged. |
|
||||||
| `io/export.py` | Lee los metadatos de un checkpoint ONNX para validarlo. |
|
| `io/registry.py` | `registry`: versiones en MLflow (`<dominio>-<escenario>`), su linaje (armado y atrición), revisiones de promoción (ML-02, ML-03, MLD-01, MLD-01b, MLD-03) y el alias `produccion`. Registers a finished run as a version (`register_run`) and sets its description. `PredictionService` stores each single prediction with the version in production (MLD-4/5, EL-04b). |
|
||||||
| `io/repositories.py` | `resolve_repository`: encuentra por nombre el repositorio de `Persistance` de un dominio. |
|
|
||||||
| `io/cohorts.py` | El archivo Parquet de un armado de cohorte: sus columnas y `read_cohort`, que lo lee como marco tras revisar su esquema. |
|
|
||||||
| `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. |
|
| `steps/` | Funciones puras que comparten todos los modelos: sin E/S, se prueban solas. |
|
||||||
| `pipelines/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. |
|
| `pipelines/reading.py` | Los nodos de Hamilton con que lee todo DAG de un modelo: `cohort_build`, `members`, `known_until` y `timeline` (la línea de tiempo de los miembros, cortada en `datos_as_of` del armado y en `known_until`: su `conocida_hasta` o, si no tiene, el momento de la lectura). Los repositorios entran como insumos. |
|
||||||
| `scripts/export_cohort.py` (fuera del paquete) | Exporta un armado de cohorte del kit a su archivo Parquet, una sola vez, leyendo la vista de dbt sin escribir en la base: `uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N]`. La vista se crea aparte, con `dbt run --select <dominio>_linea_de_tiempo`, y solo hace falta repetirlo si cambia su modelo. |
|
| `steps/cohort.py`, `steps/cohort_file.py` | The plain functions the cohort pipelines list: the chain's steps, and from a population and the timeline to the file's table, its hash and its lineage. |
|
||||||
| `cacu/cin2_logistic/` | El modelo de prueba de CaCu, sin significado clínico: sus pasos (`model.py`, nodos de Hamilton), su driver (`train.py`) y sus ajustes (`model.toml`). Solo lee el archivo Parquet del armado. Se entrena con `python -m models train cacu cin2_logistic [--armado N] [--environment dev|prod]`. |
|
| `pipelines/cohort_build.py` | Builds a cohort: all patients → index date → A1 → … → An → study population. Lists the steps, gives each rule its own nodes and runs them. `python -m models cohorts build cacu cohorte_vigilancia --manifest target/manifest.json [--graph]` shows the attrition or the Mermaid diagram; it stores nothing. |
|
||||||
|
| `pipelines/export_cohort.py` | Exports a build to its Parquet file. `python -m models cohorts export cacu cohorte_vigilancia [--build N]` writes the kit's build once; `--source dbt --manifest target/manifest.json` builds it from dbt's rules into `dbt/<n>.parquet` and writes only when its rows change. The timeline comes from dbt's view `<domain>_linea_de_tiempo`. |
|
||||||
|
| `cacu/cin2_logistic/` | El modelo de prueba de CaCu, sin significado clínico: sus pasos (`model.py`, nodos de Hamilton), su driver (`train.py`) y sus ajustes (`model.toml`). Solo lee el archivo Parquet del armado. Se entrena con `python -m models train cacu cin2_logistic [--armado N] [--environment dev|prod]`. Estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--armado N] [--version N]` (`estimate.py`); by default it uses the version holding the `produccion` alias. `python -m models run cacu cin2_logistic [--export] [--train] [--promote] [--estimate --output file.parquet]` runs only the steps named, in that order, and repeats none already done. |
|
||||||
| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). |
|
| `cacu/`, `cama/`, `tea/` | Un paquete por dominio, con sus escenarios y sus cuadernos (`notebooks/`, fuera del paquete instalado). |
|
||||||
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
|
| `ocr.py` | Los trabajos de OCR (`OCR_JOBS`): resultados de VPH, grado CIN y grado histológico desde los PDF guardados (VAR-01..09). |
|
||||||
| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. |
|
| `testing.py` | Ayudas para las pruebas de otro código: `CacuStandIn`, un estimador determinista sin MLflow para correr la cadena de riesgos sin un modelo entrenado. No es un modelo clínico. |
|
||||||
|
|||||||
+215
-13
@@ -14,41 +14,222 @@ def _show_help(parser: argparse.ArgumentParser) -> int:
|
|||||||
return 2
|
return 2
|
||||||
|
|
||||||
|
|
||||||
def _train(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
def _model_module(args: argparse.Namespace, name: str):
|
||||||
"""Finds the model's folder from its name and trains it on the build's file."""
|
"""A module of the model's folder; `None` and a message on stderr if there's no such model."""
|
||||||
if args.environment == "prod" and args.armado is None:
|
|
||||||
parser.error("a prod run names its cohort build: --armado (ML-03)")
|
|
||||||
|
|
||||||
from importlib import import_module
|
from importlib import import_module
|
||||||
|
|
||||||
from persistance.settings import settings
|
|
||||||
|
|
||||||
from models.io.cohorts import cohorts_root, find_cohort_file
|
|
||||||
|
|
||||||
package = f"models.{args.domain}.{args.scenario}"
|
package = f"models.{args.domain}.{args.scenario}"
|
||||||
try:
|
try:
|
||||||
model, trainer = import_module(f"{package}.model"), import_module(f"{package}.train")
|
return import_module(f"{package}.{name}")
|
||||||
except ModuleNotFoundError as error:
|
except ModuleNotFoundError as error:
|
||||||
if not (error.name or "").startswith(package):
|
if not (error.name or "").startswith(package):
|
||||||
raise
|
raise
|
||||||
print(f"no such model: {args.domain}/{args.scenario}", file=sys.stderr)
|
print(f"no such model: {args.domain}/{args.scenario}", file=sys.stderr)
|
||||||
return 1
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _cohort_file(args: argparse.Namespace, model):
|
||||||
|
"""The build's exported file; `None` and a message on stderr if it's missing."""
|
||||||
|
from persistance.settings import settings
|
||||||
|
|
||||||
|
from models.io.storage import cohorts_root, find_cohort_file
|
||||||
|
|
||||||
try:
|
try:
|
||||||
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
|
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
|
||||||
path = find_cohort_file(root, model.SETTINGS["cohort"], args.armado)
|
return find_cohort_file(root, model.SETTINGS["cohort"], args.armado)
|
||||||
except (FileNotFoundError, ValueError) as error:
|
except (FileNotFoundError, ValueError) as error:
|
||||||
print(f"{error}: export it with scripts/export_cohort.py", file=sys.stderr)
|
print(f"{error}: export it with `python -m models cohorts export {model.SETTINGS['cohort'].replace('/', ' ')}`", file=sys.stderr)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _train(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
||||||
|
"""Trains the model on the build's file, always as a new version."""
|
||||||
|
if args.environment == "prod" and args.armado is None:
|
||||||
|
parser.error("a prod run names its cohort build: --armado (ML-03)")
|
||||||
|
if not (model := _model_module(args, "model")) or not (trainer := _model_module(args, "train")):
|
||||||
|
return 1
|
||||||
|
if not (path := _cohort_file(args, model)):
|
||||||
return 1
|
return 1
|
||||||
print(f"{args.domain}/{args.scenario} version {trainer.train(path, args.environment.upper())}, from {path}")
|
print(f"{args.domain}/{args.scenario} version {trainer.train(path, args.environment.upper())}, from {path}")
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def _estimate_step(args: argparse.Namespace, path) -> int:
|
||||||
|
estimator = _model_module(args, "estimate")
|
||||||
|
if not estimator:
|
||||||
|
return 1
|
||||||
|
try:
|
||||||
|
resolved, written = estimator.estimate(path, args.output, args.version)
|
||||||
|
except LookupError as error:
|
||||||
|
print(error, file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
print(f"{'estimated' if written else 'already estimated'}: version {resolved.version}, from {path}, to {args.output}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def _estimate(args: argparse.Namespace) -> int:
|
||||||
|
"""Scores the build's file with a registered version and writes the output file."""
|
||||||
|
if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)):
|
||||||
|
return 1
|
||||||
|
return _estimate_step(args, path)
|
||||||
|
|
||||||
|
|
||||||
|
def _promote_step(args: argparse.Namespace, version: str) -> int:
|
||||||
|
from mlflow import MlflowException
|
||||||
|
|
||||||
|
from models.io.registry import PRODUCTION_ALIAS, registered_name, registry
|
||||||
|
|
||||||
|
name = registered_name(args.domain, args.scenario)
|
||||||
|
try:
|
||||||
|
current = registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS).version
|
||||||
|
except MlflowException:
|
||||||
|
current = None
|
||||||
|
if str(current) == str(version):
|
||||||
|
print(f"already in production: version {version}")
|
||||||
|
return 0
|
||||||
|
registry.client.set_registered_model_alias(name, PRODUCTION_ALIAS, version)
|
||||||
|
print(f"in production: version {version}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
||||||
|
"""Runs the steps asked for, in their order. A step whose result already exists is a no-op."""
|
||||||
|
if not (args.export or args.train or args.promote or args.estimate):
|
||||||
|
parser.error("name at least one step: --export, --train, --promote, --estimate")
|
||||||
|
if args.estimate and not args.output:
|
||||||
|
parser.error("--estimate needs --output")
|
||||||
|
if args.train and args.environment == "prod" and args.armado is None:
|
||||||
|
parser.error("a prod run names its cohort build: --armado (ML-03)")
|
||||||
|
if args.train and args.version:
|
||||||
|
parser.error("--version names an existing version: it can't go with --train")
|
||||||
|
if not (model := _model_module(args, "model")):
|
||||||
|
return 1
|
||||||
|
|
||||||
|
if args.export:
|
||||||
|
cohort = model.SETTINGS["cohort"].split("/", 1)[1]
|
||||||
|
export = argparse.Namespace(domain=args.domain, cohort=cohort, source="kit", build=args.armado, manifest=None)
|
||||||
|
if code := _cohort_export(export):
|
||||||
|
return code
|
||||||
|
if not (args.train or args.promote or args.estimate):
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if not (path := _cohort_file(args, model)):
|
||||||
|
return 1
|
||||||
|
version = args.version
|
||||||
|
if args.train or (args.promote and not version):
|
||||||
|
if not (trainer := _model_module(args, "train")):
|
||||||
|
return 1
|
||||||
|
environment = args.environment.upper()
|
||||||
|
version = trainer.find_trained(path, environment)
|
||||||
|
if args.train and version:
|
||||||
|
print(f"already trained: version {version}, from {path}")
|
||||||
|
elif args.train:
|
||||||
|
version = trainer.train(path, environment)
|
||||||
|
print(f"trained: version {version}, from {path}")
|
||||||
|
elif not version:
|
||||||
|
print(f"no {environment} version trained on {path}: use --train or --version", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
if args.promote and (code := _promote_step(args, version)):
|
||||||
|
return code
|
||||||
|
return _estimate_step(args, path) if args.estimate else 0
|
||||||
|
|
||||||
|
|
||||||
|
def _cohort_build(args: argparse.Namespace) -> int:
|
||||||
|
"""Runs the cohort's rules and shows its attrition, or only its graph. Stores nothing."""
|
||||||
|
from sqlalchemy.exc import DBAPIError
|
||||||
|
|
||||||
|
from importlib import import_module
|
||||||
|
|
||||||
|
from models.io.contracts import CohortDefinitionError
|
||||||
|
from models.io.storage import read_queries
|
||||||
|
from models.pipelines.cohort_build import build_cohort, build_driver, mermaid
|
||||||
|
|
||||||
|
url = f"{args.domain}/{args.cohort}"
|
||||||
|
try:
|
||||||
|
queries = read_queries(args.manifest, url)
|
||||||
|
if args.graph:
|
||||||
|
print(mermaid(build_driver(queries).graph))
|
||||||
|
return 0
|
||||||
|
built = build_cohort(queries, import_module(f"persistance.{args.domain}").dbt_query_repository)
|
||||||
|
except (FileNotFoundError, CohortDefinitionError) as error:
|
||||||
|
print(error, file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
except DBAPIError as error:
|
||||||
|
print(f"a query of {url} failed ({error.orig}): is `{args.domain}_linea_de_tiempo` created? "
|
||||||
|
f"Run `dbt run --select {args.domain}_linea_de_tiempo` in Transformation", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
print(built.attrition.to_string(index=False))
|
||||||
|
print(f"{url}: {len(built.study_population)} members, not stored")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def _cohort_export(args: argparse.Namespace) -> int:
|
||||||
|
"""Exports a build to its Parquet file: the kit's stored build, or one built now from dbt's rules."""
|
||||||
|
from importlib import import_module
|
||||||
|
|
||||||
|
from persistance.aristas.dbt import DbtRelationError
|
||||||
|
from persistance.settings import settings
|
||||||
|
from sqlalchemy.exc import DBAPIError
|
||||||
|
|
||||||
|
from models.io.contracts import CohortDefinitionError
|
||||||
|
from models.io.storage import read_queries
|
||||||
|
from models.io.storage import cohorts_root
|
||||||
|
from models.pipelines.export_cohort import export_dbt_build, export_kit_build
|
||||||
|
|
||||||
|
url = f"{args.domain}/{args.cohort}"
|
||||||
|
repositories = import_module(f"persistance.{args.domain}")
|
||||||
|
timeline = repositories.timeline_repository
|
||||||
|
try:
|
||||||
|
root = cohorts_root(getattr(settings, f"{args.domain}_database_url"))
|
||||||
|
if args.source == "dbt":
|
||||||
|
queries = read_queries(args.manifest, url)
|
||||||
|
path, outcome = export_dbt_build(queries, repositories.dbt_query_repository, timeline, root, args.domain)
|
||||||
|
else:
|
||||||
|
path, outcome = export_kit_build(repositories.cohorte_repository, timeline, root, args.domain, url, args.build)
|
||||||
|
except PermissionError as error:
|
||||||
|
print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
except DBAPIError as error:
|
||||||
|
print(f"a query of {url} failed ({error.orig}): is `{args.domain}_linea_de_tiempo` created? "
|
||||||
|
f"Run `dbt run --select {args.domain}_linea_de_tiempo` in Transformation", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
except (FileNotFoundError, LookupError, ValueError, DbtRelationError) as error:
|
||||||
|
print(error, file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
print(f"{outcome}: {path}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
def _cohort_export_checked(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
||||||
|
if args.source == "dbt" and not args.manifest:
|
||||||
|
parser.error("--source dbt needs --manifest")
|
||||||
|
if args.source == "dbt" and args.build is not None:
|
||||||
|
parser.error("--build names a kit build: it can't go with --source dbt")
|
||||||
|
return _cohort_export(args)
|
||||||
|
|
||||||
|
|
||||||
def build_parser() -> argparse.ArgumentParser:
|
def build_parser() -> argparse.ArgumentParser:
|
||||||
parser = argparse.ArgumentParser(prog="python -m models", description="Commands of the screening models.")
|
parser = argparse.ArgumentParser(prog="python -m models", description="Commands of the screening models.")
|
||||||
commands = parser.add_subparsers(dest="command", metavar="<command>", required=True)
|
commands = parser.add_subparsers(dest="command", metavar="<command>", required=True)
|
||||||
|
|
||||||
cohorts = commands.add_parser("cohorts", help="the cohort builds and their Parquet files")
|
cohorts = commands.add_parser("cohorts", help="the cohort builds and their Parquet files")
|
||||||
cohorts.set_defaults(run=lambda args: _show_help(cohorts))
|
cohorts.set_defaults(run=lambda args: _show_help(cohorts))
|
||||||
|
actions = cohorts.add_subparsers(dest="action", metavar="<action>")
|
||||||
|
build = actions.add_parser("build", help="run a cohort's rules and show its attrition; stores nothing")
|
||||||
|
build.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||||
|
build.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
|
||||||
|
build.add_argument("--manifest", required=True, help="the manifest.json `dbt compile` wrote")
|
||||||
|
build.add_argument("--graph", action="store_true", help="print the chain as a Mermaid diagram without running it")
|
||||||
|
build.set_defaults(run=_cohort_build)
|
||||||
|
|
||||||
|
export = actions.add_parser("export", help="export a build to its Parquet file, once")
|
||||||
|
export.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||||
|
export.add_argument("cohort", help="the cohort without its domain, e.g. cohorte_vigilancia")
|
||||||
|
export.add_argument("--source", choices=["kit", "dbt"], default="kit",
|
||||||
|
help="the kit's stored build, or one built now from dbt's rules")
|
||||||
|
export.add_argument("--build", type=int, help="the kit build's armado_id; the cohort's latest by default")
|
||||||
|
export.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --source dbt")
|
||||||
|
export.set_defaults(run=lambda args: _cohort_export_checked(export, args))
|
||||||
|
|
||||||
train = commands.add_parser("train", help="train a model on a cohort build's file and register a version")
|
train = commands.add_parser("train", help="train a model on a cohort build's file and register a version")
|
||||||
train.add_argument("domain", choices=["cacu", "cama", "tea"])
|
train.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||||
@@ -56,6 +237,27 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
train.add_argument("--armado", type=int, help="the build's armado_id; the cohort's latest exported one by default")
|
train.add_argument("--armado", type=int, help="the build's armado_id; the cohort's latest exported one by default")
|
||||||
train.add_argument("--environment", choices=["dev", "prod"], default="dev")
|
train.add_argument("--environment", choices=["dev", "prod"], default="dev")
|
||||||
train.set_defaults(run=lambda args: _train(train, args))
|
train.set_defaults(run=lambda args: _train(train, args))
|
||||||
|
|
||||||
|
estimate = commands.add_parser("estimate", help="score a cohort build's file with a registered version")
|
||||||
|
estimate.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||||
|
estimate.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
||||||
|
estimate.add_argument("--output", required=True, help="the Parquet file to write")
|
||||||
|
estimate.add_argument("--armado", type=int, help="the build's armado_id; the cohort's latest exported one by default")
|
||||||
|
estimate.add_argument("--version", help="the model version; the one in production by default")
|
||||||
|
estimate.set_defaults(run=_estimate)
|
||||||
|
|
||||||
|
run = commands.add_parser("run", help="run the pipeline's steps you name; those already done are no-ops")
|
||||||
|
run.add_argument("domain", choices=["cacu", "cama", "tea"])
|
||||||
|
run.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
|
||||||
|
run.add_argument("--export", action="store_true", help="export the build to its Parquet file")
|
||||||
|
run.add_argument("--train", action="store_true", help="train, unless a version from this file, code and environment exists")
|
||||||
|
run.add_argument("--promote", action="store_true", help="set the production alias on that version, or on --version")
|
||||||
|
run.add_argument("--estimate", action="store_true", help="score the build with --version, or the one in production")
|
||||||
|
run.add_argument("--armado", type=int, help="the build's armado_id; the latest by default")
|
||||||
|
run.add_argument("--version", help="an existing model version, for --promote and --estimate")
|
||||||
|
run.add_argument("--environment", choices=["dev", "prod"], default="dev")
|
||||||
|
run.add_argument("--output", help="the Parquet file --estimate writes")
|
||||||
|
run.set_defaults(run=lambda args: _run(run, args))
|
||||||
return parser
|
return parser
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
"""Scores a build's file with a registered version and writes the probabilities to a Parquet file."""
|
||||||
|
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import mlflow.pyfunc
|
||||||
|
import pyarrow as pa
|
||||||
|
|
||||||
|
from models.cacu.cin2_logistic.model import SETTINGS
|
||||||
|
from models.io.contracts import ESTIMATE_COLUMNS
|
||||||
|
from models.io.lineage import matches
|
||||||
|
from models.io.registry import ResolvedVersion, registered_name, registry
|
||||||
|
from models.io.storage import read_cohort, read_metadata, write_once
|
||||||
|
|
||||||
|
|
||||||
|
def already_estimated(output_path: Path, version: str, armado_id: str) -> bool:
|
||||||
|
"""Whether the output file already holds this version's scores of this build."""
|
||||||
|
return output_path.exists() and matches(read_metadata(output_path), {"modelo_version": version, "armado_id": armado_id})
|
||||||
|
|
||||||
|
|
||||||
|
def estimate(cohort_path: str | Path, output_path: str | Path, version: str | None = None) -> tuple[ResolvedVersion, bool]:
|
||||||
|
"""Uses the version holding the production alias unless given one, and returns it and whether it wrote the file.
|
||||||
|
The file's metadata says which version and build its rows come from; `modelo_sha` is copied when the version has
|
||||||
|
it, and isn't checked."""
|
||||||
|
domain, scenario = SETTINGS["domain"], SETTINGS["scenario"]
|
||||||
|
output_path = Path(output_path)
|
||||||
|
resolved = registry.resolve(domain, scenario, version)
|
||||||
|
armado_id = read_metadata(cohort_path)["armado_id"]
|
||||||
|
if already_estimated(output_path, resolved.version, armado_id):
|
||||||
|
return resolved, False
|
||||||
|
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(cohort_path))
|
||||||
|
if tuple(risks.columns) != ESTIMATE_COLUMNS:
|
||||||
|
raise ValueError(f"version {resolved.version} returned {list(risks.columns)}, not {list(ESTIMATE_COLUMNS)}")
|
||||||
|
provenance = {"modelo_nombre": registered_name(domain, scenario), "modelo_version": resolved.version,
|
||||||
|
"mlflow_run_id": resolved.run_id, "armado_id": armado_id}
|
||||||
|
if resolved.modelo_sha:
|
||||||
|
provenance["modelo_sha"] = resolved.modelo_sha
|
||||||
|
table = pa.Table.from_pandas(risks, preserve_index=False)
|
||||||
|
write_once(table.replace_schema_metadata({**table.schema.metadata, **provenance}), output_path)
|
||||||
|
return resolved, True
|
||||||
@@ -7,7 +7,6 @@ nothing about performance.
|
|||||||
Each public function is a Hamilton node and each parameter is the node of that name; `train.py` holds the driver.
|
Each public function is a Hamilton node and each parameter is the node of that name; `train.py` holds the driver.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import hashlib
|
|
||||||
import tomllib
|
import tomllib
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
@@ -16,9 +15,10 @@ import pandas as pd
|
|||||||
from sklearn.linear_model import LogisticRegression
|
from sklearn.linear_model import LogisticRegression
|
||||||
from sklearn.metrics import brier_score_loss, roc_auc_score
|
from sklearn.metrics import brier_score_loss, roc_auc_score
|
||||||
|
|
||||||
from models.io.cohorts import cohort_lineage, read_cohort
|
from models.io.lineage import file_sha256
|
||||||
from models.io.registry import registered_name
|
from models.io.registry import registry
|
||||||
from models.io.training import TrainingRun
|
from models.io.storage import read_cohort, read_metadata
|
||||||
|
from models.io.tracking import TrainingRun
|
||||||
|
|
||||||
SETTINGS = tomllib.loads((Path(__file__).parent / "model.toml").read_text())
|
SETTINGS = tomllib.loads((Path(__file__).parent / "model.toml").read_text())
|
||||||
NORMAL = "NORMAL"
|
NORMAL = "NORMAL"
|
||||||
@@ -29,7 +29,17 @@ def cohort(cohort_path: str) -> pd.DataFrame:
|
|||||||
|
|
||||||
|
|
||||||
def lineage(cohort_path: str) -> dict:
|
def lineage(cohort_path: str) -> dict:
|
||||||
return cohort_lineage(cohort_path)
|
return read_metadata(cohort_path)
|
||||||
|
|
||||||
|
|
||||||
|
def cohort_sha256(cohort_path: str) -> str:
|
||||||
|
return file_sha256(cohort_path)
|
||||||
|
|
||||||
|
|
||||||
|
def code_sha256() -> str:
|
||||||
|
"""The hash of this folder's steps and settings: what says the model itself changed."""
|
||||||
|
folder = Path(__file__).parent
|
||||||
|
return file_sha256(folder / "model.py", folder / "model.toml")
|
||||||
|
|
||||||
|
|
||||||
def prepare(cohort: pd.DataFrame) -> pd.DataFrame:
|
def prepare(cohort: pd.DataFrame) -> pd.DataFrame:
|
||||||
@@ -75,22 +85,24 @@ def evaluate(train: pd.DataFrame, test: pd.DataFrame, predict: pd.Series) -> dic
|
|||||||
|
|
||||||
|
|
||||||
class Cin2Logistic(mlflow.pyfunc.PythonModel):
|
class Cin2Logistic(mlflow.pyfunc.PythonModel):
|
||||||
"""The registered artifact: takes a build's long frame and returns each member's probability."""
|
"""The registered artifact: takes a build's long frame and returns `pac_id`, `fecha_indice` and `probabilidad`."""
|
||||||
|
|
||||||
def __init__(self, fitted: LogisticRegression):
|
def __init__(self, fitted: LogisticRegression):
|
||||||
self.fitted = fitted
|
self.fitted = fitted
|
||||||
|
|
||||||
def predict(self, context, model_input, params=None):
|
def predict(self, context, model_input, params=None):
|
||||||
return predict(self.fitted, prepare(model_input))
|
members = prepare(model_input)
|
||||||
|
return members[["pac_id", "fecha_indice"]].assign(probabilidad=predict(self.fitted, members))
|
||||||
|
|
||||||
|
|
||||||
def registered_model(fit: LogisticRegression, evaluate: dict, lineage: dict, cohort_path: str, environment: str) -> str:
|
def registered_model(fit: LogisticRegression, evaluate: dict, lineage: dict, cohort_path: str, cohort_sha256: str,
|
||||||
|
code_sha256: str, environment: str) -> str:
|
||||||
"""Registers the fitted model and returns its version. The run keeps the file's path and hash, never its content."""
|
"""Registers the fitted model and returns its version. The run keeps the file's path and hash, never its content."""
|
||||||
run = TrainingRun(domain=SETTINGS["domain"], scenario=SETTINGS["scenario"], environment=environment,
|
run = TrainingRun(domain=SETTINGS["domain"], scenario=SETTINGS["scenario"], environment=environment,
|
||||||
cohorte_armado_id=int(lineage["armado_id"]))
|
cohorte_armado_id=int(lineage["armado_id"]))
|
||||||
run.log_model(Cin2Logistic(fit))
|
run.log_model(Cin2Logistic(fit))
|
||||||
version = run.finish(metrics=evaluate, hyperparameters={
|
run.finish(metrics=evaluate, hyperparameters={
|
||||||
"cohort_file": str(cohort_path), "cohort_sha256": hashlib.sha256(Path(cohort_path).read_bytes()).hexdigest()})
|
"cohort_file": str(cohort_path), "cohort_sha256": cohort_sha256, "code_sha256": code_sha256})
|
||||||
name = registered_name(SETTINGS["domain"], SETTINGS["scenario"])
|
version = registry.register_run(run)
|
||||||
run.client.update_model_version(name, version, description=SETTINGS["description"])
|
registry.set_description(SETTINGS["domain"], SETTINGS["scenario"], version, SETTINGS["description"])
|
||||||
return version
|
return version
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
"""The model's Hamilton driver."""
|
"""The model's Hamilton driver, and what makes repeating a training a no-op."""
|
||||||
|
|
||||||
from hamilton import driver
|
from hamilton import driver
|
||||||
|
|
||||||
from models.cacu.cin2_logistic import model
|
from models.cacu.cin2_logistic import model
|
||||||
|
from models.io.lineage import matches
|
||||||
|
from models.io.registry import registered_name, registry
|
||||||
|
|
||||||
|
|
||||||
def train(cohort_path: str, environment: str = "DEV") -> str:
|
def train(cohort_path: str, environment: str = "DEV") -> str:
|
||||||
@@ -10,3 +12,16 @@ def train(cohort_path: str, environment: str = "DEV") -> str:
|
|||||||
dr = driver.Builder().with_modules(model).build()
|
dr = driver.Builder().with_modules(model).build()
|
||||||
inputs = {"cohort_path": str(cohort_path), "environment": environment}
|
inputs = {"cohort_path": str(cohort_path), "environment": environment}
|
||||||
return dr.execute(["registered_model"], inputs=inputs)["registered_model"]
|
return dr.execute(["registered_model"], inputs=inputs)["registered_model"]
|
||||||
|
|
||||||
|
|
||||||
|
def find_trained(cohort_path: str, environment: str = "DEV") -> str | None:
|
||||||
|
"""The newest version not retired from the same file, code and environment."""
|
||||||
|
name = registered_name(model.SETTINGS["domain"], model.SETTINGS["scenario"])
|
||||||
|
expected = {"cohort_sha256": model.cohort_sha256(str(cohort_path)), "code_sha256": model.code_sha256()}
|
||||||
|
versions = sorted(registry.client.search_model_versions(f"name='{name}'"), key=lambda mv: int(mv.version), reverse=True)
|
||||||
|
for mv in versions:
|
||||||
|
if mv.tags.get("environment") != environment or mv.tags.get("retirada_en"):
|
||||||
|
continue
|
||||||
|
if matches(registry.client.get_run(mv.run_id).data.params, expected):
|
||||||
|
return str(mv.version)
|
||||||
|
return None
|
||||||
|
|||||||
@@ -1,66 +0,0 @@
|
|||||||
"""A cohort build's Parquet file: its columns, and reading it as a frame.
|
|
||||||
|
|
||||||
Long format: one row per member and event, with the member's index date on every row. A model gets the whole
|
|
||||||
frame and computes its own outcome and predictors from it; it never reads the database.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import pandas as pd
|
|
||||||
import pyarrow as pa
|
|
||||||
import pyarrow.parquet as pq
|
|
||||||
from sqlalchemy.engine import make_url
|
|
||||||
|
|
||||||
SCHEMA = pa.schema([
|
|
||||||
("pac_id", pa.int64()), ("fecha_indice", pa.date32()), ("fecha", pa.date32()),
|
|
||||||
("conocida_en", pa.timestamp("us", tz="UTC")), ("clase", pa.string()), ("tipo", pa.string()),
|
|
||||||
("codigo", pa.string()), ("valor_codigo", pa.string()), ("valor_numerico", pa.float64()),
|
|
||||||
("fuente_tabla", pa.string()), ("fuente_id", pa.string()),
|
|
||||||
])
|
|
||||||
|
|
||||||
|
|
||||||
class CohortFileError(ValueError):
|
|
||||||
"""The file isn't a cohort build: its columns or types aren't `SCHEMA`'s."""
|
|
||||||
|
|
||||||
|
|
||||||
def cohorts_root(database_url: str) -> Path:
|
|
||||||
"""`COHORTS_DIR`, or `cohorts/` next to the domain's SQLite file. Other engines have no such folder."""
|
|
||||||
if configured := os.environ.get("COHORTS_DIR"):
|
|
||||||
return Path(configured)
|
|
||||||
url = make_url(database_url)
|
|
||||||
if url.get_backend_name() != "sqlite" or not url.database:
|
|
||||||
raise ValueError("this database has no data folder: set COHORTS_DIR")
|
|
||||||
return Path(url.database.removeprefix("file:")).parent / "cohorts"
|
|
||||||
|
|
||||||
|
|
||||||
def cohort_path(root: Path, url: str, armado_id: int) -> Path:
|
|
||||||
domain, cohort = url.split("/", 1)
|
|
||||||
return root / domain / cohort / f"{armado_id}.parquet"
|
|
||||||
|
|
||||||
|
|
||||||
def find_cohort_file(root: Path, url: str, armado_id: int | None = None) -> Path:
|
|
||||||
"""The file of that build, or of the cohort's latest build that has a file."""
|
|
||||||
if armado_id is None:
|
|
||||||
builds = [int(file.stem) for file in cohort_path(root, url, 0).parent.glob("*.parquet") if file.stem.isdigit()]
|
|
||||||
if not builds:
|
|
||||||
raise FileNotFoundError(f"no exported builds of {url} under {root}")
|
|
||||||
armado_id = max(builds)
|
|
||||||
path = cohort_path(root, url, armado_id)
|
|
||||||
if not path.exists():
|
|
||||||
raise FileNotFoundError(f"build {armado_id} of {url} isn't exported: no {path}")
|
|
||||||
return path
|
|
||||||
|
|
||||||
|
|
||||||
def cohort_lineage(path: str | Path) -> dict[str, str]:
|
|
||||||
"""The lineage in the file's metadata, without reading any rows."""
|
|
||||||
metadata = pq.read_metadata(path).metadata
|
|
||||||
return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")}
|
|
||||||
|
|
||||||
|
|
||||||
def read_cohort(path: str | Path) -> pd.DataFrame:
|
|
||||||
"""The build's rows, after checking the file's schema without reading them."""
|
|
||||||
schema = pq.read_schema(path)
|
|
||||||
if not schema.equals(SCHEMA, check_metadata=False):
|
|
||||||
raise CohortFileError(f"{path} doesn't have a cohort build's columns: {schema.names}")
|
|
||||||
return pd.read_parquet(path)
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
"""The contract through which a model is asked for the risk of a cohort build's members.
|
|
||||||
|
|
||||||
The caller hands the estimator the wide frame of a cohort build, `(columns, rows)`, with
|
|
||||||
`columns = ["pac_id", "fecha_indice", <variables>]`. The estimator returns one `Risk` per member and
|
|
||||||
horizon, and its `Provenance`: the keys that reconcile a batch with MLflow (MLflow keeps no rows and no
|
|
||||||
patients).
|
|
||||||
|
|
||||||
`Risk` and `Provenance` keep the names of the columns they're saved to (`evaluacion_riesgo`,
|
|
||||||
`evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what Persistance's `PROCEDENCIA` expects.
|
|
||||||
|
|
||||||
This module doesn't import the kit, Persistance or the orchestration: it receives lists.
|
|
||||||
"""
|
|
||||||
|
|
||||||
from dataclasses import asdict, dataclass
|
|
||||||
from typing import NamedTuple, Protocol, runtime_checkable
|
|
||||||
|
|
||||||
|
|
||||||
class Risk(NamedTuple):
|
|
||||||
"""A member's risk at one horizon (FHIR `RiskAssessment.prediction`)."""
|
|
||||||
|
|
||||||
pac_id: int
|
|
||||||
horizonte_anios: float # years from the index date; 0 = prevalent
|
|
||||||
probabilidad: float # 0 to 1
|
|
||||||
ic_bajo: float | None = None
|
|
||||||
ic_alto: float | None = None
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
|
||||||
class Provenance:
|
|
||||||
"""Which model the risks come from: the keys a batch stores."""
|
|
||||||
|
|
||||||
modelo_nombre: str
|
|
||||||
modelo_version: str
|
|
||||||
mlflow_run_id: str
|
|
||||||
modelo_sha: str
|
|
||||||
|
|
||||||
def as_dict(self) -> dict[str, str]:
|
|
||||||
return asdict(self)
|
|
||||||
|
|
||||||
|
|
||||||
@runtime_checkable
|
|
||||||
class RiskEstimator(Protocol):
|
|
||||||
"""What every risk model the orchestration can call provides."""
|
|
||||||
|
|
||||||
cohort_url: str # the cohort whose frame it reads ("cacu/cohorte_vigilancia")
|
|
||||||
outcome: str # what it predicts ("cin2_mas")
|
|
||||||
|
|
||||||
def provenance(self) -> Provenance: ...
|
|
||||||
|
|
||||||
def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: ...
|
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
"""The shapes of the data the pipelines read and write. Nothing here reads or writes.
|
||||||
|
|
||||||
|
- A cohort build's Parquet file (`COHORT_SCHEMA`): long, one row per member and event, with the member's index date on
|
||||||
|
every row.
|
||||||
|
- A cohort as dbt compiled it (`ExclusionRule`, `CohortQueries`) and what building it gives (`BuiltCohort`).
|
||||||
|
- An estimate's output (`ESTIMATE_COLUMNS`): one row per member.
|
||||||
|
- The risk contract (`Risk`, `Provenance`, `RiskEstimator`). `RiskEstimator` takes the wide frame of a cohort build,
|
||||||
|
`(columns, rows)` with `columns = ["pac_id", "fecha_indice", <variables>]`. `Risk` and `Provenance` keep the names of
|
||||||
|
the columns they're saved to (`evaluacion_riesgo`, `evaluacion_riesgo_lote`), so `Provenance.as_dict()` is what
|
||||||
|
Persistance's `PROCEDENCIA` expects.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from dataclasses import asdict, dataclass
|
||||||
|
from datetime import date
|
||||||
|
from typing import NamedTuple, Protocol, runtime_checkable
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import pyarrow as pa
|
||||||
|
|
||||||
|
COHORT_SCHEMA = pa.schema([
|
||||||
|
("pac_id", pa.int64()), ("fecha_indice", pa.date32()), ("fecha", pa.date32()),
|
||||||
|
("conocida_en", pa.timestamp("us", tz="UTC")), ("clase", pa.string()), ("tipo", pa.string()),
|
||||||
|
("codigo", pa.string()), ("valor_codigo", pa.string()), ("valor_numerico", pa.float64()),
|
||||||
|
("fuente_tabla", pa.string()), ("fuente_id", pa.string()),
|
||||||
|
])
|
||||||
|
|
||||||
|
ESTIMATE_COLUMNS = ("pac_id", "fecha_indice", "probabilidad")
|
||||||
|
|
||||||
|
POPULATION, INDEX, EXCLUSION = "population", "index", "exclusion"
|
||||||
|
|
||||||
|
|
||||||
|
class CohortFileError(ValueError):
|
||||||
|
"""The file isn't a cohort build: its columns or types aren't `COHORT_SCHEMA`'s."""
|
||||||
|
|
||||||
|
|
||||||
|
class CohortDefinitionError(ValueError):
|
||||||
|
"""The cohort's queries or their results don't follow the structure a build chains."""
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ExclusionRule:
|
||||||
|
name: str
|
||||||
|
description: str
|
||||||
|
order: int
|
||||||
|
sql: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class CohortQueries:
|
||||||
|
url: str
|
||||||
|
all_patients: str
|
||||||
|
index_date: str
|
||||||
|
rules: tuple[ExclusionRule, ...]
|
||||||
|
cutoff: date
|
||||||
|
parameters: dict
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class BuiltCohort:
|
||||||
|
"""The study population (`pac_id`, `fecha_indice` and the index event) and the attrition, one row per step."""
|
||||||
|
|
||||||
|
study_population: pd.DataFrame
|
||||||
|
attrition: pd.DataFrame
|
||||||
|
|
||||||
|
|
||||||
|
class Risk(NamedTuple):
|
||||||
|
"""A member's risk at one horizon (FHIR `RiskAssessment.prediction`)."""
|
||||||
|
|
||||||
|
pac_id: int
|
||||||
|
horizonte_anios: float # years from the index date; 0 = prevalent
|
||||||
|
probabilidad: float # 0 to 1
|
||||||
|
ic_bajo: float | None = None
|
||||||
|
ic_alto: float | None = None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Provenance:
|
||||||
|
"""Which model the risks come from: the keys a batch stores."""
|
||||||
|
|
||||||
|
modelo_nombre: str
|
||||||
|
modelo_version: str
|
||||||
|
mlflow_run_id: str
|
||||||
|
modelo_sha: str
|
||||||
|
|
||||||
|
def as_dict(self) -> dict[str, str]:
|
||||||
|
return asdict(self)
|
||||||
|
|
||||||
|
|
||||||
|
@runtime_checkable
|
||||||
|
class RiskEstimator(Protocol):
|
||||||
|
"""What every risk model the orchestration can call provides."""
|
||||||
|
|
||||||
|
cohort_url: str # the cohort whose frame it reads ("cacu/cohorte_vigilancia")
|
||||||
|
outcome: str # what it predicts ("cin2_mas")
|
||||||
|
|
||||||
|
def provenance(self) -> Provenance: ...
|
||||||
|
|
||||||
|
def estimate(self, columns: list[str], rows: list[tuple]) -> list[Risk]: ...
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
"""ONNX checkpoint inspection (ML-01b, MLD-03).
|
|
||||||
|
|
||||||
Writing/storing a checkpoint is `models.io.training.TrainingRun.log_artifact`,
|
|
||||||
which hands it to MLflow directly — nothing here manages storage paths.
|
|
||||||
`onnx` is an optional dependency (`models[export]`); without it
|
|
||||||
`inspect_onnx_metadata` returns `{"available": False}`.
|
|
||||||
"""
|
|
||||||
from pathlib import Path
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
|
|
||||||
def inspect_onnx_metadata(path: str | Path) -> dict[str, Any]:
|
|
||||||
"""IR version, opsets, producer and graph inputs/outputs of a checkpoint.
|
|
||||||
`{"available": False}` when the optional `onnx` package isn't installed;
|
|
||||||
`ValueError` when it is and the file isn't a valid ONNX model."""
|
|
||||||
try:
|
|
||||||
import onnx
|
|
||||||
except ImportError:
|
|
||||||
return {"available": False, "reason": "el paquete 'onnx' no está instalado (extra 'export')"}
|
|
||||||
|
|
||||||
try:
|
|
||||||
model = onnx.load(str(path))
|
|
||||||
onnx.checker.check_model(model)
|
|
||||||
except Exception as exc:
|
|
||||||
raise ValueError(f"no es un modelo ONNX válido: {exc}") from exc
|
|
||||||
return {
|
|
||||||
"available": True,
|
|
||||||
"ir_version": model.ir_version,
|
|
||||||
"producer_name": model.producer_name,
|
|
||||||
"producer_version": model.producer_version,
|
|
||||||
"opset_imports": [{"domain": o.domain, "version": o.version} for o in model.opset_import],
|
|
||||||
"graph_inputs": [i.name for i in model.graph.input],
|
|
||||||
"graph_outputs": [o.name for o in model.graph.output],
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
"""What each output came from, in one vocabulary for files, runs and versions: the names models are registered under,
|
||||||
|
the keys lineage is recorded with, the hashes that identify code, data and models, and the rule that an output already
|
||||||
|
exists when its recorded lineage matches what's expected.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pyarrow as pa
|
||||||
|
|
||||||
|
DOMAINS = ("cacu", "cama", "tea")
|
||||||
|
ARMADO_TAG = "kit.armado_id"
|
||||||
|
MODEL_SHA_TAG = "modelo_sha"
|
||||||
|
GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets
|
||||||
|
GIT_DIRTY_TAG = "models.git.dirty"
|
||||||
|
GIT_COMMIT_ENV = "MODELS_GIT_COMMIT"
|
||||||
|
|
||||||
|
|
||||||
|
def registered_name(domain: str, scenario: str) -> str:
|
||||||
|
return f"{domain}-{scenario}"
|
||||||
|
|
||||||
|
|
||||||
|
def code_version() -> dict[str, str]:
|
||||||
|
"""The git commit of this package's repository and whether tracked files have uncommitted changes.
|
||||||
|
Without a repository (a delivered image), the commit comes from `MODELS_GIT_COMMIT`; with neither,
|
||||||
|
nothing is recorded."""
|
||||||
|
root = Path(__file__).resolve().parent
|
||||||
|
try:
|
||||||
|
commit = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True,
|
||||||
|
check=True).stdout.strip()
|
||||||
|
changes = subprocess.run(["git", "-C", str(root), "status", "--porcelain", "--untracked-files=no"],
|
||||||
|
capture_output=True, text=True, check=True).stdout.strip()
|
||||||
|
except (OSError, subprocess.CalledProcessError):
|
||||||
|
commit = os.environ.get(GIT_COMMIT_ENV)
|
||||||
|
return {GIT_COMMIT_TAG: commit} if commit else {}
|
||||||
|
return {GIT_COMMIT_TAG: commit, GIT_DIRTY_TAG: str(bool(changes)).lower()}
|
||||||
|
|
||||||
|
|
||||||
|
def model_sha(model_dir: str | Path) -> str:
|
||||||
|
"""sha256 of a saved pyfunc's `python_model.pkl`: its preparation and fitted model. `MLmodel` is left
|
||||||
|
out because it carries ids and dates, so the same model saved twice has the same sha."""
|
||||||
|
return hashlib.sha256((Path(model_dir) / "python_model.pkl").read_bytes()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def file_sha256(*paths: str | Path) -> str:
|
||||||
|
"""The hash of these files' bytes, in this order."""
|
||||||
|
digest = hashlib.sha256()
|
||||||
|
for path in paths:
|
||||||
|
digest.update(Path(path).read_bytes())
|
||||||
|
return digest.hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def table_sha256(table: pa.Table) -> str:
|
||||||
|
"""The hash of a table's rows and types, leaving its metadata out, so the same content always hashes the same."""
|
||||||
|
sink = pa.BufferOutputStream()
|
||||||
|
table = table.replace_schema_metadata(None)
|
||||||
|
with pa.ipc.new_stream(sink, table.schema) as stream:
|
||||||
|
stream.write_table(table)
|
||||||
|
return hashlib.sha256(sink.getvalue().to_pybytes()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def matches(recorded: dict, expected: dict) -> bool:
|
||||||
|
"""Whether an output's recorded lineage has every expected value: then it is already done."""
|
||||||
|
return all(str(recorded.get(key)) == str(value) for key, value in expected.items())
|
||||||
|
|
||||||
|
|
||||||
|
def require_match(recorded: dict, expected: dict, what: str) -> None:
|
||||||
|
"""Refuses an output whose recorded lineage disagrees with what's expected of it."""
|
||||||
|
if not matches(recorded, expected):
|
||||||
|
raise ValueError(f"{what} doesn't belong to the build expected ({expected}): {recorded}")
|
||||||
@@ -1,132 +0,0 @@
|
|||||||
"""MLD-4/MLD-5: every prediction is stored with the MLflow model version that
|
|
||||||
produced it. Callers go through `PredictionService` rather than calling
|
|
||||||
`model.predict(...)` directly.
|
|
||||||
"""
|
|
||||||
import hashlib
|
|
||||||
import json
|
|
||||||
from collections.abc import Callable
|
|
||||||
from dataclasses import dataclass
|
|
||||||
from typing import Any, Protocol
|
|
||||||
|
|
||||||
from core.governance.models import ModelPrediction
|
|
||||||
from mlflow import MlflowException
|
|
||||||
from persistance.governance import model_prediction_repository
|
|
||||||
|
|
||||||
from models.io.registry import PRODUCTION_ALIAS, registered_name, registry
|
|
||||||
|
|
||||||
|
|
||||||
class Predictor(Protocol):
|
|
||||||
"""What the service needs from a model."""
|
|
||||||
|
|
||||||
def predict(self, data: Any) -> Any: ...
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class Interpretability:
|
|
||||||
"""MLD-03: the minimum a prediction reports for clinical interpretation.
|
|
||||||
Each model fills the ones its method has (odds ratio for a logistic
|
|
||||||
regression, hazard ratio for a survival model)."""
|
|
||||||
|
|
||||||
odds_ratio: float | None = None
|
|
||||||
hazard_ratio: float | None = None
|
|
||||||
probabilidad_acumulada: float | None = None
|
|
||||||
|
|
||||||
def to_json(self) -> str:
|
|
||||||
return json.dumps(
|
|
||||||
{
|
|
||||||
"odds_ratio": self.odds_ratio,
|
|
||||||
"hazard_ratio": self.hazard_ratio,
|
|
||||||
"probabilidad_acumulada": self.probabilidad_acumulada,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class ApplicabilityRejected(Exception):
|
|
||||||
"""Raised when the EL-04b applicability gate rejects a row. Callers
|
|
||||||
should report it as a client error (4xx), not a server error."""
|
|
||||||
|
|
||||||
|
|
||||||
class PredictionService:
|
|
||||||
"""Runs a model and records its predictions against the
|
|
||||||
MLflow version holding the `produccion` alias for `(domain, scenario)`.
|
|
||||||
|
|
||||||
If `aplicable` is given, each row (a dict of fields) is checked with it
|
|
||||||
(EL-04b). Inapplicable rows are still scored but stored with
|
|
||||||
`applicability_passed=False`, unless `reject_inapplicable` is set.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(
|
|
||||||
self,
|
|
||||||
model: Predictor,
|
|
||||||
*,
|
|
||||||
domain: str,
|
|
||||||
scenario: str,
|
|
||||||
aplicable: Callable[[dict], bool] | None = None,
|
|
||||||
reject_inapplicable: bool = False,
|
|
||||||
):
|
|
||||||
self.model = model
|
|
||||||
self.domain = domain
|
|
||||||
self.scenario = scenario
|
|
||||||
self.aplicable = aplicable
|
|
||||||
self.reject_inapplicable = reject_inapplicable
|
|
||||||
|
|
||||||
def active_model_version(self):
|
|
||||||
"""The MLflow model version currently holding the `produccion`
|
|
||||||
alias for this (domain, scenario), or `None`."""
|
|
||||||
name = registered_name(self.domain, self.scenario)
|
|
||||||
try:
|
|
||||||
return registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
|
||||||
except MlflowException:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def predict_and_record(
|
|
||||||
self,
|
|
||||||
data: Any,
|
|
||||||
*,
|
|
||||||
pac_id_hospital: str,
|
|
||||||
episodio_id: int | None = None,
|
|
||||||
interpretability: Interpretability | None = None,
|
|
||||||
) -> ModelPrediction:
|
|
||||||
"""Scores `data` and stores the result (MLD-5) tagged with the active
|
|
||||||
MLflow model version (MLD-4). `NotImplementedError` from the model is
|
|
||||||
propagated unchanged.
|
|
||||||
"""
|
|
||||||
applicability_passed = True
|
|
||||||
if self.aplicable is not None:
|
|
||||||
if not isinstance(data, dict):
|
|
||||||
raise TypeError("the applicability check needs the input as a dict of fields")
|
|
||||||
applicability_passed = self.aplicable(data)
|
|
||||||
if not applicability_passed and self.reject_inapplicable:
|
|
||||||
raise ApplicabilityRejected(
|
|
||||||
f"la fila de {pac_id_hospital} no cumple los criterios de aplicabilidad de producción (EL-04b)"
|
|
||||||
)
|
|
||||||
|
|
||||||
# Predict first, so an unimplemented model raises NotImplementedError
|
|
||||||
# even when no version is in production.
|
|
||||||
output = self.model.predict(data)
|
|
||||||
|
|
||||||
model_version = self.active_model_version()
|
|
||||||
if model_version is None:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; "
|
|
||||||
"promueva una con models.io.registry.registry.promote antes de predecir"
|
|
||||||
)
|
|
||||||
|
|
||||||
input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest()
|
|
||||||
prediction = model_prediction_repository.create(
|
|
||||||
ModelPrediction(
|
|
||||||
mlflow_run_id=model_version.run_id,
|
|
||||||
modelo_nombre=model_version.name,
|
|
||||||
modelo_version=str(model_version.version),
|
|
||||||
domain=self.domain,
|
|
||||||
pac_id_hospital=pac_id_hospital,
|
|
||||||
episodio_id=episodio_id,
|
|
||||||
input_hash=input_hash,
|
|
||||||
output=json.dumps(output, default=str),
|
|
||||||
prediccion=str(output) if not isinstance(output, (dict, list)) else None,
|
|
||||||
confianza=output.get("confianza") if isinstance(output, dict) else None,
|
|
||||||
interpretability=interpretability.to_json() if interpretability else None,
|
|
||||||
applicability_passed=applicability_passed,
|
|
||||||
)
|
|
||||||
)
|
|
||||||
return prediction
|
|
||||||
+155
-16
@@ -1,7 +1,9 @@
|
|||||||
"""Model registry: a thin layer over MLflow's own registry (ML-01b, ML-02,
|
"""Model registry: a thin layer over MLflow's own registry (ML-01b, ML-02,
|
||||||
ML-03, MLD-01, MLD-01b, MLD-03, MLD-4), adding only what MLflow doesn't know
|
ML-03, MLD-01, MLD-01b, MLD-03, MLD-4), adding only what MLflow doesn't know
|
||||||
about on its own: the promotion checks tied to the cohort a version was
|
about on its own: the promotion checks tied to the cohort a version was
|
||||||
trained on and to the validation-report convention.
|
trained on and to the validation-report convention, and `PredictionService`,
|
||||||
|
which stores each single prediction with the version in production (MLD-4/5,
|
||||||
|
EL-04b).
|
||||||
|
|
||||||
Training, versioning, artifact storage and stage live in MLflow itself
|
Training, versioning, artifact storage and stage live in MLflow itself
|
||||||
(`MLFLOW_TRACKING_URI`, the usual MLflow env var). A registered model is
|
(`MLFLOW_TRACKING_URI`, the usual MLflow env var). A registered model is
|
||||||
@@ -11,26 +13,28 @@ Cohorts are the indicator kit's builds (`cohorte_armado` in each domain's
|
|||||||
database). A version points to its build with the `kit.armado_id` tag, and
|
database). A version points to its build with the `kit.armado_id` tag, and
|
||||||
the kit's risk batches point back by `mlflow_run_id`; neither copies rows.
|
the kit's risk batches point back by `mlflow_run_id`; neither copies rows.
|
||||||
"""
|
"""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
import re
|
import re
|
||||||
import tempfile
|
import tempfile
|
||||||
|
from collections.abc import Callable
|
||||||
from dataclasses import asdict, dataclass
|
from dataclasses import asdict, dataclass
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from importlib import import_module
|
from importlib import import_module
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any, Protocol
|
||||||
|
|
||||||
from core.governance.enums import ArtifactKind, Environment
|
from core.governance.enums import ArtifactKind, Environment
|
||||||
|
from core.governance.models import ModelPrediction
|
||||||
from mlflow import MlflowClient, MlflowException
|
from mlflow import MlflowClient, MlflowException
|
||||||
from persistance.governance import model_prediction_repository
|
from persistance.governance import model_prediction_repository
|
||||||
from sqlmodel import select
|
from sqlmodel import select
|
||||||
|
|
||||||
from models.io.export import inspect_onnx_metadata
|
from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, registered_name
|
||||||
|
from models.io.tracking import MODEL_PATH, TrainingRun, inspect_onnx_metadata, log_artifact_file
|
||||||
|
|
||||||
DOMAINS = ("cacu", "cama", "tea")
|
|
||||||
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
|
REPORT_TAGS = ("technical_validation_report_uri", "clinical_validation_report_uri", "interpretability_report_uri")
|
||||||
PRODUCTION_ALIAS = "produccion"
|
PRODUCTION_ALIAS = "produccion"
|
||||||
ARMADO_TAG = "kit.armado_id"
|
|
||||||
MODEL_SHA_TAG = "modelo_sha"
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
@@ -48,10 +52,6 @@ class PromotionBlocked(Exception):
|
|||||||
super().__init__(f"la versión no cumple: {failed}")
|
super().__init__(f"la versión no cumple: {failed}")
|
||||||
|
|
||||||
|
|
||||||
def registered_name(domain: str, scenario: str) -> str:
|
|
||||||
return f"{domain}-{scenario}"
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
class ResolvedVersion:
|
class ResolvedVersion:
|
||||||
"""The version a caller will use, with what it needs to load it and to say where risks came from.
|
"""The version a caller will use, with what it needs to load it and to say where risks came from.
|
||||||
@@ -141,12 +141,34 @@ class ModelRegistry:
|
|||||||
hyperparameters: dict[str, Any] | None = None,
|
hyperparameters: dict[str, Any] | None = None,
|
||||||
**reports: str | None,
|
**reports: str | None,
|
||||||
) -> str:
|
) -> str:
|
||||||
"""For training code that runs elsewhere and reports over the API.
|
"""For training code that runs elsewhere and reports over the API: a run with these metrics, registered.
|
||||||
In-process training uses `models.io.training.TrainingRun` directly."""
|
In-process training opens its own `TrainingRun` and calls `register_run`."""
|
||||||
from models.io.training import TrainingRun
|
|
||||||
|
|
||||||
run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohorte_armado_id=cohorte_armado_id)
|
run = TrainingRun(domain=domain, scenario=scenario, environment=environment, cohorte_armado_id=cohorte_armado_id)
|
||||||
return run.finish(metrics=metrics, hyperparameters=hyperparameters, **reports)
|
return self.register_run(run.finish(metrics=metrics, hyperparameters=hyperparameters), **reports)
|
||||||
|
|
||||||
|
def register_run(self, run: TrainingRun, **reports: str | None) -> str:
|
||||||
|
"""Registers a run as a new version of `<domain>-<scenario>`, tagged with the promotion inputs (environment,
|
||||||
|
cohort link, `modelo_sha`, report URIs), and returns the version."""
|
||||||
|
unknown = set(reports) - set(REPORT_TAGS)
|
||||||
|
if unknown:
|
||||||
|
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
|
||||||
|
name = registered_name(run.domain, run.scenario)
|
||||||
|
try:
|
||||||
|
self.client.create_registered_model(name)
|
||||||
|
except MlflowException as exc:
|
||||||
|
if exc.error_code != "RESOURCE_ALREADY_EXISTS":
|
||||||
|
raise
|
||||||
|
version_tags = {"domain": run.domain, "scenario": run.scenario, "environment": run.environment.value}
|
||||||
|
if run.cohorte_armado_id is not None:
|
||||||
|
version_tags[ARMADO_TAG] = str(run.cohorte_armado_id)
|
||||||
|
if run.modelo_sha is not None:
|
||||||
|
version_tags[MODEL_SHA_TAG] = run.modelo_sha
|
||||||
|
version_tags.update({key: uri for key, uri in reports.items() if uri})
|
||||||
|
source = f"runs:/{run.run_id}/{MODEL_PATH}" if run.modelo_sha is not None else f"runs:/{run.run_id}"
|
||||||
|
return str(self.client.create_model_version(name, source=source, run_id=run.run_id, tags=version_tags).version)
|
||||||
|
|
||||||
|
def set_description(self, domain: str, scenario: str, version: str, description: str) -> None:
|
||||||
|
self.client.update_model_version(registered_name(domain, scenario), version, description=description)
|
||||||
|
|
||||||
def attach_reports(self, domain: str, scenario: str, version: str, **reports: str | None) -> None:
|
def attach_reports(self, domain: str, scenario: str, version: str, **reports: str | None) -> None:
|
||||||
"""MLD-01/01b/03 documents are usually written after training."""
|
"""MLD-01/01b/03 documents are usually written after training."""
|
||||||
@@ -169,7 +191,7 @@ class ModelRegistry:
|
|||||||
path.write_bytes(data)
|
path.write_bytes(data)
|
||||||
if kind_value == ArtifactKind.ONNX_CHECKPOINT.value:
|
if kind_value == ArtifactKind.ONNX_CHECKPOINT.value:
|
||||||
inspect_onnx_metadata(path) # raises ValueError on an invalid checkpoint
|
inspect_onnx_metadata(path) # raises ValueError on an invalid checkpoint
|
||||||
self.client.log_artifact(mv.run_id, str(path), artifact_path=kind_value)
|
log_artifact_file(self.client, mv.run_id, kind_value, path)
|
||||||
|
|
||||||
def _describe(self, mv) -> dict[str, Any]:
|
def _describe(self, mv) -> dict[str, Any]:
|
||||||
run = self.client.get_run(mv.run_id)
|
run = self.client.get_run(mv.run_id)
|
||||||
@@ -280,3 +302,120 @@ def _armado(domain: str, armado_id: str | None) -> tuple[dict | None, list[dict]
|
|||||||
"n_miembros": armado.n_miembros, "datos_as_of": armado.datos_as_of.isoformat(),
|
"n_miembros": armado.n_miembros, "datos_as_of": armado.datos_as_of.isoformat(),
|
||||||
"armado_en": armado.armado_en.isoformat()},
|
"armado_en": armado.armado_en.isoformat()},
|
||||||
[{"orden": p.orden, "paso": p.paso, "n": p.n} for p in pasos])
|
[{"orden": p.orden, "paso": p.paso, "n": p.n} for p in pasos])
|
||||||
|
|
||||||
|
|
||||||
|
class Predictor(Protocol):
|
||||||
|
"""What the service needs from a model."""
|
||||||
|
|
||||||
|
def predict(self, data: Any) -> Any: ...
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Interpretability:
|
||||||
|
"""MLD-03: the minimum a prediction reports for clinical interpretation.
|
||||||
|
Each model fills the ones its method has (odds ratio for a logistic
|
||||||
|
regression, hazard ratio for a survival model)."""
|
||||||
|
|
||||||
|
odds_ratio: float | None = None
|
||||||
|
hazard_ratio: float | None = None
|
||||||
|
probabilidad_acumulada: float | None = None
|
||||||
|
|
||||||
|
def to_json(self) -> str:
|
||||||
|
return json.dumps(
|
||||||
|
{
|
||||||
|
"odds_ratio": self.odds_ratio,
|
||||||
|
"hazard_ratio": self.hazard_ratio,
|
||||||
|
"probabilidad_acumulada": self.probabilidad_acumulada,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class ApplicabilityRejected(Exception):
|
||||||
|
"""Raised when the EL-04b applicability gate rejects a row. Callers
|
||||||
|
should report it as a client error (4xx), not a server error."""
|
||||||
|
|
||||||
|
|
||||||
|
class PredictionService:
|
||||||
|
"""Runs a model and records its predictions against the
|
||||||
|
MLflow version holding the `produccion` alias for `(domain, scenario)`.
|
||||||
|
|
||||||
|
If `aplicable` is given, each row (a dict of fields) is checked with it
|
||||||
|
(EL-04b). Inapplicable rows are still scored but stored with
|
||||||
|
`applicability_passed=False`, unless `reject_inapplicable` is set.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
model: Predictor,
|
||||||
|
*,
|
||||||
|
domain: str,
|
||||||
|
scenario: str,
|
||||||
|
aplicable: Callable[[dict], bool] | None = None,
|
||||||
|
reject_inapplicable: bool = False,
|
||||||
|
):
|
||||||
|
self.model = model
|
||||||
|
self.domain = domain
|
||||||
|
self.scenario = scenario
|
||||||
|
self.aplicable = aplicable
|
||||||
|
self.reject_inapplicable = reject_inapplicable
|
||||||
|
|
||||||
|
def active_model_version(self):
|
||||||
|
"""The MLflow model version currently holding the `produccion`
|
||||||
|
alias for this (domain, scenario), or `None`."""
|
||||||
|
name = registered_name(self.domain, self.scenario)
|
||||||
|
try:
|
||||||
|
return registry.client.get_model_version_by_alias(name, PRODUCTION_ALIAS)
|
||||||
|
except MlflowException:
|
||||||
|
return None
|
||||||
|
|
||||||
|
def predict_and_record(
|
||||||
|
self,
|
||||||
|
data: Any,
|
||||||
|
*,
|
||||||
|
pac_id_hospital: str,
|
||||||
|
episodio_id: int | None = None,
|
||||||
|
interpretability: Interpretability | None = None,
|
||||||
|
) -> ModelPrediction:
|
||||||
|
"""Scores `data` and stores the result (MLD-5) tagged with the active
|
||||||
|
MLflow model version (MLD-4). `NotImplementedError` from the model is
|
||||||
|
propagated unchanged.
|
||||||
|
"""
|
||||||
|
applicability_passed = True
|
||||||
|
if self.aplicable is not None:
|
||||||
|
if not isinstance(data, dict):
|
||||||
|
raise TypeError("the applicability check needs the input as a dict of fields")
|
||||||
|
applicability_passed = self.aplicable(data)
|
||||||
|
if not applicability_passed and self.reject_inapplicable:
|
||||||
|
raise ApplicabilityRejected(
|
||||||
|
f"la fila de {pac_id_hospital} no cumple los criterios de aplicabilidad de producción (EL-04b)"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Predict first, so an unimplemented model raises NotImplementedError
|
||||||
|
# even when no version is in production.
|
||||||
|
output = self.model.predict(data)
|
||||||
|
|
||||||
|
model_version = self.active_model_version()
|
||||||
|
if model_version is None:
|
||||||
|
raise RuntimeError(
|
||||||
|
f"no hay una versión en producción para ({self.domain}, {self.scenario}) en MLflow; "
|
||||||
|
"promueva una con registry.promote antes de predecir"
|
||||||
|
)
|
||||||
|
|
||||||
|
input_hash = hashlib.sha256(json.dumps(data, default=str, sort_keys=True).encode("utf-8")).hexdigest()
|
||||||
|
prediction = model_prediction_repository.create(
|
||||||
|
ModelPrediction(
|
||||||
|
mlflow_run_id=model_version.run_id,
|
||||||
|
modelo_nombre=model_version.name,
|
||||||
|
modelo_version=str(model_version.version),
|
||||||
|
domain=self.domain,
|
||||||
|
pac_id_hospital=pac_id_hospital,
|
||||||
|
episodio_id=episodio_id,
|
||||||
|
input_hash=input_hash,
|
||||||
|
output=json.dumps(output, default=str),
|
||||||
|
prediccion=str(output) if not isinstance(output, (dict, list)) else None,
|
||||||
|
confianza=output.get("confianza") if isinstance(output, dict) else None,
|
||||||
|
interpretability=interpretability.to_json() if interpretability else None,
|
||||||
|
applicability_passed=applicability_passed,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return prediction
|
||||||
|
|||||||
@@ -1,14 +0,0 @@
|
|||||||
"""Finds a domain's Persistance repository by name, the same objects WebApi writes with."""
|
|
||||||
import importlib
|
|
||||||
|
|
||||||
from persistance.repository import Repository
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_repository(domain: str, entity: str) -> Repository:
|
|
||||||
"""`entity` is the repository's name in `persistance.<domain>` without
|
|
||||||
the suffix, e.g. `"paciente"`, `"citologia_cervical"`."""
|
|
||||||
module = importlib.import_module(f"persistance.{domain}")
|
|
||||||
try:
|
|
||||||
return getattr(module, f"{entity}_repository")
|
|
||||||
except AttributeError as exc:
|
|
||||||
raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc
|
|
||||||
@@ -0,0 +1,171 @@
|
|||||||
|
"""Where the pipelines' data lives and how it's read and written: Parquet files (cohort builds and estimates), dbt's
|
||||||
|
manifest, and a domain's Persistance repositories.
|
||||||
|
|
||||||
|
The kit's builds are `<root>/<domain>/<cohort>/<armado_id>.parquet`. The builds of dbt's rules go in a `dbt/` folder
|
||||||
|
beside them, numbered in order, so a lookup of the kit's builds never picks one up. Persistance is imported only where a
|
||||||
|
repository is used, so a model folder reading its cohort file never loads the database layer.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import importlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import tempfile
|
||||||
|
from datetime import date
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import pyarrow as pa
|
||||||
|
import pyarrow.parquet as pq
|
||||||
|
from sqlalchemy.engine import make_url
|
||||||
|
|
||||||
|
from models.io.contracts import (COHORT_SCHEMA, EXCLUSION, INDEX, POPULATION, CohortDefinitionError, CohortFileError,
|
||||||
|
CohortQueries, ExclusionRule)
|
||||||
|
|
||||||
|
|
||||||
|
def cohorts_root(database_url: str) -> Path:
|
||||||
|
"""`COHORTS_DIR`, or `cohorts/` next to the domain's SQLite file. Other engines have no such folder."""
|
||||||
|
if configured := os.environ.get("COHORTS_DIR"):
|
||||||
|
return Path(configured)
|
||||||
|
url = make_url(database_url)
|
||||||
|
if url.get_backend_name() != "sqlite" or not url.database:
|
||||||
|
raise ValueError("this database has no data folder: set COHORTS_DIR")
|
||||||
|
return Path(url.database).parent / "cohorts"
|
||||||
|
|
||||||
|
|
||||||
|
def cohort_path(root: Path, url: str, armado_id: int) -> Path:
|
||||||
|
domain, cohort = url.split("/", 1)
|
||||||
|
return root / domain / cohort / f"{armado_id}.parquet"
|
||||||
|
|
||||||
|
|
||||||
|
def dbt_build_path(root: Path, url: str, number: int) -> Path:
|
||||||
|
return cohort_path(root, url, number).parent / "dbt" / f"{number}.parquet"
|
||||||
|
|
||||||
|
|
||||||
|
def _numbers(folder: Path) -> list[int]:
|
||||||
|
return sorted(int(file.stem) for file in folder.glob("*.parquet") if file.stem.isdigit())
|
||||||
|
|
||||||
|
|
||||||
|
def latest_dbt_build(root: Path, url: str) -> tuple[int, Path] | None:
|
||||||
|
"""The highest-numbered build of dbt's rules, or `None` if there's none."""
|
||||||
|
numbers = _numbers(dbt_build_path(root, url, 0).parent)
|
||||||
|
return (numbers[-1], dbt_build_path(root, url, numbers[-1])) if numbers else None
|
||||||
|
|
||||||
|
|
||||||
|
def find_cohort_file(root: Path, url: str, armado_id: int | None = None) -> Path:
|
||||||
|
"""The file of that build, or of the cohort's latest build that has a file."""
|
||||||
|
if armado_id is None:
|
||||||
|
builds = _numbers(cohort_path(root, url, 0).parent)
|
||||||
|
if not builds:
|
||||||
|
raise FileNotFoundError(f"no exported builds of {url} under {root}")
|
||||||
|
armado_id = max(builds)
|
||||||
|
path = cohort_path(root, url, armado_id)
|
||||||
|
if not path.exists():
|
||||||
|
raise FileNotFoundError(f"build {armado_id} of {url} isn't exported: no {path}")
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def read_cohort(path: str | Path) -> pd.DataFrame:
|
||||||
|
"""The build's rows, after checking the file's schema without reading them."""
|
||||||
|
schema = pq.read_schema(path)
|
||||||
|
if not schema.equals(COHORT_SCHEMA, check_metadata=False):
|
||||||
|
raise CohortFileError(f"{path} doesn't have a cohort build's columns: {schema.names}")
|
||||||
|
return pd.read_parquet(path)
|
||||||
|
|
||||||
|
|
||||||
|
def write_once(table: pa.Table, path: Path) -> None:
|
||||||
|
"""The file appears complete or not at all: written beside it, then renamed."""
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".tmp", delete=False) as handle:
|
||||||
|
partial = Path(handle.name)
|
||||||
|
try:
|
||||||
|
pq.write_table(table, partial)
|
||||||
|
partial.replace(path)
|
||||||
|
finally:
|
||||||
|
partial.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
def read_metadata(path: str | Path) -> dict[str, str]:
|
||||||
|
"""A Parquet file's own metadata, without reading any rows."""
|
||||||
|
metadata = pq.read_metadata(path).metadata or {}
|
||||||
|
return {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")}
|
||||||
|
|
||||||
|
|
||||||
|
def _one(nodes: list[dict], kind: str, url: str) -> dict:
|
||||||
|
found = [node for node in nodes if node["config"]["meta"]["kind"] == kind]
|
||||||
|
if len(found) != 1:
|
||||||
|
raise CohortDefinitionError(f"{url} needs exactly one `{kind}` query, not {len(found)}")
|
||||||
|
return found[0]
|
||||||
|
|
||||||
|
|
||||||
|
def _compiled(node: dict) -> str:
|
||||||
|
if not node.get("compiled_code"):
|
||||||
|
raise CohortDefinitionError(f"{node['name']} has no compiled SQL in the manifest: run `dbt compile`")
|
||||||
|
return node["compiled_code"]
|
||||||
|
|
||||||
|
|
||||||
|
def read_queries(manifest: str | Path, url: str) -> CohortQueries:
|
||||||
|
"""The cohort's compiled queries, with its exclusions in their `order`.
|
||||||
|
|
||||||
|
An exclusion may read only the index query and the data, never another of the cohort's queries: that keeps every
|
||||||
|
rule's excluded members, and the study population, independent of the order.
|
||||||
|
"""
|
||||||
|
nodes = json.loads(Path(manifest).read_text())["nodes"].values()
|
||||||
|
nodes = [node for node in nodes if node.get("config", {}).get("meta", {}).get("cohort") == url]
|
||||||
|
if not nodes:
|
||||||
|
raise CohortDefinitionError(f"{manifest} has no queries of the cohort {url}")
|
||||||
|
population, index = _one(nodes, POPULATION, url), _one(nodes, INDEX, url)
|
||||||
|
exclusions = [node for node in nodes if node["config"]["meta"]["kind"] == EXCLUSION]
|
||||||
|
if not exclusions:
|
||||||
|
raise CohortDefinitionError(f"{url} has no `{EXCLUSION}` queries")
|
||||||
|
orders = [node["config"]["meta"]["order"] for node in exclusions]
|
||||||
|
if len(set(orders)) != len(orders):
|
||||||
|
raise CohortDefinitionError(f"{url} repeats an `order` among its exclusions: {sorted(orders)}")
|
||||||
|
steps = {node["unique_id"] for node in nodes} - {index["unique_id"]}
|
||||||
|
for node in exclusions:
|
||||||
|
if read := steps & set(node["depends_on"]["nodes"]):
|
||||||
|
raise CohortDefinitionError(f"{node['name']} may only read the index date and the data, and reads {sorted(read)}")
|
||||||
|
meta = population["config"]["meta"]
|
||||||
|
if "cutoff" not in meta:
|
||||||
|
raise CohortDefinitionError(f"the population query of {url} has no `cutoff` in its meta")
|
||||||
|
rules = (ExclusionRule(node["config"]["meta"]["name"], node["description"], node["config"]["meta"]["order"], _compiled(node))
|
||||||
|
for node in exclusions)
|
||||||
|
return CohortQueries(url, _compiled(population), _compiled(index), tuple(sorted(rules, key=lambda rule: rule.order)),
|
||||||
|
date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}")))
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_repository(domain: str, entity: str):
|
||||||
|
"""`entity` is the repository's name in `persistance.<domain>` without
|
||||||
|
the suffix, e.g. `"paciente"`, `"citologia_cervical"`."""
|
||||||
|
module = importlib.import_module(f"persistance.{domain}")
|
||||||
|
try:
|
||||||
|
return getattr(module, f"{entity}_repository")
|
||||||
|
except AttributeError as exc:
|
||||||
|
raise ValueError(f"persistance.{domain} has no {entity}_repository") from exc
|
||||||
|
|
||||||
|
|
||||||
|
class ReadOnlyRepository:
|
||||||
|
"""ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`.
|
||||||
|
Write methods raise `PermissionError` so a training routine cannot
|
||||||
|
modify clinical data."""
|
||||||
|
|
||||||
|
_WRITE_METHODS = {"create", "bulk_upsert", "open_session"}
|
||||||
|
|
||||||
|
def __init__(self, repository):
|
||||||
|
self._repository = repository
|
||||||
|
self.model = repository.model
|
||||||
|
|
||||||
|
def get(self, id_):
|
||||||
|
return self._repository.get(id_)
|
||||||
|
|
||||||
|
def list(self, *, limit: int = 100, offset: int = 0, **filters):
|
||||||
|
return self._repository.list(limit=limit, offset=offset, **filters)
|
||||||
|
|
||||||
|
def count(self, **filters) -> int:
|
||||||
|
return self._repository.count(**filters)
|
||||||
|
|
||||||
|
def __getattr__(self, name: str):
|
||||||
|
if name in self._WRITE_METHODS:
|
||||||
|
raise PermissionError(
|
||||||
|
f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository."
|
||||||
|
)
|
||||||
|
raise AttributeError(name)
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
"""Bookkeeping around a training run (ML-01..ML-05).
|
"""MLflow runs: what happened in one execution (ML-01..ML-05).
|
||||||
|
|
||||||
Does not train anything. It opens an MLflow run, records which cohort
|
Does not train anything. It opens an MLflow run, records which cohort
|
||||||
build fed it (ML-03), the artifacts it produced (ML-01a/b), keeps data
|
build fed it (ML-03), the artifacts it produced (ML-01a/b), keeps data
|
||||||
access read-only (ML-04) and tags the run as dev or prod (ML-02); MLflow
|
access read-only (ML-04) and tags the run as dev or prod (ML-02); MLflow
|
||||||
stores the run, metrics and artifacts. It uses `MlflowClient`'s run-scoped
|
stores the run, metrics and artifacts. Turning a run into a registered
|
||||||
|
version is `models.io.registry`'s. It uses `MlflowClient`'s run-scoped
|
||||||
methods instead of the fluent API's global active run, so two runs in one
|
methods instead of the fluent API's global active run, so two runs in one
|
||||||
process never interfere.
|
process never interfere.
|
||||||
|
|
||||||
@@ -18,77 +19,55 @@ uncommitted changes (`MODELS_GIT_COMMIT` where there's no repository, as in the
|
|||||||
delivered images). A PROD run only logs models whose class lives in a module, at a
|
delivered images). A PROD run only logs models whose class lives in a module, at a
|
||||||
known commit, never one defined in a notebook.
|
known commit, never one defined in a notebook.
|
||||||
"""
|
"""
|
||||||
import hashlib
|
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
import subprocess
|
|
||||||
import tempfile
|
import tempfile
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
import mlflow.pyfunc
|
import mlflow.pyfunc
|
||||||
from core.governance.enums import ArtifactKind, Environment
|
from core.governance.enums import ArtifactKind, Environment
|
||||||
from mlflow import MlflowClient, MlflowException
|
from mlflow import MlflowClient
|
||||||
from persistance.repository import Repository
|
|
||||||
|
|
||||||
from models.io.registry import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, REPORT_TAGS, registered_name
|
from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, code_version, model_sha, registered_name
|
||||||
from models.io.repositories import resolve_repository
|
from models.io.storage import ReadOnlyRepository, resolve_repository
|
||||||
|
|
||||||
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
|
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
|
||||||
MODEL_PATH = "model"
|
MODEL_PATH = "model"
|
||||||
GIT_COMMIT_TAG = "mlflow.source.git.commit" # the tag MLflow's own API sets
|
|
||||||
GIT_DIRTY_TAG = "models.git.dirty"
|
|
||||||
GIT_COMMIT_ENV = "MODELS_GIT_COMMIT"
|
|
||||||
|
|
||||||
|
|
||||||
def code_version() -> dict[str, str]:
|
def inspect_onnx_metadata(path: str | Path) -> dict[str, Any]:
|
||||||
"""The git commit of this package's repository and whether tracked files have uncommitted changes.
|
"""IR version, opsets, producer and graph inputs/outputs of a checkpoint (ML-01b, MLD-03), checked before it's
|
||||||
Without a repository (a delivered image), the commit comes from `MODELS_GIT_COMMIT`; with neither,
|
logged. `onnx` is an optional dependency (`models[export]`).
|
||||||
nothing is recorded."""
|
`{"available": False}` when the optional `onnx` package isn't installed;
|
||||||
root = Path(__file__).resolve().parent
|
`ValueError` when it is and the file isn't a valid ONNX model."""
|
||||||
try:
|
try:
|
||||||
commit = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], capture_output=True, text=True,
|
import onnx
|
||||||
check=True).stdout.strip()
|
except ImportError:
|
||||||
changes = subprocess.run(["git", "-C", str(root), "status", "--porcelain", "--untracked-files=no"],
|
return {"available": False, "reason": "el paquete 'onnx' no está instalado (extra 'export')"}
|
||||||
capture_output=True, text=True, check=True).stdout.strip()
|
|
||||||
except (OSError, subprocess.CalledProcessError):
|
try:
|
||||||
commit = os.environ.get(GIT_COMMIT_ENV)
|
model = onnx.load(str(path))
|
||||||
return {GIT_COMMIT_TAG: commit} if commit else {}
|
onnx.checker.check_model(model)
|
||||||
return {GIT_COMMIT_TAG: commit, GIT_DIRTY_TAG: str(bool(changes)).lower()}
|
except Exception as exc:
|
||||||
|
raise ValueError(f"no es un modelo ONNX válido: {exc}") from exc
|
||||||
|
return {
|
||||||
|
"available": True,
|
||||||
|
"ir_version": model.ir_version,
|
||||||
|
"producer_name": model.producer_name,
|
||||||
|
"producer_version": model.producer_version,
|
||||||
|
"opset_imports": [{"domain": o.domain, "version": o.version} for o in model.opset_import],
|
||||||
|
"graph_inputs": [i.name for i in model.graph.input],
|
||||||
|
"graph_outputs": [o.name for o in model.graph.output],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
def model_sha(model_dir: str | Path) -> str:
|
def log_artifact_file(client: MlflowClient, run_id: str, kind: str, path: str | Path, *,
|
||||||
"""sha256 of a saved pyfunc's `python_model.pkl`: its preparation and fitted model. `MLmodel` is left
|
metadata: dict[str, Any] | None = None) -> None:
|
||||||
out because it carries ids and dates, so the same model saved twice has the same sha."""
|
"""ML-01a/ML-01b: logs an artifact file to a run, under a folder named for its kind."""
|
||||||
return hashlib.sha256((Path(model_dir) / "python_model.pkl").read_bytes()).hexdigest()
|
client.log_artifact(run_id, str(path), artifact_path=kind)
|
||||||
|
if metadata:
|
||||||
|
client.log_dict(run_id, metadata, f"{kind}/{Path(path).name}.meta.json")
|
||||||
class ReadOnlyRepository:
|
|
||||||
"""ML-04: read-only view of a `Repository` exposing `get`/`list`/`count`.
|
|
||||||
Write methods raise `PermissionError` so a training routine cannot
|
|
||||||
modify clinical data."""
|
|
||||||
|
|
||||||
_WRITE_METHODS = {"create", "bulk_upsert", "open_session"}
|
|
||||||
|
|
||||||
def __init__(self, repository: Repository):
|
|
||||||
self._repository = repository
|
|
||||||
self.model = repository.model
|
|
||||||
|
|
||||||
def get(self, id_):
|
|
||||||
return self._repository.get(id_)
|
|
||||||
|
|
||||||
def list(self, *, limit: int = 100, offset: int = 0, **filters):
|
|
||||||
return self._repository.list(limit=limit, offset=offset, **filters)
|
|
||||||
|
|
||||||
def count(self, **filters) -> int:
|
|
||||||
return self._repository.count(**filters)
|
|
||||||
|
|
||||||
def __getattr__(self, name: str):
|
|
||||||
if name in self._WRITE_METHODS:
|
|
||||||
raise PermissionError(
|
|
||||||
f"ML-04: un TrainingRun solo puede leer; '{name}' no está disponible en ReadOnlyRepository."
|
|
||||||
)
|
|
||||||
raise AttributeError(name)
|
|
||||||
|
|
||||||
|
|
||||||
class TrainingRun:
|
class TrainingRun:
|
||||||
@@ -142,10 +121,7 @@ class TrainingRun:
|
|||||||
def log_artifact(self, kind: ArtifactKind | str, path: str | Path, *, metadata: dict[str, Any] | None = None) -> None:
|
def log_artifact(self, kind: ArtifactKind | str, path: str | Path, *, metadata: dict[str, Any] | None = None) -> None:
|
||||||
"""ML-01a/ML-01b: logs an artifact file to the run, under a folder
|
"""ML-01a/ML-01b: logs an artifact file to the run, under a folder
|
||||||
named for its kind."""
|
named for its kind."""
|
||||||
kind = ArtifactKind(kind)
|
log_artifact_file(self.client, self.run_id, ArtifactKind(kind).value, path, metadata=metadata)
|
||||||
self.client.log_artifact(self.run_id, str(path), artifact_path=kind.value)
|
|
||||||
if metadata:
|
|
||||||
self.client.log_dict(self.run_id, metadata, f"{kind.value}/{Path(path).name}.meta.json")
|
|
||||||
|
|
||||||
def log_model(self, python_model: mlflow.pyfunc.PythonModel, *, signature=None) -> str:
|
def log_model(self, python_model: mlflow.pyfunc.PythonModel, *, signature=None) -> str:
|
||||||
"""Saves `python_model` as a pyfunc under the run's `model` folder, tags the run with its
|
"""Saves `python_model` as a pyfunc under the run's `model` folder, tags the run with its
|
||||||
@@ -165,39 +141,13 @@ class TrainingRun:
|
|||||||
self.modelo_sha = sha
|
self.modelo_sha = sha
|
||||||
return sha
|
return sha
|
||||||
|
|
||||||
def finish(
|
def finish(self, *, metrics: dict[str, Any] | None = None, hyperparameters: dict[str, Any] | None = None) -> "TrainingRun":
|
||||||
self,
|
"""Logs metrics and parameters and closes the run. Registering it as a version is the registry's
|
||||||
*,
|
(`models.io.registry.registry.register_run`)."""
|
||||||
metrics: dict[str, Any] | None = None,
|
|
||||||
hyperparameters: dict[str, Any] | None = None,
|
|
||||||
**reports: str | None,
|
|
||||||
) -> str:
|
|
||||||
"""Logs metrics/params to the run, registers it as a new version of
|
|
||||||
`<domain>-<scenario>` tagged with `models.io.registry`'s promotion
|
|
||||||
inputs (environment, cohort link, report URIs), and returns the new
|
|
||||||
version string. Call once, after training (and artifact logging)
|
|
||||||
completes."""
|
|
||||||
unknown = set(reports) - set(REPORT_TAGS)
|
|
||||||
if unknown:
|
|
||||||
raise ValueError(f"campos desconocidos: {sorted(unknown)}")
|
|
||||||
for key, value in (metrics or {}).items():
|
for key, value in (metrics or {}).items():
|
||||||
self.client.log_metric(self.run_id, key, value)
|
self.client.log_metric(self.run_id, key, value)
|
||||||
for key, value in (hyperparameters or {}).items():
|
for key, value in (hyperparameters or {}).items():
|
||||||
self.client.log_param(self.run_id, key, value if isinstance(value, (str, int, float, bool)) else json.dumps(value, default=str))
|
self.client.log_param(self.run_id, key, value if isinstance(value, (str, int, float, bool)) else json.dumps(value, default=str))
|
||||||
|
|
||||||
name = registered_name(self.domain, self.scenario)
|
|
||||||
try:
|
|
||||||
self.client.create_registered_model(name)
|
|
||||||
except MlflowException as exc:
|
|
||||||
if exc.error_code != "RESOURCE_ALREADY_EXISTS":
|
|
||||||
raise
|
|
||||||
version_tags = {"domain": self.domain, "scenario": self.scenario, "environment": self.environment.value}
|
|
||||||
if self.cohorte_armado_id is not None:
|
|
||||||
version_tags[ARMADO_TAG] = str(self.cohorte_armado_id)
|
|
||||||
if self.modelo_sha is not None:
|
|
||||||
version_tags[MODEL_SHA_TAG] = self.modelo_sha
|
|
||||||
version_tags.update({key: uri for key, uri in reports.items() if uri})
|
|
||||||
source = f"runs:/{self.run_id}/{MODEL_PATH}" if self.modelo_sha is not None else f"runs:/{self.run_id}"
|
|
||||||
model_version = self.client.create_model_version(name, source=source, run_id=self.run_id, tags=version_tags)
|
|
||||||
self.client.set_terminated(self.run_id)
|
self.client.set_terminated(self.run_id)
|
||||||
return str(model_version.version)
|
return self
|
||||||
|
|
||||||
+1
-1
@@ -32,7 +32,7 @@ from extraction import FieldKind, FieldSpec, read_document
|
|||||||
from extraction.nlp import RecordExtractor, SegmentLine
|
from extraction.nlp import RecordExtractor, SegmentLine
|
||||||
from extraction.nlp.vocabulary import CLINICAL_TERMS, labels_for
|
from extraction.nlp.vocabulary import CLINICAL_TERMS, labels_for
|
||||||
from extraction.ocr import TesseractOcr
|
from extraction.ocr import TesseractOcr
|
||||||
from models.io.repositories import resolve_repository
|
from models.io.storage import resolve_repository
|
||||||
from persistance.repository import Repository
|
from persistance.repository import Repository
|
||||||
|
|
||||||
# Below this confidence a value is stored but flagged for manual review.
|
# Below this confidence a value is stored but flagged for manual review.
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
"""Builds a cohort: all patients -> index date -> A1 -> ... -> An -> study population.
|
||||||
|
|
||||||
|
Lists the steps of `models.steps.cohort`, gives each rule its own `em_<rule>` and `a_<rule>` node, and runs them.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import types
|
||||||
|
|
||||||
|
from hamilton import ad_hoc_utils, driver
|
||||||
|
from hamilton.function_modifiers import group, inject, parameterize, source, value
|
||||||
|
|
||||||
|
from persistance.aristas.dbt import DbtQueryRepository
|
||||||
|
|
||||||
|
from models.io.contracts import BuiltCohort, CohortQueries
|
||||||
|
from models.steps.cohort import all_patients, attrition, excluded, indexed, remaining, study_population
|
||||||
|
|
||||||
|
INPUTS = ("cohort_queries", "dbt_queries")
|
||||||
|
|
||||||
|
|
||||||
|
def _fresh(function):
|
||||||
|
"""A copy to decorate: Hamilton keeps a decorator on the function itself, so decorating the step would carry it into
|
||||||
|
the next build."""
|
||||||
|
copy = types.FunctionType(function.__code__, function.__globals__, function.__name__, function.__defaults__,
|
||||||
|
function.__closure__)
|
||||||
|
copy.__annotations__, copy.__doc__ = dict(function.__annotations__), function.__doc__
|
||||||
|
copy.__module__, copy.__qualname__ = function.__module__, function.__qualname__
|
||||||
|
return copy
|
||||||
|
|
||||||
|
|
||||||
|
def build_driver(queries: CohortQueries) -> driver.Driver:
|
||||||
|
"""The chain for the cohort's rules, in their order."""
|
||||||
|
rules = list(queries.rules)
|
||||||
|
previous = ["indexed", *[f"a_{rule.name}" for rule in rules[:-1]]]
|
||||||
|
nodes = [
|
||||||
|
all_patients,
|
||||||
|
indexed,
|
||||||
|
parameterize(**{f"em_{rule.name}": {"rule": value(rule)} for rule in rules})(_fresh(excluded)),
|
||||||
|
parameterize(**{f"a_{rule.name}": {"population": source(before), "flagged": source(f"em_{rule.name}")}
|
||||||
|
for rule, before in zip(rules, previous)})(_fresh(remaining)),
|
||||||
|
inject(last=source(f"a_{rules[-1].name}"))(_fresh(study_population)),
|
||||||
|
inject(populations=group(*[source(f"a_{rule.name}") for rule in rules]), rules=value(rules))(_fresh(attrition)),
|
||||||
|
]
|
||||||
|
return driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(*nodes)).build()
|
||||||
|
|
||||||
|
|
||||||
|
def build_cohort(queries: CohortQueries, dbt_queries: DbtQueryRepository) -> BuiltCohort:
|
||||||
|
"""Runs the chain; `dbt_queries` is the domain's `dbt_query_repository`."""
|
||||||
|
results = build_driver(queries).execute(["study_population", "attrition"],
|
||||||
|
inputs={"cohort_queries": queries, "dbt_queries": dbt_queries})
|
||||||
|
return BuiltCohort(results["study_population"], results["attrition"])
|
||||||
|
|
||||||
|
|
||||||
|
def mermaid(graph) -> str:
|
||||||
|
"""The chain as a Mermaid diagram, read from the graph without running it."""
|
||||||
|
def label(name: str) -> str:
|
||||||
|
if name.startswith("em_"):
|
||||||
|
return f'{name}["EM: {name[3:]}"]'
|
||||||
|
if name.startswith("a_"):
|
||||||
|
return f'{name}["A: {name[2:]}"]'
|
||||||
|
return f"{name}[({name})]" if name in ("all_patients", "study_population") else f"{name}[{name}]"
|
||||||
|
|
||||||
|
lines = ["graph LR"]
|
||||||
|
for node in graph.nodes.values():
|
||||||
|
if node.name in INPUTS or node.name == "attrition":
|
||||||
|
continue
|
||||||
|
if node.name.startswith("em_"):
|
||||||
|
lines.append(f' r_{node.name[3:]}[/"R: {node.name[3:]}"/] --> {label(node.name)}')
|
||||||
|
lines += [f" {dependency.name} --> {label(node.name)}" for dependency in node.dependencies
|
||||||
|
if dependency.name not in INPUTS]
|
||||||
|
lines += [f" {dependency.name} -.-> attrition" for dependency in graph.nodes["attrition"].dependencies]
|
||||||
|
return "\n".join(lines)
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
"""Exports a cohort build to its Parquet file: the members' events up to the cut-off, with the build's lineage.
|
||||||
|
|
||||||
|
The steps come from `models.steps.cohort_file`, the reading and writing from `models.io`. Two sources share them:
|
||||||
|
|
||||||
|
- `export_kit_build`: a build the kit stored, written once to `<armado_id>.parquet`;
|
||||||
|
- `export_dbt_build`: the study population of dbt's rules, built now. A file whose rows hash like the latest one's is
|
||||||
|
reused; otherwise the next number is written.
|
||||||
|
|
||||||
|
The timeline comes from the domain's `timeline_repository` (dbt's view `<domain>_linea_de_tiempo`), cut at the
|
||||||
|
build's date in the query, and dbt's rules run through its `dbt_query_repository`. Nothing here writes to the
|
||||||
|
database.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from datetime import date
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import pyarrow as pa
|
||||||
|
from hamilton import ad_hoc_utils, driver
|
||||||
|
|
||||||
|
from models.io.contracts import CohortQueries
|
||||||
|
from models.io.lineage import matches, require_match
|
||||||
|
from models.io.storage import cohort_path, dbt_build_path, latest_dbt_build, read_metadata, write_once
|
||||||
|
from models.pipelines.cohort_build import build_cohort
|
||||||
|
from models.steps.cohort_file import cohort_events, cohort_table, content_sha256, lineage
|
||||||
|
|
||||||
|
NODES = [cohort_events, content_sha256, lineage, cohort_table]
|
||||||
|
|
||||||
|
|
||||||
|
def _table(timeline_rows: list[dict], population: pd.DataFrame, cutoff: date, base_lineage: dict) -> tuple[pa.Table, str]:
|
||||||
|
dr = driver.Builder().with_modules(ad_hoc_utils.create_temporary_module(*NODES)).build()
|
||||||
|
inputs = {"timeline_rows": timeline_rows, "study_population": population, "cutoff": cutoff, "base_lineage": base_lineage}
|
||||||
|
results = dr.execute(["cohort_table", "content_sha256"], inputs=inputs)
|
||||||
|
return results["cohort_table"], results["content_sha256"]
|
||||||
|
|
||||||
|
|
||||||
|
def export_kit_build(cohorts, timeline, root: Path, domain: str, url: str, build_id: int | None = None) -> tuple[Path, str]:
|
||||||
|
"""The kit build's file, reused if it's there and belongs to the build. `cohorts` and `timeline` are the domain's
|
||||||
|
`cohorte_repository` and `timeline_repository`."""
|
||||||
|
build_id = build_id if build_id is not None else cohorts.latest_build(url)
|
||||||
|
build = None if build_id is None else cohorts.build(build_id)
|
||||||
|
if build is None or build.url != url:
|
||||||
|
raise LookupError(f"no such build of {url}: {build_id}")
|
||||||
|
path = cohort_path(root, url, build.armado_id)
|
||||||
|
if path.exists():
|
||||||
|
require_match(read_metadata(path), {"armado_id": build.armado_id, "n_members": build.n_miembros}, str(path))
|
||||||
|
return path, "reused"
|
||||||
|
population = pd.DataFrame([(m.pac_id, m.fecha_indice) for m in cohorts.members(build.armado_id)],
|
||||||
|
columns=["pac_id", "fecha_indice"])
|
||||||
|
base = {"url": url, "version": build.version, "armado_id": build.armado_id, "domain": domain, "producer": "kit",
|
||||||
|
"parametros": cohorts.get(build.armado_id).parametros or "{}", "datos_as_of": build.datos_as_of.isoformat()}
|
||||||
|
table, _ = _table(timeline.read(until=build.datos_as_of), population, build.datos_as_of, base)
|
||||||
|
write_once(table, path)
|
||||||
|
return path, "exported"
|
||||||
|
|
||||||
|
|
||||||
|
def export_dbt_build(queries: CohortQueries, dbt_queries, timeline, root: Path, domain: str) -> tuple[Path, str]:
|
||||||
|
"""Builds the cohort from dbt's rules and writes it, unless its rows are the latest file's. `dbt_queries` and
|
||||||
|
`timeline` are the domain's `dbt_query_repository` and `timeline_repository`."""
|
||||||
|
built = build_cohort(queries, dbt_queries)
|
||||||
|
latest = latest_dbt_build(root, queries.url)
|
||||||
|
number = latest[0] + 1 if latest else 1
|
||||||
|
base = {"url": queries.url, "build": number, "domain": domain, "producer": "dbt",
|
||||||
|
"parametros": json.dumps(queries.parameters, sort_keys=True), "datos_as_of": queries.cutoff.isoformat(),
|
||||||
|
"rules": json.dumps([rule.name for rule in queries.rules]),
|
||||||
|
"attrition": built.attrition.astype(object).where(built.attrition.notna(), None).to_json(orient="records")}
|
||||||
|
table, sha = _table(timeline.read(until=queries.cutoff), built.study_population, queries.cutoff, base)
|
||||||
|
if latest and matches(read_metadata(latest[1]), {"content_sha256": sha}):
|
||||||
|
return latest[1], "reused"
|
||||||
|
path = dbt_build_path(root, queries.url, number)
|
||||||
|
write_once(table, path)
|
||||||
|
return path, "exported"
|
||||||
@@ -1 +1,4 @@
|
|||||||
"""Pure functions shared by every model: no I/O, testable alone."""
|
"""The plain functions pipelines are built from: each becomes a Hamilton node once a pipeline lists it.
|
||||||
|
|
||||||
|
They neither read nor write on their own: what they read comes in as a parameter, and a pipeline decides when they run.
|
||||||
|
"""
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
"""The steps of a cohort build: all patients, the index date, each rule's excluded members and what remains.
|
||||||
|
|
||||||
|
They know no rule by name: a pipeline gives each rule its own `excluded` and `remaining` node. The queries run through
|
||||||
|
the domain's `dbt_query_repository`.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from persistance.aristas.dbt import DbtQueryRepository
|
||||||
|
|
||||||
|
from models.io.contracts import CohortDefinitionError, CohortQueries, ExclusionRule
|
||||||
|
|
||||||
|
|
||||||
|
def _frame(rows: list[dict], columns: list[str]) -> pd.DataFrame:
|
||||||
|
return pd.DataFrame(rows) if rows else pd.DataFrame(columns=columns)
|
||||||
|
|
||||||
|
|
||||||
|
def all_patients(cohort_queries: CohortQueries, dbt_queries: DbtQueryRepository) -> pd.DataFrame:
|
||||||
|
return _frame(dbt_queries.read(cohort_queries.all_patients), ["pac_id"])
|
||||||
|
|
||||||
|
|
||||||
|
def indexed(all_patients: pd.DataFrame, cohort_queries: CohortQueries, dbt_queries: DbtQueryRepository) -> pd.DataFrame:
|
||||||
|
"""The patients with an index date. A patient outside `all_patients` is an error, not attrition."""
|
||||||
|
index = _frame(dbt_queries.read(cohort_queries.index_date), ["pac_id", "fecha_indice"])
|
||||||
|
if index["pac_id"].duplicated().any():
|
||||||
|
raise CohortDefinitionError("the index query gives a patient more than one index date")
|
||||||
|
if unknown := len(set(index["pac_id"]) - set(all_patients["pac_id"])):
|
||||||
|
raise CohortDefinitionError(f"the index query gives {unknown} patients outside all patients")
|
||||||
|
return index.assign(fecha_indice=pd.to_datetime(index["fecha_indice"]).dt.date)
|
||||||
|
|
||||||
|
|
||||||
|
def excluded(rule: ExclusionRule, dbt_queries: DbtQueryRepository) -> set:
|
||||||
|
"""Everyone the rule flags."""
|
||||||
|
return {row["pac_id"] for row in dbt_queries.read(rule.sql)}
|
||||||
|
|
||||||
|
|
||||||
|
def remaining(population: pd.DataFrame, flagged: set) -> pd.DataFrame:
|
||||||
|
"""The previous population minus a rule's excluded members."""
|
||||||
|
return population[~population["pac_id"].isin(flagged)]
|
||||||
|
|
||||||
|
|
||||||
|
def study_population(last: pd.DataFrame) -> pd.DataFrame:
|
||||||
|
return last
|
||||||
|
|
||||||
|
|
||||||
|
def attrition(all_patients: pd.DataFrame, indexed: pd.DataFrame, populations: list[pd.DataFrame],
|
||||||
|
rules: list[ExclusionRule]) -> pd.DataFrame:
|
||||||
|
"""Each rule is charged only for those it removes from the population it receives."""
|
||||||
|
sizes = [("all_patients", len(all_patients)), ("indexed", len(indexed)),
|
||||||
|
*[(rule.name, len(population)) for rule, population in zip(rules, populations)]]
|
||||||
|
rows = [(step, n, None if i == 0 else sizes[i - 1][1] - n) for i, (step, n) in enumerate(sizes)]
|
||||||
|
return pd.DataFrame(rows, columns=["step", "n", "excluded"]).astype({"excluded": "Int64"})
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
"""The steps from a study population and the timeline to a build's table, with its lineage."""
|
||||||
|
|
||||||
|
from datetime import date, datetime, timezone
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
import pyarrow as pa
|
||||||
|
|
||||||
|
from models.io.contracts import COHORT_SCHEMA as SCHEMA
|
||||||
|
from models.io.lineage import table_sha256
|
||||||
|
|
||||||
|
ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"]
|
||||||
|
TIMELINE = [name for name in SCHEMA.names if name != "fecha_indice"]
|
||||||
|
|
||||||
|
|
||||||
|
def cohort_events(timeline_rows: list[dict], study_population: pd.DataFrame, cutoff: date) -> pd.DataFrame:
|
||||||
|
"""The members' events up to `cutoff`, in the file's order. A member without events stops the build."""
|
||||||
|
members = study_population[["pac_id", "fecha_indice"]]
|
||||||
|
frame = pd.DataFrame(timeline_rows, columns=TIMELINE).merge(members, on="pac_id")
|
||||||
|
frame["fecha"] = pd.to_datetime(frame["fecha"], format="ISO8601").dt.date
|
||||||
|
frame["conocida_en"] = pd.to_datetime(frame["conocida_en"], format="ISO8601", utc=True)
|
||||||
|
frame["valor_numerico"] = pd.to_numeric(frame["valor_numerico"])
|
||||||
|
frame = frame[frame["fecha"] <= cutoff]
|
||||||
|
if missing := len(members) - frame["pac_id"].nunique():
|
||||||
|
raise ValueError(f"{missing} members have no events in the timeline")
|
||||||
|
return frame.sort_values(ROW_ORDER, kind="stable")[SCHEMA.names].reset_index(drop=True)
|
||||||
|
|
||||||
|
|
||||||
|
def content_sha256(cohort_events: pd.DataFrame) -> str:
|
||||||
|
"""The hash of the rows alone, so the same content gives the same hash whenever it's built."""
|
||||||
|
return table_sha256(pa.Table.from_pandas(cohort_events, schema=SCHEMA, preserve_index=False))
|
||||||
|
|
||||||
|
|
||||||
|
def lineage(base_lineage: dict, cohort_events: pd.DataFrame, content_sha256: str) -> dict:
|
||||||
|
return {**base_lineage, "n_members": cohort_events["pac_id"].nunique(), "content_sha256": content_sha256,
|
||||||
|
"built_at": datetime.now(timezone.utc).isoformat()}
|
||||||
|
|
||||||
|
|
||||||
|
def cohort_table(cohort_events: pd.DataFrame, lineage: dict) -> pa.Table:
|
||||||
|
table = pa.Table.from_pandas(cohort_events, schema=SCHEMA, preserve_index=False)
|
||||||
|
return table.replace_schema_metadata({**table.schema.metadata, **{k: str(v) for k, v in lineage.items()}})
|
||||||
+1
-1
@@ -8,7 +8,7 @@ model and isn't used outside tests; it has no tests of its own.
|
|||||||
import hashlib
|
import hashlib
|
||||||
import json
|
import json
|
||||||
|
|
||||||
from models.io.contract import Provenance, Risk
|
from models.io.contracts import Provenance, Risk
|
||||||
|
|
||||||
# A base probability and what each baseline predictor adds, capped at `tope`.
|
# A base probability and what each baseline predictor adds, capped at `tope`.
|
||||||
CACU_RULE = {"base": 0.01, "pap_anormal": 0.05, "vph_positivo": 0.10, "tope": 0.95}
|
CACU_RULE = {"base": 0.01, "pap_anormal": 0.05, "vph_positivo": 0.10, "tope": 0.95}
|
||||||
|
|||||||
@@ -1,138 +0,0 @@
|
|||||||
"""Export a kit cohort build to its Parquet file, once.
|
|
||||||
|
|
||||||
uv run python scripts/export_cohort.py --domain cacu --cohort cohorte_vigilancia [--build N]
|
|
||||||
|
|
||||||
One file per build, `<data>/cohorts/<domain>/<cohort>/<armado_id>.parquet`, where `<data>` is the folder of the
|
|
||||||
domain's database and `COHORTS_DIR` replaces `<data>/cohorts`. Long format: one row per member and event, with
|
|
||||||
the member's index date on every row and the build's lineage in the file's metadata.
|
|
||||||
|
|
||||||
The timeline comes from dbt's view `<domain>_linea_de_tiempo`, which holds no rows and needs creating only when its
|
|
||||||
dbt model changes (`dbt run --select <domain>_linea_de_tiempo`). The script only reads, through the domain's
|
|
||||||
repository, so it needs neither dbt nor write access. In a read-only folder, with nothing writing to the file, use
|
|
||||||
`CACU_DATABASE_URL=sqlite:///file:/path/cacu.db?immutable=1&uri=true`; `mode=ro` isn't enough for a WAL database.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import sys
|
|
||||||
import tempfile
|
|
||||||
from collections.abc import Callable, Iterable
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from importlib import import_module
|
|
||||||
from pathlib import Path
|
|
||||||
|
|
||||||
import pandas as pd
|
|
||||||
import pyarrow as pa
|
|
||||||
import pyarrow.parquet as pq
|
|
||||||
from persistance.aristas.oro import CohortBuild, CohortMember
|
|
||||||
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository
|
|
||||||
from persistance.settings import settings
|
|
||||||
from sqlalchemy import column, select, table
|
|
||||||
from sqlalchemy.exc import DBAPIError
|
|
||||||
|
|
||||||
from models.io.cohorts import SCHEMA, cohort_lineage, cohort_path, cohorts_root
|
|
||||||
|
|
||||||
ROW_ORDER = ["pac_id", "fecha", "clase", "tipo", "fuente_id"]
|
|
||||||
|
|
||||||
|
|
||||||
class TimelineViewError(RuntimeError):
|
|
||||||
"""dbt's timeline view can't be read."""
|
|
||||||
|
|
||||||
|
|
||||||
def read_timeline(repository: TimelineRepository, domain: str) -> list[dict]:
|
|
||||||
"""Every event of the domain, from dbt's view. The cut-offs are applied in `build_table`."""
|
|
||||||
name = f"{domain}_linea_de_tiempo"
|
|
||||||
view = table(name, *(column(c) for c in TIMELINE_COLUMNS))
|
|
||||||
try:
|
|
||||||
return repository.with_query(lambda **_: select(*(view.c[c] for c in TIMELINE_COLUMNS))).read()
|
|
||||||
except DBAPIError as error:
|
|
||||||
raise TimelineViewError(f"can't read {name} ({error.orig}): is it created? "
|
|
||||||
f"Run `dbt run --select {name}` in Transformation") from error
|
|
||||||
|
|
||||||
|
|
||||||
def build_table(rows: list[dict], members: Iterable[CohortMember], build: CohortBuild, *, domain: str,
|
|
||||||
parametros: str | None) -> pa.Table:
|
|
||||||
"""The members' events up to `datos_as_of` and loaded by `conocida_hasta`, in the file's order, with the lineage."""
|
|
||||||
members = list(members)
|
|
||||||
index_dates = pd.DataFrame([(m.pac_id, m.fecha_indice) for m in members], columns=["pac_id", "fecha_indice"])
|
|
||||||
frame = pd.DataFrame(rows, columns=list(TIMELINE_COLUMNS)).merge(index_dates, on="pac_id")
|
|
||||||
frame["fecha"] = pd.to_datetime(frame["fecha"], format="ISO8601").dt.date
|
|
||||||
frame["conocida_en"] = pd.to_datetime(frame["conocida_en"], format="ISO8601", utc=True)
|
|
||||||
frame["valor_numerico"] = pd.to_numeric(frame["valor_numerico"])
|
|
||||||
frame = frame[frame["fecha"] <= build.datos_as_of]
|
|
||||||
if build.conocida_hasta is not None:
|
|
||||||
known_until = pd.Timestamp(build.conocida_hasta)
|
|
||||||
frame = frame[frame["conocida_en"] <= (known_until.tz_localize("UTC") if known_until.tzinfo is None else known_until)]
|
|
||||||
missing = len(members) - frame["pac_id"].nunique()
|
|
||||||
if missing:
|
|
||||||
raise ValueError(f"{missing} members of build {build.armado_id} have no events in the timeline")
|
|
||||||
frame = frame.sort_values(ROW_ORDER, kind="stable")
|
|
||||||
lineage = {
|
|
||||||
"url": build.url, "version": build.version, "armado_id": build.armado_id, "domain": domain,
|
|
||||||
"parametros": parametros or "{}", "datos_as_of": build.datos_as_of.isoformat(),
|
|
||||||
"conocida_hasta": build.conocida_hasta.isoformat() if build.conocida_hasta else "",
|
|
||||||
"n_members": len(members), "producer": "kit", "built_at": datetime.now(timezone.utc).isoformat(),
|
|
||||||
}
|
|
||||||
table = pa.Table.from_pandas(frame[SCHEMA.names], schema=SCHEMA, preserve_index=False)
|
|
||||||
return table.replace_schema_metadata({**table.schema.metadata, **{k: str(v) for k, v in lineage.items()}})
|
|
||||||
|
|
||||||
|
|
||||||
def write_once(table: pa.Table, path: Path) -> None:
|
|
||||||
"""The file appears complete or not at all."""
|
|
||||||
path.parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
with tempfile.NamedTemporaryFile(dir=path.parent, suffix=".tmp", delete=False) as handle:
|
|
||||||
partial = Path(handle.name)
|
|
||||||
try:
|
|
||||||
pq.write_table(table, partial)
|
|
||||||
partial.replace(path)
|
|
||||||
finally:
|
|
||||||
partial.unlink(missing_ok=True)
|
|
||||||
|
|
||||||
|
|
||||||
def ensure(build: CohortBuild, root: Path, make_table: Callable[[], pa.Table]) -> tuple[Path, str]:
|
|
||||||
"""The build's file: reused if it's already there and belongs to the build, written once if not."""
|
|
||||||
path = cohort_path(root, build.url, build.armado_id)
|
|
||||||
if path.exists():
|
|
||||||
lineage = cohort_lineage(path)
|
|
||||||
if lineage.get("armado_id") != str(build.armado_id) or lineage.get("n_members") != str(build.n_miembros):
|
|
||||||
raise ValueError(f"{path} doesn't belong to build {build.armado_id}: {lineage}")
|
|
||||||
return path, "reused"
|
|
||||||
write_once(make_table(), path)
|
|
||||||
return path, "exported"
|
|
||||||
|
|
||||||
|
|
||||||
def main(argv: list[str] | None = None) -> int:
|
|
||||||
parser = argparse.ArgumentParser(description="Export a kit cohort build to its Parquet file, once.")
|
|
||||||
parser.add_argument("--domain", required=True, choices=["cacu", "cama", "tea"])
|
|
||||||
parser.add_argument("--cohort", required=True, help="the cohort without its domain, e.g. cohorte_vigilancia")
|
|
||||||
parser.add_argument("--build", type=int, help="the build's armado_id; the cohort's latest by default")
|
|
||||||
args = parser.parse_args(argv)
|
|
||||||
|
|
||||||
repositories = import_module(f"persistance.{args.domain}")
|
|
||||||
cohorts, timeline = repositories.cohorte_repository, repositories.timeline_repository
|
|
||||||
url = f"{args.domain}/{args.cohort}"
|
|
||||||
build_id = args.build if args.build is not None else cohorts.latest_build(url)
|
|
||||||
build = None if build_id is None else cohorts.build(build_id)
|
|
||||||
if build is None or build.url != url:
|
|
||||||
print(f"no such build of {url}: {build_id}", file=sys.stderr)
|
|
||||||
return 1
|
|
||||||
|
|
||||||
database_url = getattr(settings, f"{args.domain}_database_url")
|
|
||||||
|
|
||||||
def make_table() -> pa.Table:
|
|
||||||
return build_table(read_timeline(timeline, args.domain), cohorts.members(build.armado_id), build, domain=args.domain,
|
|
||||||
parametros=cohorts.get(build.armado_id).parametros)
|
|
||||||
|
|
||||||
try:
|
|
||||||
path, outcome = ensure(build, cohorts_root(database_url), make_table)
|
|
||||||
except PermissionError as error:
|
|
||||||
print(f"{error}: the data folder is read-only, set COHORTS_DIR", file=sys.stderr)
|
|
||||||
return 1
|
|
||||||
except TimelineViewError as error:
|
|
||||||
print(error, file=sys.stderr)
|
|
||||||
return 1
|
|
||||||
print(f"{outcome}: {path}")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
"""What this module covers: `models.cacu.cin2_logistic`: how the dummy model computes its outcome and input, its temporal
|
"""What this module covers: `models.cacu.cin2_logistic`: how the dummy model computes its outcome and input, its temporal
|
||||||
split, that training on a build's file registers a version with its lineage, and the `models train` command over it.
|
split, that training on a build's file registers a version with its lineage, and the `models train` and
|
||||||
|
`models estimate` commands over it, and that `models run` does the steps it's told to and repeats none.
|
||||||
|
|
||||||
Fixtures: `cohort_frame`, a long frame of 20 members whose index dates rise with `pac_id`; `cohort_file`, that frame as a
|
Fixtures: `cohort_frame`, a long frame of 20 members whose index dates rise with `pac_id`; `cohort_file`, that frame as a
|
||||||
build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `mlflow_tracking` (conftest), a
|
build's Parquet file with its lineage; `exported`, builds 7 and 12 under a `COHORTS_DIR`; `mlflow_tracking` (conftest), a
|
||||||
@@ -16,9 +17,10 @@ import pytest
|
|||||||
|
|
||||||
from models.__main__ import main
|
from models.__main__ import main
|
||||||
from models.cacu.cin2_logistic import model
|
from models.cacu.cin2_logistic import model
|
||||||
from models.cacu.cin2_logistic.train import train
|
from models.cacu.cin2_logistic.train import find_trained, train
|
||||||
from models.io.cohorts import SCHEMA
|
from models.io.contracts import COHORT_SCHEMA as SCHEMA
|
||||||
from models.io.registry import ARMADO_TAG, MODEL_SHA_TAG, registry
|
from models.io.lineage import ARMADO_TAG, MODEL_SHA_TAG
|
||||||
|
from models.io.registry import PRODUCTION_ALIAS, registry
|
||||||
|
|
||||||
|
|
||||||
def _row(pac_id, index, days, valor, tipo="bethesda"):
|
def _row(pac_id, index, days, valor, tipo="bethesda"):
|
||||||
@@ -105,8 +107,8 @@ def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame
|
|||||||
assert run.metrics["n_train"] == 14 and run.metrics["n_test"] == 6 and "auc" in run.metrics
|
assert run.metrics["n_train"] == 14 and run.metrics["n_test"] == 6 and "auc" in run.metrics
|
||||||
assert len(run.params["cohort_sha256"]) == 64
|
assert len(run.params["cohort_sha256"]) == 64
|
||||||
|
|
||||||
probabilities = mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame)
|
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame)
|
||||||
assert len(probabilities) == 20 and probabilities.between(0, 1).all()
|
assert sorted(risks["pac_id"]) == list(range(1, 21)) and risks["probabilidad"].between(0, 1).all()
|
||||||
|
|
||||||
|
|
||||||
def test_the_command_trains_on_the_latest_exported_build(exported, mlflow_tracking, capsys):
|
def test_the_command_trains_on_the_latest_exported_build(exported, mlflow_tracking, capsys):
|
||||||
@@ -146,3 +148,146 @@ def test_what_is_missing_is_named(exported, arguments, message, capsys):
|
|||||||
version. Fails if the command lets the import error through, or trains on another file."""
|
version. Fails if the command lets the import error through, or trains on another file."""
|
||||||
assert main(["train", *arguments]) == 1
|
assert main(["train", *arguments]) == 1
|
||||||
assert message in capsys.readouterr().err
|
assert message in capsys.readouterr().err
|
||||||
|
|
||||||
|
|
||||||
|
def test_estimate_scores_each_member_with_the_production_version(exported, mlflow_tracking, tmp_path, capsys):
|
||||||
|
"""Pins down: with no `--version`, the command uses the version holding the production alias and writes one row per
|
||||||
|
member, identified by `pac_id`, with the version and build in the file's metadata. Fails if it takes the newest
|
||||||
|
version instead of the alias, or the output can't be matched to members."""
|
||||||
|
main(["train", "cacu", "cin2_logistic"])
|
||||||
|
main(["train", "cacu", "cin2_logistic"])
|
||||||
|
registry.client.set_registered_model_alias("cacu-cin2_logistic", PRODUCTION_ALIAS, "1")
|
||||||
|
output = tmp_path / "risks" / "output.parquet"
|
||||||
|
|
||||||
|
assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output)]) == 0
|
||||||
|
|
||||||
|
assert "version 1" in capsys.readouterr().out
|
||||||
|
risks = pd.read_parquet(output)
|
||||||
|
assert list(risks.columns) == ["pac_id", "fecha_indice", "probabilidad"]
|
||||||
|
assert sorted(risks["pac_id"]) == list(range(1, 21)) and risks["probabilidad"].between(0, 1).all()
|
||||||
|
metadata = pq.read_metadata(output).metadata
|
||||||
|
assert metadata[b"modelo_version"] == b"1" and metadata[b"armado_id"] == b"12"
|
||||||
|
|
||||||
|
|
||||||
|
def test_estimate_uses_the_version_it_is_given(exported, mlflow_tracking, tmp_path):
|
||||||
|
"""Pins down: `--version` runs that version even if it isn't in production. Fails if the option is ignored or the
|
||||||
|
alias becomes mandatory."""
|
||||||
|
main(["train", "cacu", "cin2_logistic"])
|
||||||
|
output = tmp_path / "output.parquet"
|
||||||
|
|
||||||
|
assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output), "--version", "1"]) == 0
|
||||||
|
|
||||||
|
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"1"
|
||||||
|
|
||||||
|
|
||||||
|
def test_estimate_without_a_production_version_is_refused(exported, mlflow_tracking, tmp_path, capsys):
|
||||||
|
"""Pins down: with no `--version` and no version in production, the command ends with exit 1, says so and writes
|
||||||
|
nothing. Fails if it falls back to another version or lets the error through."""
|
||||||
|
main(["train", "cacu", "cin2_logistic"])
|
||||||
|
output = tmp_path / "output.parquet"
|
||||||
|
|
||||||
|
assert main(["estimate", "cacu", "cin2_logistic", "--output", str(output)]) == 1
|
||||||
|
|
||||||
|
assert "no version in production" in capsys.readouterr().err and not output.exists()
|
||||||
|
|
||||||
|
|
||||||
|
RUN = ["run", "cacu", "cin2_logistic"]
|
||||||
|
|
||||||
|
|
||||||
|
def _versions():
|
||||||
|
return registry.client.search_model_versions("name='cacu-cin2_logistic'")
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_without_a_step_is_refused(capsys):
|
||||||
|
"""Pins down: `run` needs a step named, so it never does everything by default. Fails if an empty call starts running
|
||||||
|
steps."""
|
||||||
|
with pytest.raises(SystemExit) as stopped:
|
||||||
|
main(RUN)
|
||||||
|
|
||||||
|
assert stopped.value.code == 2 and "--export" in capsys.readouterr().err
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_only_does_the_steps_it_is_given(exported, mlflow_tracking, tmp_path):
|
||||||
|
"""Pins down: `--train` alone registers a version, sets no alias and writes no output. Fails if a step runs without
|
||||||
|
its option."""
|
||||||
|
assert main([*RUN, "--train"]) == 0
|
||||||
|
|
||||||
|
assert len(_versions()) == 1
|
||||||
|
with pytest.raises(LookupError):
|
||||||
|
registry.resolve("cacu", "cin2_logistic")
|
||||||
|
|
||||||
|
|
||||||
|
def test_repeating_every_step_changes_nothing(exported, mlflow_tracking, tmp_path, capsys):
|
||||||
|
"""Pins down: a second identical run registers no version and doesn't rewrite the output. Fails if `--train` stops
|
||||||
|
looking for the existing version, or `--estimate` stops reading the output's metadata."""
|
||||||
|
output = tmp_path / "output.parquet"
|
||||||
|
steps = [*RUN, "--train", "--promote", "--estimate", "--output", str(output)]
|
||||||
|
assert main(steps) == 0
|
||||||
|
written = output.stat().st_mtime_ns
|
||||||
|
capsys.readouterr()
|
||||||
|
|
||||||
|
assert main(steps) == 0
|
||||||
|
|
||||||
|
assert len(_versions()) == 1 and output.stat().st_mtime_ns == written
|
||||||
|
out = capsys.readouterr().out
|
||||||
|
assert "already trained" in out and "already in production" in out and "already estimated" in out
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_new_build_or_environment_trains_again(exported, mlflow_tracking):
|
||||||
|
"""Pins down: what says a training is the same is the file and the environment, so a build with other content or a
|
||||||
|
PROD run gets its own version. Fails if the check ignores either and reuses a version from something else."""
|
||||||
|
assert main([*RUN, "--train", "--armado", "7"]) == 0
|
||||||
|
assert main([*RUN, "--train", "--armado", "7", "--environment", "prod"]) == 0
|
||||||
|
frame = pd.read_parquet(exported / "12.parquet")
|
||||||
|
_write(frame[frame["pac_id"] != 1], exported / "12.parquet", 12)
|
||||||
|
assert main([*RUN, "--train", "--armado", "12"]) == 0
|
||||||
|
|
||||||
|
assert len(_versions()) == 3
|
||||||
|
|
||||||
|
|
||||||
|
def test_changed_model_code_trains_again(exported, mlflow_tracking, monkeypatch):
|
||||||
|
"""Pins down: a version trained by other code isn't reused. Fails if the check stops comparing `code_sha256`."""
|
||||||
|
assert main([*RUN, "--train"]) == 0
|
||||||
|
assert find_trained(exported / "12.parquet") == "1"
|
||||||
|
|
||||||
|
monkeypatch.setattr(model, "code_sha256", lambda: "other")
|
||||||
|
|
||||||
|
assert find_trained(exported / "12.parquet") is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_moved_alias_estimates_again(exported, mlflow_tracking, tmp_path):
|
||||||
|
"""Pins down: the output is reused only for the same version, so a new production version rewrites it. Fails if
|
||||||
|
`--estimate` skips because the file exists."""
|
||||||
|
output = tmp_path / "output.parquet"
|
||||||
|
assert main(["train", "cacu", "cin2_logistic"]) == 0
|
||||||
|
assert main(["train", "cacu", "cin2_logistic"]) == 0
|
||||||
|
assert main([*RUN, "--promote", "--version", "1", "--estimate", "--output", str(output)]) == 0
|
||||||
|
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"1"
|
||||||
|
|
||||||
|
assert main([*RUN, "--promote", "--version", "2", "--estimate", "--output", str(output)]) == 0
|
||||||
|
|
||||||
|
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"2"
|
||||||
|
|
||||||
|
|
||||||
|
def test_promote_needs_a_version(exported, mlflow_tracking, capsys):
|
||||||
|
"""Pins down: `--promote` with nothing trained on the file and no `--version` ends with exit 1 and sets no alias.
|
||||||
|
Fails if it promotes some other version."""
|
||||||
|
assert main([*RUN, "--promote"]) == 1
|
||||||
|
assert "use --train or --version" in capsys.readouterr().err
|
||||||
|
|
||||||
|
|
||||||
|
def test_export_runs_first_and_stops_the_rest_if_it_fails(exported, mlflow_tracking, monkeypatch):
|
||||||
|
"""Pins down: `--export` exports the kit build of `model.toml`'s cohort, and its failure stops the next steps. Fails if
|
||||||
|
the cohort or the build change, or training continues on a stale file."""
|
||||||
|
calls = []
|
||||||
|
|
||||||
|
def refuse(cohorts, read_timeline, root, domain, url, build_id=None):
|
||||||
|
calls.append((domain, url, build_id))
|
||||||
|
raise LookupError(f"no such build of {url}: {build_id}")
|
||||||
|
|
||||||
|
monkeypatch.setattr("models.pipelines.export_cohort.export_kit_build", refuse)
|
||||||
|
|
||||||
|
assert main([*RUN, "--export", "--train", "--armado", "7"]) == 1
|
||||||
|
|
||||||
|
assert calls == [("cacu", "cacu/cohorte_vigilancia", 7)]
|
||||||
|
assert not _versions()
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
"""What this module covers: the `RiskEstimator` contract in `models.io.contract` and the two records it
|
"""What this module covers: the `RiskEstimator` contract in `models.io.contracts` and the two records it
|
||||||
returns, `Risk` and `Provenance`.
|
returns, `Risk` and `Provenance`.
|
||||||
|
|
||||||
Fixtures: no pytest fixtures. `ConstantEstimator` is the smallest class that meets the contract: one
|
Fixtures: no pytest fixtures. `ConstantEstimator` is the smallest class that meets the contract: one
|
||||||
fixed probability per member and horizon. `Incomplete` lacks `provenance`.
|
fixed probability per member and horizon. `Incomplete` lacks `provenance`.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from models.io.contract import Provenance, Risk, RiskEstimator
|
from models.io.contracts import Provenance, Risk, RiskEstimator
|
||||||
|
|
||||||
|
|
||||||
class ConstantEstimator:
|
class ConstantEstimator:
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
"""What this module covers: `models.io.lineage`, the vocabulary files, runs and versions record their origin with: the
|
||||||
|
hashes of files and tables, and the rule that decides an output is already done.
|
||||||
|
|
||||||
|
Fixtures: none; each test builds its own small table or file.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pyarrow as pa
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from models.io.lineage import file_sha256, matches, registered_name, require_match, table_sha256
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_table_hashes_by_its_rows_not_its_metadata():
|
||||||
|
"""Pins down: the same rows hash the same whatever metadata the table carries, and another row changes the hash.
|
||||||
|
Fails if metadata such as `built_at` enters the hash, so every rebuild would look new."""
|
||||||
|
table = pa.table({"pac_id": [1, 2]})
|
||||||
|
|
||||||
|
assert table_sha256(table) == table_sha256(table.replace_schema_metadata({"built_at": "now"}))
|
||||||
|
assert table_sha256(table) != table_sha256(pa.table({"pac_id": [1, 2, 3]}))
|
||||||
|
|
||||||
|
|
||||||
|
def test_files_hash_in_order(tmp_path):
|
||||||
|
"""Pins down: several files hash as their bytes in the order given, so a model's code hash covers each file. Fails
|
||||||
|
if a file is skipped or the order stops mattering."""
|
||||||
|
a, b = tmp_path / "a", tmp_path / "b"
|
||||||
|
a.write_bytes(b"one")
|
||||||
|
b.write_bytes(b"two")
|
||||||
|
|
||||||
|
assert file_sha256(a, b) != file_sha256(b, a) != file_sha256(a)
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_output_is_done_when_its_lineage_has_every_expected_value():
|
||||||
|
"""Pins down: recorded lineage matches when every expected key has its value, compared as text since files and
|
||||||
|
MLflow store text; extra keys don't matter. Fails if a missing key counts as a match or numbers stop matching text."""
|
||||||
|
recorded = {"armado_id": "7", "n_members": "2", "built_at": "now"}
|
||||||
|
|
||||||
|
assert matches(recorded, {"armado_id": 7, "n_members": 2})
|
||||||
|
assert not matches(recorded, {"armado_id": 7, "content_sha256": "x"})
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_mismatch_is_refused_with_both_sides():
|
||||||
|
"""Pins down: `require_match` names what was expected and what was found. Fails if a mismatch passes silently."""
|
||||||
|
with pytest.raises(ValueError, match="doesn't belong.*armado_id"):
|
||||||
|
require_match({"armado_id": "1"}, {"armado_id": 2}, "build.parquet")
|
||||||
|
|
||||||
|
|
||||||
|
def test_models_are_registered_as_domain_and_scenario():
|
||||||
|
"""Pins down: the name runs and versions share. Fails if the convention changes on one side only."""
|
||||||
|
assert registered_name("cacu", "cin2_logistic") == "cacu-cin2_logistic"
|
||||||
@@ -16,9 +16,10 @@ import pytest
|
|||||||
from core.governance.enums import Environment
|
from core.governance.enums import Environment
|
||||||
from mlflow import MlflowClient
|
from mlflow import MlflowClient
|
||||||
|
|
||||||
from models.io import training
|
from models.io import lineage
|
||||||
from models.io.registry import MODEL_SHA_TAG, registry
|
from models.io.lineage import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, MODEL_SHA_TAG
|
||||||
from models.io.training import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, TrainingRun
|
from models.io.registry import registry
|
||||||
|
from models.io.tracking import TrainingRun
|
||||||
|
|
||||||
|
|
||||||
class Constant(mlflow.pyfunc.PythonModel):
|
class Constant(mlflow.pyfunc.PythonModel):
|
||||||
@@ -37,7 +38,7 @@ def _train(model: Constant | None = None, scenario: str = "tamizaje") -> tuple[T
|
|||||||
run = TrainingRun(domain="cacu", scenario=scenario, environment=Environment.DEV)
|
run = TrainingRun(domain="cacu", scenario=scenario, environment=Environment.DEV)
|
||||||
if model is not None:
|
if model is not None:
|
||||||
run.log_model(model)
|
run.log_model(model)
|
||||||
return run, run.finish(metrics={"auc": 0.7})
|
return run, registry.register_run(run.finish(metrics={"auc": 0.7}))
|
||||||
|
|
||||||
|
|
||||||
def test_a_logged_model_is_what_the_version_loads(mlflow_tracking):
|
def test_a_logged_model_is_what_the_version_loads(mlflow_tracking):
|
||||||
@@ -129,7 +130,7 @@ def test_an_explicit_version_is_returned_with_its_status(production_ready):
|
|||||||
|
|
||||||
|
|
||||||
def _git(*args: str) -> str:
|
def _git(*args: str) -> str:
|
||||||
return subprocess.run(["git", "-C", str(Path(training.__file__).parent), *args], capture_output=True, text=True,
|
return subprocess.run(["git", "-C", str(Path(lineage.__file__).parent), *args], capture_output=True, text=True,
|
||||||
check=True).stdout.strip()
|
check=True).stdout.strip()
|
||||||
|
|
||||||
|
|
||||||
@@ -155,7 +156,7 @@ def test_without_a_repository_the_commit_comes_from_the_environment(mlflow_track
|
|||||||
def no_git(*args, **kwargs):
|
def no_git(*args, **kwargs):
|
||||||
raise FileNotFoundError("git")
|
raise FileNotFoundError("git")
|
||||||
|
|
||||||
monkeypatch.setattr(training.subprocess, "run", no_git)
|
monkeypatch.setattr(lineage.subprocess, "run", no_git)
|
||||||
monkeypatch.setenv(GIT_COMMIT_ENV, "abc123")
|
monkeypatch.setenv(GIT_COMMIT_ENV, "abc123")
|
||||||
tags = MlflowClient().get_run(TrainingRun(domain="cacu", scenario="tamizaje",
|
tags = MlflowClient().get_run(TrainingRun(domain="cacu", scenario="tamizaje",
|
||||||
environment=Environment.DEV).run_id).data.tags
|
environment=Environment.DEV).run_id).data.tags
|
||||||
|
|||||||
@@ -56,7 +56,7 @@ def test_retire_and_lineage(production_ready):
|
|||||||
|
|
||||||
|
|
||||||
def test_invalid_onnx_checkpoint_is_rejected(production_ready):
|
def test_invalid_onnx_checkpoint_is_rejected(production_ready):
|
||||||
from models.io.export import inspect_onnx_metadata
|
from models.io.tracking import inspect_onnx_metadata
|
||||||
|
|
||||||
with pytest.raises(ValueError, match="ONNX"):
|
with pytest.raises(ValueError, match="ONNX"):
|
||||||
import tempfile
|
import tempfile
|
||||||
|
|||||||
@@ -2,8 +2,7 @@ import json
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from models.io.prediction import ApplicabilityRejected, Interpretability, PredictionService
|
from models.io.registry import ApplicabilityRejected, Interpretability, PredictionService, registry
|
||||||
from models.io.registry import registry
|
|
||||||
|
|
||||||
|
|
||||||
class StubModel:
|
class StubModel:
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
"""What this module covers: `models.io.cohorts`, reading a cohort build's file; and the rule that a model's folder
|
"""What this module covers: `models.io.storage`, reading a cohort build's file; and the rule that a model's folder
|
||||||
doesn't import the database layer, since the file is its only input.
|
doesn't import the database layer, since the file is its only input.
|
||||||
|
|
||||||
Fixtures: `cohort_file`, a small Parquet file of a build with two members.
|
Fixtures: `cohort_file`, a small Parquet file of a build with two members.
|
||||||
@@ -13,7 +13,8 @@ import pyarrow.parquet as pq
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import models
|
import models
|
||||||
from models.io.cohorts import SCHEMA, CohortFileError, read_cohort
|
from models.io.contracts import COHORT_SCHEMA as SCHEMA, CohortFileError
|
||||||
|
from models.io.storage import read_cohort
|
||||||
|
|
||||||
|
|
||||||
def _row(pac_id, fecha_indice, valor, fuente_id):
|
def _row(pac_id, fecha_indice, valor, fuente_id):
|
||||||
@@ -1,10 +1,10 @@
|
|||||||
"""What this module covers: `resolve_repository`, how `models` finds a domain's Persistance repository by name.
|
"""What this module covers: `models.io.storage.resolve_repository`, how `models` finds a domain's Persistance repository by name.
|
||||||
|
|
||||||
Fixtures: `cacu_db` (from `conftest.py`), an empty CaCu SQLite database per test.
|
Fixtures: `cacu_db` (from `conftest.py`), an empty CaCu SQLite database per test.
|
||||||
"""
|
"""
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from models.io.repositories import resolve_repository
|
from models.io.storage import resolve_repository
|
||||||
|
|
||||||
|
|
||||||
def test_resolves_the_domain_repository_and_reads_its_rows(cacu_db):
|
def test_resolves_the_domain_repository_and_reads_its_rows(cacu_db):
|
||||||
@@ -4,7 +4,8 @@ from core.governance.enums import ArtifactKind, Environment
|
|||||||
from models.io.registry import registry
|
from models.io.registry import registry
|
||||||
from mlflow import MlflowException
|
from mlflow import MlflowException
|
||||||
|
|
||||||
from models.io.training import ReadOnlyRepository, TrainingRun
|
from models.io.storage import ReadOnlyRepository
|
||||||
|
from models.io.tracking import TrainingRun
|
||||||
|
|
||||||
|
|
||||||
def test_prod_run_requires_a_cohort_build():
|
def test_prod_run_requires_a_cohort_build():
|
||||||
@@ -23,7 +24,7 @@ def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path)
|
|||||||
|
|
||||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||||
run.log_artifact(ArtifactKind.ONNX_CHECKPOINT, checkpoint, metadata={"opset": 17})
|
run.log_artifact(ArtifactKind.ONNX_CHECKPOINT, checkpoint, metadata={"opset": 17})
|
||||||
version = run.finish(metrics={"auc": 0.81})
|
version = registry.register_run(run.finish(metrics={"auc": 0.81}))
|
||||||
|
|
||||||
mv = registry.get("cacu", "tamizaje", version)
|
mv = registry.get("cacu", "tamizaje", version)
|
||||||
assert mv.tags["environment"] == Environment.DEV.value
|
assert mv.tags["environment"] == Environment.DEV.value
|
||||||
@@ -61,23 +62,34 @@ def test_experiments_keep_artifacts_under_the_configured_root(mlflow_tracking, t
|
|||||||
assert experiment.artifact_location.endswith(str(root / "cama-riesgo"))
|
assert experiment.artifact_location.endswith(str(root / "cama-riesgo"))
|
||||||
|
|
||||||
|
|
||||||
def test_finish_only_tolerates_an_existing_registered_model(mlflow_tracking, monkeypatch):
|
def test_registering_only_tolerates_an_existing_registered_model(mlflow_tracking, monkeypatch):
|
||||||
|
from mlflow import MlflowClient
|
||||||
|
|
||||||
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||||
assert run.finish() == "1"
|
assert registry.register_run(run.finish()) == "1"
|
||||||
|
|
||||||
second = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
second = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||||
assert second.finish() == "2"
|
assert registry.register_run(second.finish()) == "2"
|
||||||
|
|
||||||
third = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
third = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
|
||||||
|
|
||||||
def unreachable(name):
|
def unreachable(self, name):
|
||||||
raise MlflowException("servidor no disponible")
|
raise MlflowException("servidor no disponible")
|
||||||
|
|
||||||
monkeypatch.setattr(third.client, "create_registered_model", unreachable)
|
monkeypatch.setattr(MlflowClient, "create_registered_model", unreachable)
|
||||||
with pytest.raises(MlflowException, match="no disponible"):
|
with pytest.raises(MlflowException, match="no disponible"):
|
||||||
third.finish()
|
registry.register_run(third.finish())
|
||||||
|
|
||||||
|
|
||||||
def test_unknown_domain_is_rejected():
|
def test_unknown_domain_is_rejected():
|
||||||
with pytest.raises(ValueError, match="dominio desconocido"):
|
with pytest.raises(ValueError, match="dominio desconocido"):
|
||||||
TrainingRun(domain="x", scenario="tamizaje", environment=Environment.DEV)
|
TrainingRun(domain="x", scenario="tamizaje", environment=Environment.DEV)
|
||||||
|
|
||||||
|
|
||||||
|
def test_finishing_a_run_registers_nothing(mlflow_tracking):
|
||||||
|
"""Pins down: closing a run logs its metrics and ends it, and only the registry turns it into a version, so a run
|
||||||
|
can be kept without becoming a model. Fails if `finish` starts registering again."""
|
||||||
|
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV).finish(metrics={"auc": 0.5})
|
||||||
|
|
||||||
|
assert registry.client.get_run(run.run_id).info.status == "FINISHED"
|
||||||
|
assert registry.client.search_model_versions("name='cacu-tamizaje'") == []
|
||||||
@@ -2,7 +2,7 @@ import onnx
|
|||||||
import onnx.helper
|
import onnx.helper
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
from models.io.export import inspect_onnx_metadata
|
from models.io.tracking import inspect_onnx_metadata
|
||||||
|
|
||||||
|
|
||||||
def _tiny_onnx_bytes() -> bytes:
|
def _tiny_onnx_bytes() -> bytes:
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
"""What this module covers: reading a cohort's queries from dbt's manifest (`models.io.storage.read_queries`), the
|
||||||
|
graph `models.pipelines.cohort_build` generates from them, and the `models cohorts build` command over it.
|
||||||
|
|
||||||
|
Fixtures: `manifest`, a function writing a `manifest.json` whose queries are literal rows, so no dbt or tables are
|
||||||
|
needed: patients 1 to 6 with a cut-off in their meta, 1 to 5 with an index date, rule `first` flags 2 and 3, rule `second` flags 3 and 4;
|
||||||
|
`cacu_db` (conftest), a temporary CaCu database whose session the command reads through.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from persistance.aristas.dbt import DbtQueryRepository
|
||||||
|
from sqlalchemy import create_engine, text
|
||||||
|
from sqlmodel import Session
|
||||||
|
|
||||||
|
from models.__main__ import main
|
||||||
|
from models.io.contracts import CohortDefinitionError, CohortQueries, ExclusionRule
|
||||||
|
from models.io.storage import read_queries
|
||||||
|
from models.pipelines.cohort_build import build_cohort, build_driver, mermaid
|
||||||
|
from models.steps import cohort
|
||||||
|
|
||||||
|
URL = "cacu/sample"
|
||||||
|
|
||||||
|
|
||||||
|
def _rows(*ids):
|
||||||
|
return " union all ".join(f"select {i} as pac_id" for i in ids)
|
||||||
|
|
||||||
|
|
||||||
|
INDEX = " union all ".join(f"select {i} as pac_id, '2025-01-0{i}' as fecha_indice" for i in range(1, 6))
|
||||||
|
|
||||||
|
|
||||||
|
def _node(name, kind, sql, order=None, reads=()):
|
||||||
|
meta = {"cohort": URL, "kind": kind} | ({"cutoff": "2025-12-31", "parameters": '{"cutoff": "2025-12-31"}'} if kind == "population" else {})
|
||||||
|
if order is not None:
|
||||||
|
meta |= {"name": name, "order": order}
|
||||||
|
return {"name": name, "unique_id": f"model.p.{name}", "description": f"{name} rule", "compiled_code": sql,
|
||||||
|
"config": {"meta": meta}, "depends_on": {"nodes": [f"model.p.{r}" for r in reads]}}
|
||||||
|
|
||||||
|
|
||||||
|
def _standard():
|
||||||
|
return [_node("all_patients", "population", _rows(1, 2, 3, 4, 5, 6)), _node("index", "index", INDEX),
|
||||||
|
_node("first", "exclusion", _rows(2, 3), 1, ["index", "timeline"]),
|
||||||
|
_node("second", "exclusion", _rows(3, 4), 2, ["index", "timeline"])]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def manifest(tmp_path):
|
||||||
|
"""Writes the given nodes, the standard cohort by default, plus a model of another cohort, and returns the path."""
|
||||||
|
def write(nodes=None):
|
||||||
|
other = _node("foreign", "population", _rows(99)) | {"config": {"meta": {"cohort": "cacu/other", "kind": "population"}}}
|
||||||
|
nodes = _standard() if nodes is None else nodes
|
||||||
|
path = tmp_path / "manifest.json"
|
||||||
|
path.write_text(json.dumps({"nodes": {node["unique_id"]: node for node in [*nodes, other]}}))
|
||||||
|
return path
|
||||||
|
return write
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def _sqlite_reader():
|
||||||
|
"""The real `DbtQueryRepository` over an empty in-memory database: the test queries are literal rows."""
|
||||||
|
return DbtQueryRepository(lambda: Session(create_engine("sqlite://")))
|
||||||
|
|
||||||
|
|
||||||
|
def test_rules_come_from_the_manifest_in_their_order(manifest):
|
||||||
|
"""Pins down: only this cohort's queries are read, with name, description and order from the YAML. Fails if another
|
||||||
|
cohort's models leak in, or the rules follow the manifest's order instead of `order`."""
|
||||||
|
nodes = _standard()
|
||||||
|
queries = read_queries(manifest(nodes[:2] + nodes[:1:-1]), URL)
|
||||||
|
|
||||||
|
assert [(rule.name, rule.order) for rule in queries.rules] == [("first", 1), ("second", 2)]
|
||||||
|
assert queries.rules[0].description == "first rule" and "99" not in queries.all_patients
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_chain_gives_population_and_attrition(manifest):
|
||||||
|
"""Pins down: the study population is the indexed patients minus every rule's set, and a patient two rules flag is
|
||||||
|
charged to the first. Fails if attrition counts each set whole, or a rule stops applying."""
|
||||||
|
built = build_cohort(read_queries(manifest(), URL), _sqlite_reader())
|
||||||
|
|
||||||
|
assert sorted(built.study_population["pac_id"]) == [1, 5]
|
||||||
|
assert built.attrition.to_dict("list")["step"] == ["all_patients", "indexed", "first", "second"]
|
||||||
|
assert built.attrition["n"].tolist() == [6, 5, 3, 2]
|
||||||
|
assert built.attrition["excluded"].tolist()[1:] == [1, 2, 1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_order_changes_the_charge_not_the_population(manifest):
|
||||||
|
"""Pins down: with the rules reversed the population is the same and patient 3 is charged to the other rule. Fails if
|
||||||
|
a rule starts depending on the chain."""
|
||||||
|
forward = read_queries(manifest(), URL)
|
||||||
|
backward = CohortQueries(URL, forward.all_patients, forward.index_date, tuple(reversed(forward.rules)), forward.cutoff, {})
|
||||||
|
one, other = build_cohort(forward, _sqlite_reader()), build_cohort(backward, _sqlite_reader())
|
||||||
|
|
||||||
|
assert set(one.study_population["pac_id"]) == set(other.study_population["pac_id"])
|
||||||
|
assert one.attrition["step"].tolist()[2:] == ["first", "second"] and other.attrition["step"].tolist()[2:] == ["second", "first"]
|
||||||
|
assert one.attrition["excluded"].tolist()[2:] == [2, 1] and other.attrition["excluded"].tolist()[2:] == [2, 1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_new_rule_only_needs_its_query(manifest):
|
||||||
|
"""Pins down: adding a rule in the manifest adds its nodes, with no code naming it. Fails if the chain stops being
|
||||||
|
generated from the rules."""
|
||||||
|
queries = read_queries(manifest([*_standard(), _node("third", "exclusion", _rows(5), 3, ["index"])]), URL)
|
||||||
|
built = build_cohort(queries, _sqlite_reader())
|
||||||
|
|
||||||
|
assert {"em_third", "a_third"} <= set(build_driver(queries).graph.nodes)
|
||||||
|
assert built.study_population["pac_id"].tolist() == [1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_index_dates_become_dates(manifest):
|
||||||
|
"""Pins down: `fecha_indice` is a date whatever the engine returns; SQLite returns text. Fails if the conversion is
|
||||||
|
lost, which the export's schema would reject."""
|
||||||
|
built = build_cohort(read_queries(manifest(), URL), _sqlite_reader())
|
||||||
|
|
||||||
|
assert built.study_population.set_index("pac_id").loc[1, "fecha_indice"] == date(2025, 1, 1)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_population_without_cutoff_is_refused(manifest):
|
||||||
|
"""Pins down: the build needs the cut-off its events are cut at. Fails if the export could run without one."""
|
||||||
|
nodes = _standard()
|
||||||
|
del nodes[0]["config"]["meta"]["cutoff"]
|
||||||
|
|
||||||
|
with pytest.raises(CohortDefinitionError, match="no `cutoff`"):
|
||||||
|
read_queries(manifest(nodes), URL)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("change, message", [
|
||||||
|
(lambda n: n[:1] + n[2:], "exactly one `index`"),
|
||||||
|
(lambda n: n[:2], "no `exclusion` queries"),
|
||||||
|
(lambda n: [*n, _node("third", "exclusion", _rows(5), 1)], "repeats an `order`"),
|
||||||
|
(lambda n: [*n, _node("third", "exclusion", _rows(5), 3, ["first"])], "may only read"),
|
||||||
|
(lambda n: [*n[:2], n[2] | {"compiled_code": None}, n[3]], "dbt compile"),
|
||||||
|
])
|
||||||
|
def test_a_badly_defined_cohort_is_refused(manifest, change, message):
|
||||||
|
"""Pins down: what the chain relies on is checked when reading. The fourth case is what keeps the rules commutable: an
|
||||||
|
exclusion can't read another step. Fails if any of these reaches the graph."""
|
||||||
|
with pytest.raises(CohortDefinitionError, match=message):
|
||||||
|
read_queries(manifest(change(_standard())), URL)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("index_sql, message", [
|
||||||
|
("select 1 as pac_id, '2025-01-01' as fecha_indice union all select 1, '2025-01-02'", "more than one index date"),
|
||||||
|
("select 7 as pac_id, '2025-01-01' as fecha_indice", "outside all patients"),
|
||||||
|
])
|
||||||
|
def test_a_wrong_index_is_an_error_not_attrition(index_sql, message):
|
||||||
|
"""Pins down: a repeated patient or one unknown to `all_patients` stops the build. Fails if an inner join silently
|
||||||
|
drops them and they pass as attrition."""
|
||||||
|
queries = CohortQueries(URL, _rows(1, 2), index_sql, (ExclusionRule("r", "", 1, _rows(2)),), date(2025, 12, 31), {})
|
||||||
|
|
||||||
|
with pytest.raises(Exception, match=message):
|
||||||
|
build_cohort(queries, _sqlite_reader())
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_graph_comes_without_running_anything(manifest):
|
||||||
|
"""Pins down: the diagram shows each rule, its excluded members and its population, and leaves the inputs out. Fails if
|
||||||
|
the nodes stop being derived from the rules."""
|
||||||
|
diagram = mermaid(build_driver(read_queries(manifest(), URL)).graph)
|
||||||
|
|
||||||
|
assert 'em_first["EM: first"]' in diagram and "a_first --> " in diagram
|
||||||
|
assert "dbt_queries" not in diagram and "cohort_queries" not in diagram and "a_second --> study_population" in diagram
|
||||||
|
|
||||||
|
|
||||||
|
def test_cutoff_and_parameters_come_from_the_population_meta(manifest):
|
||||||
|
"""Pins down: the cut-off and the parameters dbt rendered into the population query's meta are read with the rules,
|
||||||
|
so the export cuts the events where the rules did. Fails if they're lost or not parsed."""
|
||||||
|
queries = read_queries(manifest(), URL)
|
||||||
|
|
||||||
|
assert queries.cutoff == date(2025, 12, 31) and queries.parameters == {"cutoff": "2025-12-31"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_two_builds_with_other_rules_stay_apart(manifest):
|
||||||
|
"""Pins down: building a chain decorates copies, so a second build with other rules doesn't inherit the first's
|
||||||
|
nodes, and the steps themselves stay plain. Fails if the pipeline decorates the step functions in place."""
|
||||||
|
queries = read_queries(manifest(), URL)
|
||||||
|
build_driver(queries)
|
||||||
|
other = build_driver(CohortQueries(URL, queries.all_patients, queries.index_date, (ExclusionRule("only", "", 1, _rows(2)),),
|
||||||
|
queries.cutoff, {}))
|
||||||
|
|
||||||
|
assert {"em_only", "a_only"} <= set(other.graph.nodes) and "em_first" not in other.graph.nodes
|
||||||
|
assert not getattr(cohort.excluded, "__dict__", {})
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_command_builds_through_the_session(manifest, cacu_db, capsys):
|
||||||
|
"""Pins down: `cohorts build` reads through the domain's session, shows the attrition and says nothing was stored.
|
||||||
|
Fails if the wiring to the session or the output changes."""
|
||||||
|
assert main(["cohorts", "build", "cacu", "sample", "--manifest", str(manifest())]) == 0
|
||||||
|
|
||||||
|
out = capsys.readouterr().out
|
||||||
|
assert "second" in out and "cacu/sample: 2 members, not stored" in out
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_command_prints_the_graph_without_a_database(manifest, capsys):
|
||||||
|
"""Pins down: `--graph` needs only the manifest. Fails if it runs a query."""
|
||||||
|
nodes = _standard()
|
||||||
|
nodes[0]["compiled_code"] = "select from nowhere"
|
||||||
|
|
||||||
|
assert main(["cohorts", "build", "cacu", "sample", "--manifest", str(manifest(nodes)), "--graph"]) == 0
|
||||||
|
assert capsys.readouterr().out.startswith("graph LR")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("arguments, message", [
|
||||||
|
(["--manifest", "/nowhere/manifest.json"], "manifest.json"),
|
||||||
|
(["--graph"], "has no queries"),
|
||||||
|
])
|
||||||
|
def test_what_is_missing_is_named(manifest, arguments, message, capsys):
|
||||||
|
"""Pins down: a missing manifest or an unknown cohort ends with exit 1 and a message. Fails if a traceback gets out."""
|
||||||
|
if arguments[0] == "--graph":
|
||||||
|
arguments = ["--manifest", str(manifest())]
|
||||||
|
assert main(["cohorts", "build", "cacu", "unknown", *arguments]) == 1
|
||||||
|
else:
|
||||||
|
assert main(["cohorts", "build", "cacu", "sample", *arguments]) == 1
|
||||||
|
assert message in capsys.readouterr().err
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_query_that_fails_points_to_the_view(manifest, cacu_db, capsys):
|
||||||
|
"""Pins down: a query that can't run, usually because the view isn't created, ends with exit 1 and names the dbt
|
||||||
|
command. Fails if the database error reaches the user raw."""
|
||||||
|
nodes = _standard()
|
||||||
|
nodes[0]["compiled_code"] = "select pac_id from no_such_view"
|
||||||
|
|
||||||
|
assert main(["cohorts", "build", "cacu", "sample", "--manifest", str(manifest(nodes))]) == 1
|
||||||
|
assert "dbt run --select cacu_linea_de_tiempo" in capsys.readouterr().err
|
||||||
+171
-110
@@ -1,49 +1,56 @@
|
|||||||
"""What this module covers: `scripts/export_cohort.py`, the standalone export of a kit cohort build: where the file
|
"""What this module covers: exporting a cohort build to its Parquet file. The steps (`models.steps.cohort_file`), the
|
||||||
goes, what it holds, that it's written once, and that the timeline is read from dbt's view without changing the database.
|
file (`models.io.storage`, `models.io.lineage`), both sources of `models.pipelines.export_cohort`, and the `models cohorts export` command.
|
||||||
|
Reading the timeline and dbt's queries is Persistance's, tested there.
|
||||||
|
|
||||||
Fixtures: `script`, the module loaded from its path, since `scripts/` isn't part of the package; `build`, a build
|
Fixtures: `build`, a kit build cut at 2025-12-31 with two members, and `kit`, a stand-in of its repository; `events`, one
|
||||||
cut at 2025-12-31 with two members; `events`, one kept event per member plus one event each cut-off must drop and
|
kept event per member plus one after the cut-off and one of a patient outside the build; `dbt_cohort`, compiled queries
|
||||||
one of a patient outside the build; `timeline_db`, a SQLite file with a `cacu_linea_de_tiempo` view and its repository.
|
whose rules keep patients 10 and 20.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import importlib.util
|
|
||||||
import sqlite3
|
|
||||||
from datetime import date, datetime, timezone
|
from datetime import date, datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from types import SimpleNamespace
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
import pyarrow.parquet as pq
|
import pyarrow.parquet as pq
|
||||||
import pytest
|
import pytest
|
||||||
from persistance.aristas.oro import CohortBuild, CohortMember
|
from persistance.aristas.oro import CohortBuild, CohortMember
|
||||||
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository
|
from persistance.aristas.dbt import DbtQueryRepository
|
||||||
from sqlmodel import Session, create_engine
|
from sqlalchemy import create_engine, text
|
||||||
|
from sqlmodel import Session
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[1]
|
from models.__main__ import main
|
||||||
|
from models.io.contracts import COHORT_SCHEMA as SCHEMA, CohortQueries, ExclusionRule
|
||||||
|
from models.io.storage import cohorts_root, read_metadata, write_once
|
||||||
|
from models.pipelines.export_cohort import export_dbt_build, export_kit_build
|
||||||
|
from models.steps.cohort_file import cohort_events, content_sha256
|
||||||
|
|
||||||
|
URL = "cacu/cohorte_vigilancia"
|
||||||
MEMBERS = [CohortMember(20, date(2025, 2, 1), "citologiacervical", "b"),
|
MEMBERS = [CohortMember(20, date(2025, 2, 1), "citologiacervical", "b"),
|
||||||
CohortMember(10, date(2025, 1, 1), "citologiacervical", "a")]
|
CohortMember(10, date(2025, 1, 1), "citologiacervical", "a")]
|
||||||
|
POPULATION = pd.DataFrame({"pac_id": [20, 10], "fecha_indice": [date(2025, 2, 1), date(2025, 1, 1)]})
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
def _build(armado_id=1, n_miembros=2):
|
||||||
def script():
|
return CohortBuild(armado_id, URL, "1.0", "huella", "marco", date(2025, 12, 31), None, n_miembros,
|
||||||
"""The script as a module."""
|
datetime(2026, 1, 1, tzinfo=timezone.utc))
|
||||||
spec = importlib.util.spec_from_file_location("export_cohort", ROOT / "scripts" / "export_cohort.py")
|
|
||||||
module = importlib.util.module_from_spec(spec)
|
|
||||||
spec.loader.exec_module(module)
|
|
||||||
return module
|
|
||||||
|
|
||||||
|
|
||||||
def _build(armado_id=1, known_until=None, n_miembros=2):
|
|
||||||
return CohortBuild(armado_id, "cacu/cohorte_vigilancia", "1.0", "huella", "marco", date(2025, 12, 31), known_until,
|
|
||||||
n_miembros, datetime(2026, 1, 1, tzinfo=timezone.utc))
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def build():
|
def build():
|
||||||
"""A build with a clinical cut-off and a load cut-off."""
|
"""A kit build with a clinical cut-off."""
|
||||||
return _build(known_until=datetime(2026, 1, 2, 8, tzinfo=timezone.utc))
|
return _build()
|
||||||
|
|
||||||
|
|
||||||
def _event(pac_id, fecha, conocida_en, fuente_id):
|
@pytest.fixture
|
||||||
return {"pac_id": pac_id, "fecha": fecha, "conocida_en": conocida_en, "clase": "medicion", "tipo": "bethesda",
|
def kit(build):
|
||||||
|
"""The cohort repository's reads an export needs, over `build` and its members."""
|
||||||
|
return SimpleNamespace(latest_build=lambda url: build.armado_id, build=lambda i: build if i == build.armado_id else None,
|
||||||
|
members=lambda i: MEMBERS, get=lambda i: SimpleNamespace(parametros='{"corte": "2025-12-31"}'))
|
||||||
|
|
||||||
|
|
||||||
|
def _event(pac_id, fecha, fuente_id):
|
||||||
|
return {"pac_id": pac_id, "fecha": fecha, "conocida_en": "2025-02-02 10:00:00", "clase": "medicion", "tipo": "bethesda",
|
||||||
"codigo": "bethesda", "valor_codigo": "NORMAL", "valor_numerico": None, "fuente_tabla": "citologiacervical",
|
"codigo": "bethesda", "valor_codigo": "NORMAL", "valor_numerico": None, "fuente_tabla": "citologiacervical",
|
||||||
"fuente_id": fuente_id}
|
"fuente_id": fuente_id}
|
||||||
|
|
||||||
@@ -51,134 +58,188 @@ def _event(pac_id, fecha, conocida_en, fuente_id):
|
|||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def events():
|
def events():
|
||||||
"""Dates as text, as SQLite returns them from a subquery."""
|
"""Dates as text, as SQLite returns them from a subquery."""
|
||||||
return [_event(20, "2025-03-01", "2025-03-02 10:00:00", "kept-20"),
|
return [_event(20, "2025-03-01", "kept-20"), _event(10, "2025-02-01", "kept-10"),
|
||||||
_event(10, "2025-02-01", "2025-02-02 10:00:00.5", "kept-10"),
|
_event(10, "2026-02-01", "after-the-cutoff"), _event(99, "2025-02-01", "not-a-member")]
|
||||||
_event(10, "2026-02-01", "2026-01-01 00:00:00", "after-datos-as-of"),
|
|
||||||
_event(20, "2025-06-01", "2026-01-03 00:00:00", "loaded-after-the-build"),
|
|
||||||
_event(99, "2025-02-01", "2025-02-02 00:00:00", "not-a-member")]
|
|
||||||
|
|
||||||
|
|
||||||
def test_table_keeps_members_within_both_cut_offs_in_the_file_order(script, build, events):
|
|
||||||
"""Pins down: only members' events, up to `datos_as_of` and loaded by `conocida_hasta`, ordered by patient, each
|
|
||||||
with its index date. Fails if a cut-off or the join with the members is lost, or the rows aren't sorted."""
|
|
||||||
table = script.build_table(events, MEMBERS, build, domain="cacu", parametros='{"corte": "2025-12-31"}')
|
|
||||||
|
|
||||||
assert table.column("fuente_id").to_pylist() == ["kept-10", "kept-20"]
|
|
||||||
assert table.column("fecha_indice").to_pylist() == [date(2025, 1, 1), date(2025, 2, 1)]
|
|
||||||
assert table.schema.names == script.SCHEMA.names
|
|
||||||
|
|
||||||
|
|
||||||
def test_table_carries_the_lineage(script, build, events):
|
class _Timeline:
|
||||||
"""Pins down: the file explains itself: the build's identity and cut-offs are in its metadata. Fails if a key
|
"""Stands in for `timeline_repository`: the given rows, counting reads; the export cuts them itself too."""
|
||||||
a reader relies on is dropped or renamed."""
|
|
||||||
metadata = script.build_table(events, MEMBERS, build, domain="cacu", parametros='{"corte": "2025-12-31"}').schema.metadata
|
|
||||||
lineage = {k.decode(): v.decode() for k, v in metadata.items() if k not in (b"pandas", b"ARROW:schema")}
|
|
||||||
|
|
||||||
assert lineage["armado_id"] == "1" and lineage["url"] == build.url and lineage["n_members"] == "2"
|
def __init__(self, rows):
|
||||||
assert lineage["domain"] == "cacu" and lineage["producer"] == "kit" and lineage["datos_as_of"] == "2025-12-31"
|
self.rows, self.reads = rows, 0
|
||||||
assert lineage["parametros"] == '{"corte": "2025-12-31"}'
|
|
||||||
|
def read(self, *, until=None, **_):
|
||||||
|
self.reads += 1
|
||||||
|
return self.rows
|
||||||
|
|
||||||
|
|
||||||
def test_a_member_without_events_is_refused(script, build, events):
|
_query = DbtQueryRepository(lambda: Session(create_engine("sqlite://")))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def dbt_cohort():
|
||||||
|
"""Patients 10, 20 and 30, all indexed; one rule excludes 30."""
|
||||||
|
index = "select 10 as pac_id, '2025-01-01' as fecha_indice union all select 20, '2025-02-01' union all select 30, '2025-03-01'"
|
||||||
|
return CohortQueries(URL, "select 10 as pac_id union all select 20 union all select 30", index,
|
||||||
|
(ExclusionRule("third", "", 1, "select 30 as pac_id"),), date(2025, 12, 31), {"cutoff": "2025-12-31"})
|
||||||
|
|
||||||
|
|
||||||
|
def test_events_are_the_members_up_to_the_cutoff_in_order(events):
|
||||||
|
"""Pins down: only members' events, up to the cut-off, ordered by patient, each with its index date. Fails if the
|
||||||
|
cut-off or the join with the members is lost, or the rows aren't sorted."""
|
||||||
|
frame = cohort_events(events, POPULATION, date(2025, 12, 31))
|
||||||
|
|
||||||
|
assert frame["fuente_id"].tolist() == ["kept-10", "kept-20"]
|
||||||
|
assert frame["fecha_indice"].tolist() == [date(2025, 1, 1), date(2025, 2, 1)] and list(frame.columns) == SCHEMA.names
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_member_without_events_is_refused(events):
|
||||||
"""Pins down: every member has at least one row, so a timeline that lost someone stops the export. Fails if the
|
"""Pins down: every member has at least one row, so a timeline that lost someone stops the export. Fails if the
|
||||||
file is written with fewer members than the build."""
|
file is written with fewer members than the population."""
|
||||||
with pytest.raises(ValueError, match="1 members"):
|
with pytest.raises(ValueError, match="1 members"):
|
||||||
script.build_table([e for e in events if e["pac_id"] != 20], MEMBERS, build, domain="cacu", parametros=None)
|
cohort_events([e for e in events if e["pac_id"] != 20], POPULATION, date(2025, 12, 31))
|
||||||
|
|
||||||
|
|
||||||
def test_file_is_written_once(script, build, events, tmp_path):
|
def test_the_hash_follows_the_rows_only(events):
|
||||||
"""Pins down: a second run reuses the file without rebuilding it. Fails if `ensure` calls `make_table` again."""
|
"""Pins down: the same rows hash the same however they arrive, and another row changes the hash. Fails if the hash
|
||||||
calls = []
|
takes in the input order or misses a row."""
|
||||||
|
one = content_sha256(cohort_events(events, POPULATION, date(2025, 12, 31)))
|
||||||
|
reordered = content_sha256(cohort_events(events[::-1], POPULATION, date(2025, 12, 31)))
|
||||||
|
longer = content_sha256(cohort_events(events, POPULATION, date(2026, 12, 31)))
|
||||||
|
|
||||||
def make_table():
|
assert one == reordered != longer
|
||||||
calls.append(1)
|
|
||||||
return script.build_table(events, MEMBERS, build, domain="cacu", parametros=None)
|
|
||||||
|
|
||||||
path, first = script.ensure(build, tmp_path, make_table)
|
|
||||||
_, second = script.ensure(build, tmp_path, make_table)
|
def test_kit_build_is_written_once_with_its_lineage(kit, events, tmp_path):
|
||||||
|
"""Pins down: the kit's build goes to `<armado_id>.parquet` with its identity and cut-off, and a second run reuses it
|
||||||
|
without reading the timeline. Fails if the lineage loses a key a reader relies on, or the export repeats."""
|
||||||
|
timeline = _Timeline(events)
|
||||||
|
|
||||||
|
path, first = export_kit_build(kit, timeline, tmp_path, "cacu", URL)
|
||||||
|
_, second = export_kit_build(kit, timeline, tmp_path, "cacu", URL)
|
||||||
|
|
||||||
assert path == tmp_path / "cacu" / "cohorte_vigilancia" / "1.parquet"
|
assert path == tmp_path / "cacu" / "cohorte_vigilancia" / "1.parquet"
|
||||||
assert (first, second, len(calls)) == ("exported", "reused", 1)
|
assert (first, second, timeline.reads) == ("exported", "reused", 1)
|
||||||
assert pq.read_metadata(path).num_rows == 2
|
lineage = read_metadata(path)
|
||||||
|
assert lineage["armado_id"] == "1" and lineage["n_members"] == "2" and lineage["producer"] == "kit"
|
||||||
|
assert lineage["datos_as_of"] == "2025-12-31" and lineage["parametros"] == '{"corte": "2025-12-31"}'
|
||||||
|
|
||||||
|
|
||||||
def test_file_of_another_build_is_refused(script, build, events, tmp_path):
|
def test_file_of_another_build_is_refused(kit, events, tmp_path):
|
||||||
"""Pins down: a file whose lineage names another build isn't reused. Fails if `ensure` trusts the path alone."""
|
"""Pins down: a file whose lineage names another build isn't reused. Fails if the export trusts the path alone."""
|
||||||
other = tmp_path / "cacu" / "cohorte_vigilancia"
|
other = SimpleNamespace(**{**kit.__dict__, "build": lambda i: _build(armado_id=1, n_miembros=5)})
|
||||||
other.mkdir(parents=True)
|
export_kit_build(kit, _Timeline(events), tmp_path, "cacu", URL)
|
||||||
pq.write_table(script.build_table(events, MEMBERS, _build(armado_id=7), domain="cacu", parametros=None), other / "1.parquet")
|
|
||||||
|
|
||||||
with pytest.raises(ValueError, match="doesn't belong"):
|
with pytest.raises(ValueError, match="doesn't belong"):
|
||||||
script.ensure(build, tmp_path, lambda: pytest.fail("must not export"))
|
export_kit_build(other, _Timeline(None), tmp_path, "cacu", URL)
|
||||||
|
|
||||||
|
|
||||||
def test_failed_export_leaves_no_file(script, build, events, tmp_path, monkeypatch):
|
def test_unknown_kit_build_is_named(kit, tmp_path):
|
||||||
|
"""Pins down: a build that doesn't exist ends in `LookupError` before anything is read. Fails if it exports another."""
|
||||||
|
with pytest.raises(LookupError, match="no such build"):
|
||||||
|
export_kit_build(kit, _Timeline(None), tmp_path, "cacu", URL, build_id=9)
|
||||||
|
|
||||||
|
|
||||||
|
def test_dbt_build_writes_its_population_and_attrition(dbt_cohort, events, tmp_path):
|
||||||
|
"""Pins down: dbt's rules give the members, numbered in the `dbt/` folder, with their parameters, rules and attrition
|
||||||
|
in the lineage. Fails if the export ignores the rules, or the file lands where the kit's builds are looked for."""
|
||||||
|
path, outcome = export_dbt_build(dbt_cohort, _query, _Timeline(events), tmp_path, "cacu")
|
||||||
|
|
||||||
|
assert (path, outcome) == (tmp_path / "cacu" / "cohorte_vigilancia" / "dbt" / "1.parquet", "exported")
|
||||||
|
assert sorted(set(pq.read_table(path).column("pac_id").to_pylist())) == [10, 20]
|
||||||
|
lineage = read_metadata(path)
|
||||||
|
assert lineage["producer"] == "dbt" and lineage["build"] == "1" and lineage["rules"] == '["third"]'
|
||||||
|
assert '"step":"third","n":2,"excluded":1' in lineage["attrition"] and len(lineage["content_sha256"]) == 64
|
||||||
|
|
||||||
|
|
||||||
|
def test_dbt_build_is_reused_until_its_rows_change(dbt_cohort, events, tmp_path):
|
||||||
|
"""Pins down: building again with the same rows writes nothing; new rows write the next number. Fails if every run
|
||||||
|
writes a file, or a change is missed."""
|
||||||
|
first, _ = export_dbt_build(dbt_cohort, _query, _Timeline(events), tmp_path, "cacu")
|
||||||
|
again, outcome = export_dbt_build(dbt_cohort, _query, _Timeline(events), tmp_path, "cacu")
|
||||||
|
more = [*events, _event(20, "2025-04-01", "new-20")]
|
||||||
|
second, changed = export_dbt_build(dbt_cohort, _query, _Timeline(more), tmp_path, "cacu")
|
||||||
|
|
||||||
|
assert (again, outcome) == (first, "reused")
|
||||||
|
assert (second.name, changed) == ("2.parquet", "exported")
|
||||||
|
|
||||||
|
|
||||||
|
def test_failed_write_leaves_no_file(events, tmp_path, monkeypatch):
|
||||||
"""Pins down: when the last step of the write fails, neither the file nor the temporary one stays behind, so a
|
"""Pins down: when the last step of the write fails, neither the file nor the temporary one stays behind, so a
|
||||||
later run can't take a partial file as the build's. Fails if `write_once` stops removing the temporary file."""
|
later run can't take a partial file as the build's. Fails if `write_once` stops removing the temporary file."""
|
||||||
table = script.build_table(events, MEMBERS, build, domain="cacu", parametros=None)
|
table = pq.read_table(export_kit_build(SimpleNamespace(latest_build=lambda u: 1, build=lambda i: _build(), members=lambda i: MEMBERS,
|
||||||
|
get=lambda i: SimpleNamespace(parametros=None)),
|
||||||
|
_Timeline(events), tmp_path / "first", "cacu", URL)[0])
|
||||||
|
|
||||||
def fail(*_):
|
def fail(*_):
|
||||||
raise OSError("disk full")
|
raise OSError("disk full")
|
||||||
|
|
||||||
monkeypatch.setattr(Path, "replace", fail)
|
monkeypatch.setattr(Path, "replace", fail)
|
||||||
with pytest.raises(OSError, match="disk full"):
|
with pytest.raises(OSError, match="disk full"):
|
||||||
script.write_once(table, tmp_path / "cacu" / "1.parquet")
|
write_once(table, tmp_path / "cacu" / "1.parquet")
|
||||||
|
|
||||||
assert not list((tmp_path / "cacu").iterdir())
|
assert not list((tmp_path / "cacu").iterdir())
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("url", ["sqlite:////data/cacu.db", "sqlite:///file:/data/cacu.db?immutable=1&uri=true"])
|
def test_files_live_next_to_the_database(monkeypatch):
|
||||||
def test_files_live_next_to_the_database(script, monkeypatch, url):
|
"""Pins down: `cohorts/` next to the SQLite file. Fails if the default folder moves."""
|
||||||
"""Pins down: `cohorts/` next to the SQLite file, in both URL forms. Fails if a read-only URL's `file:` prefix
|
|
||||||
ends up in the path."""
|
|
||||||
monkeypatch.delenv("COHORTS_DIR", raising=False)
|
monkeypatch.delenv("COHORTS_DIR", raising=False)
|
||||||
assert script.cohorts_root(url) == Path("/data/cohorts")
|
assert cohorts_root("sqlite:////data/cacu.db") == Path("/data/cohorts")
|
||||||
|
|
||||||
|
|
||||||
def test_cohorts_dir_replaces_the_folder(script, monkeypatch):
|
def test_cohorts_dir_replaces_the_folder(monkeypatch):
|
||||||
"""Pins down: `COHORTS_DIR` wins, for read-only data folders and server engines. Fails if it's ignored."""
|
"""Pins down: `COHORTS_DIR` wins, for read-only data folders and server engines. Fails if it's ignored."""
|
||||||
monkeypatch.setenv("COHORTS_DIR", "/writable")
|
monkeypatch.setenv("COHORTS_DIR", "/writable")
|
||||||
assert script.cohorts_root("mysql://host/cacu") == Path("/writable")
|
assert cohorts_root("mysql://host/cacu") == Path("/writable")
|
||||||
|
|
||||||
|
|
||||||
def test_server_engine_needs_cohorts_dir(script, monkeypatch):
|
def test_server_engine_needs_cohorts_dir(monkeypatch):
|
||||||
"""Pins down: a server database has no data folder, so the script says what to set. Fails if it guesses a path."""
|
"""Pins down: a server database has no data folder, so the export says what to set. Fails if it guesses a path."""
|
||||||
monkeypatch.delenv("COHORTS_DIR", raising=False)
|
monkeypatch.delenv("COHORTS_DIR", raising=False)
|
||||||
with pytest.raises(ValueError, match="COHORTS_DIR"):
|
with pytest.raises(ValueError, match="COHORTS_DIR"):
|
||||||
script.cohorts_root("mysql://host/cacu")
|
cohorts_root("mysql://host/cacu")
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
def test_the_command_exports_from_dbt_through_the_session(cacu_db, tmp_path, monkeypatch, capsys):
|
||||||
def timeline_db(tmp_path):
|
"""Pins down: `cohorts export --source dbt` reads the manifest, runs the rules and the timeline through the domain's
|
||||||
"""A SQLite file with one event behind a `cacu_linea_de_tiempo` view, and a repository over it."""
|
session and writes the file, then reuses it. Fails if the wiring to the session, the manifest or the folder changes."""
|
||||||
path = tmp_path / "cacu.db"
|
import json
|
||||||
connection = sqlite3.connect(path)
|
|
||||||
connection.execute(f"create table eventos ({', '.join(TIMELINE_COLUMNS)})")
|
from persistance.db import get_cacu_engine
|
||||||
connection.execute("create view cacu_linea_de_tiempo as select * from eventos")
|
|
||||||
connection.execute("insert into eventos values (10, '2025-02-01', '2025-02-02', 'medicion', 'vph', 'vph', 'a', null, 't', '1')")
|
with get_cacu_engine().begin() as connection:
|
||||||
connection.commit()
|
connection.execute(text("create view cacu_linea_de_tiempo as select 10 as pac_id, '2025-02-01' as fecha, "
|
||||||
connection.close()
|
"'2025-02-02 10:00:00' as conocida_en, 'medicion' as clase, 'bethesda' as tipo, 'bethesda' as codigo, "
|
||||||
engine = create_engine(f"sqlite:///{path}")
|
"'NORMAL' as valor_codigo, null as valor_numerico, 't' as fuente_tabla, '1' as fuente_id"))
|
||||||
return path, TimelineRepository(lambda: Session(engine))
|
nodes = [
|
||||||
|
{"name": "p", "kind": "population", "sql": "select 10 as pac_id union all select 20",
|
||||||
|
"meta": {"cutoff": "2025-12-31", "parameters": '{"cutoff": "2025-12-31"}'}},
|
||||||
|
{"name": "i", "kind": "index", "sql": "select 10 as pac_id, '2025-01-01' as fecha_indice union all select 20, '2025-01-01'"},
|
||||||
|
{"name": "x", "kind": "exclusion", "sql": "select 20 as pac_id", "meta": {"name": "only", "order": 1}},
|
||||||
|
]
|
||||||
|
manifest = tmp_path / "manifest.json"
|
||||||
|
manifest.write_text(json.dumps({"nodes": {n["name"]: {
|
||||||
|
"name": n["name"], "unique_id": n["name"], "description": "", "compiled_code": n["sql"], "depends_on": {"nodes": []},
|
||||||
|
"config": {"meta": {"cohort": URL, "kind": n["kind"], **n.get("meta", {})}}} for n in nodes}}))
|
||||||
|
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
|
||||||
|
command = ["cohorts", "export", "cacu", "cohorte_vigilancia", "--source", "dbt", "--manifest", str(manifest)]
|
||||||
|
|
||||||
|
assert main(command) == 0 and main(command) == 0
|
||||||
|
|
||||||
|
out = capsys.readouterr().out
|
||||||
|
assert "exported:" in out and "reused:" in out
|
||||||
|
assert pq.read_table(tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt" / "1.parquet").column("pac_id").to_pylist() == [10]
|
||||||
|
|
||||||
|
|
||||||
def test_read_timeline_reads_the_view_and_changes_nothing(script, timeline_db):
|
@pytest.mark.parametrize("arguments, message", [
|
||||||
"""Pins down: the rows come from the domain's view, with the column contract, and the read adds no object. Fails
|
(["--source", "dbt"], "needs --manifest"),
|
||||||
if the script reads another relation, or starts creating objects in the database."""
|
(["--source", "dbt", "--manifest", "m.json", "--build", "1"], "can't go with --source dbt"),
|
||||||
path, repository = timeline_db
|
])
|
||||||
|
def test_dbt_source_arguments_are_checked(arguments, message, capsys):
|
||||||
|
"""Pins down: `--source dbt` needs the manifest and takes no kit build. Fails if either combination runs."""
|
||||||
|
with pytest.raises(SystemExit) as stopped:
|
||||||
|
main(["cohorts", "export", "cacu", "cohorte_vigilancia", *arguments])
|
||||||
|
|
||||||
rows = script.read_timeline(repository, "cacu")
|
assert stopped.value.code == 2 and message in capsys.readouterr().err
|
||||||
|
|
||||||
assert [(row["pac_id"], row["valor_codigo"]) for row in rows] == [(10, "a")]
|
|
||||||
connection = sqlite3.connect(path)
|
|
||||||
assert connection.execute("select name from sqlite_master order by name").fetchall() == [("cacu_linea_de_tiempo",), ("eventos",)]
|
|
||||||
connection.close()
|
|
||||||
|
|
||||||
|
|
||||||
def test_missing_view_says_how_to_create_it(script, timeline_db):
|
|
||||||
"""Pins down: without the view the error names the dbt command to run. Fails if the driver's error reaches the
|
|
||||||
user unexplained, or if the message stops naming the domain's model."""
|
|
||||||
_, repository = timeline_db
|
|
||||||
|
|
||||||
with pytest.raises(script.TimelineViewError, match="dbt run --select cama_linea_de_tiempo"):
|
|
||||||
script.read_timeline(repository, "cama")
|
|
||||||
|
|||||||
Reference in New Issue
Block a user