Estimates stored as batches of risks in the domain's database: models store and run --store; a kit file is read as dbt's only when its producer is dbt

This commit is contained in:
2026-11-06 00:21:53 -06:00
parent 22d1fda0f3
commit 761b5b03bc
9 changed files with 236 additions and 15 deletions
+1
View File
@@ -20,6 +20,7 @@ WebApi.
| `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. | | `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. |
| `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/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`. | | `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`. |
| `steps/risks.py`, `pipelines/store_risks.py` | Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`), through `cohorte_repository`: one preliminary risk per member at the model's horizon, with the version's MLflow keys. Storing the same estimate again adds nothing. A batch points to a kit build (`armado_id`), so estimates of dbt builds are refused. `python -m models store cacu cin2_logistic --input file.parquet`, or `run … --estimate --store --output file.parquet`. |
| `cacu/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within `outcome_window_months` (provisional, 12) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. Its steps (`model.py`, Hamilton nodes), driver (`train.py`) and settings (`model.toml`); it only reads the build's Parquet file. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]` (`estimate.py`), by default with 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/cin2_logistic/` | CaCu's CIN2+ prototype: the probability of a CIN2+ biopsy within `outcome_window_months` (provisional, 12) of the index cytology, from the index sample's Bethesda, HPV and HPV 16/18 results; no clinical validation. Its steps (`model.py`, Hamilton nodes), driver (`train.py`) and settings (`model.toml`); it only reads the build's Parquet file. Train with `python -m models train cacu cin2_logistic [--source kit|dbt] [--build N] [--environment dev|prod]`; estimate with `python -m models estimate cacu cin2_logistic --output file.parquet [--build N] [--version N]` (`estimate.py`), by default with 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). |
+33 -7
View File
@@ -77,6 +77,23 @@ def _estimate_step(args: argparse.Namespace, path) -> int:
return 0 return 0
def _store_step(args: argparse.Namespace, estimate_path) -> int:
from models.pipelines.store_risks import store_estimate
try:
batch, written = store_estimate(estimate_path, args.domain)
except (LookupError, ValueError, FileNotFoundError) as error:
print(error, file=sys.stderr)
return 1
print(f"{'stored' if written else 'already stored'}: batch {batch}, from {estimate_path}")
return 0
def _store(args: argparse.Namespace) -> int:
"""Stores an estimate file as a batch of risks in the domain's database."""
return _store_step(args, args.input)
def _estimate(args: argparse.Namespace) -> int: def _estimate(args: argparse.Namespace) -> int:
"""Scores the build's file with a registered version and writes the output file.""" """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)): if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)):
@@ -104,10 +121,10 @@ def _promote_step(args: argparse.Namespace, version: str) -> int:
def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int: 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.""" """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): if not (args.export or args.train or args.promote or args.estimate or args.store):
parser.error("name at least one step: --export, --train, --promote, --estimate") parser.error("name at least one step: --export, --train, --promote, --estimate, --store")
if args.estimate and not args.output: if (args.estimate or args.store) and not args.output:
parser.error("--estimate needs --output") parser.error("--estimate and --store need --output")
if args.train and args.environment == "prod" and args.armado is None and not (args.export and args.source == "dbt"): if args.train and args.environment == "prod" and args.armado is None and not (args.export and args.source == "dbt"):
parser.error("a prod run names its cohort build: --build (ML-03)") parser.error("a prod run names its cohort build: --build (ML-03)")
if args.export and args.source == "dbt" and not args.manifest: if args.export and args.source == "dbt" and not args.manifest:
@@ -128,7 +145,7 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
if code := _cohort_export(export): if code := _cohort_export(export):
return code return code
if not (args.train or args.promote or args.estimate): if not (args.train or args.promote or args.estimate):
return 0 return _store_step(args, args.output) if args.store else 0
if not (path := _cohort_file(args, model)): if not (path := _cohort_file(args, model)):
return 1 return 1
@@ -148,7 +165,9 @@ def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
return 1 return 1
if args.promote and (code := _promote_step(args, version)): if args.promote and (code := _promote_step(args, version)):
return code return code
return _estimate_step(args, path) if args.estimate else 0 if args.estimate and (code := _estimate_step(args, path)):
return code
return _store_step(args, args.output) if args.store else 0
def _cohort_build(args: argparse.Namespace) -> int: def _cohort_build(args: argparse.Namespace) -> int:
@@ -267,6 +286,12 @@ def build_parser() -> argparse.ArgumentParser:
estimate.add_argument("--version", help="the model version; the one in production by default") estimate.add_argument("--version", help="the model version; the one in production by default")
estimate.set_defaults(run=_estimate) estimate.set_defaults(run=_estimate)
store = commands.add_parser("store", help="store an estimate file as a batch of risks in the domain's database")
store.add_argument("domain", choices=["cacu", "cama", "tea"])
store.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
store.add_argument("--input", required=True, help="the Parquet file `estimate` wrote")
store.set_defaults(run=_store)
run = commands.add_parser("run", help="run the pipeline's steps you name; those already done are no-ops") 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("domain", choices=["cacu", "cama", "tea"])
run.add_argument("scenario", help="the model's folder, e.g. cin2_logistic") run.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
@@ -274,12 +299,13 @@ def build_parser() -> argparse.ArgumentParser:
run.add_argument("--train", action="store_true", help="train, unless a version from this file, code and environment exists") 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("--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("--estimate", action="store_true", help="score the build with --version, or the one in production")
run.add_argument("--store", action="store_true", help="store the estimate in --output as a batch of risks")
run.add_argument("--build", "--armado", dest="armado", type=int, run.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default") help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'") run.add_argument("--source", choices=["kit", "dbt"], default="kit", help="whose builds: the kit's or dbt's rules'")
run.add_argument("--version", help="an existing model version, for --promote and --estimate") 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("--environment", choices=["dev", "prod"], default="dev")
run.add_argument("--output", help="the Parquet file --estimate writes") run.add_argument("--output", help="the Parquet file --estimate writes and --store reads")
run.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --export --source dbt") run.add_argument("--manifest", help="the manifest.json `dbt compile` wrote; needed with --export --source dbt")
run.set_defaults(run=lambda args: _run(run, args)) run.set_defaults(run=lambda args: _run(run, args))
return parser return parser
+5 -3
View File
@@ -20,8 +20,8 @@ def already_estimated(output_path: Path, version: str, cohort: dict[str, str]) -
def estimate(cohort_path: str | Path, output_path: str | Path, version: str | None = None) -> tuple[ResolvedVersion, bool]: 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. """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 which build's file (`models.io.lineage.cohort_reference`) its rows The file's metadata says which version and which build's file (`models.io.lineage.cohort_reference`) its rows
come from; `modelo_sha` is copied when the version has come from, and the outcome and horizon they estimate (`cin2_12m`, 1.0 years); `modelo_sha` is copied when the
it, and isn't checked.""" version has it, and isn't checked."""
domain, scenario = SETTINGS["domain"], SETTINGS["scenario"] domain, scenario = SETTINGS["domain"], SETTINGS["scenario"]
output_path = Path(output_path) output_path = Path(output_path)
resolved = registry.resolve(domain, scenario, version) resolved = registry.resolve(domain, scenario, version)
@@ -31,8 +31,10 @@ def estimate(cohort_path: str | Path, output_path: str | Path, version: str | No
risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(cohort_path)) risks = mlflow.pyfunc.load_model(resolved.model_uri).predict(read_cohort(cohort_path))
if tuple(risks.columns) != ESTIMATE_COLUMNS: if tuple(risks.columns) != ESTIMATE_COLUMNS:
raise ValueError(f"version {resolved.version} returned {list(risks.columns)}, not {list(ESTIMATE_COLUMNS)}") raise ValueError(f"version {resolved.version} returned {list(risks.columns)}, not {list(ESTIMATE_COLUMNS)}")
window = SETTINGS["outcome_window_months"]
provenance = {"modelo_nombre": registered_name(domain, scenario), "modelo_version": resolved.version, provenance = {"modelo_nombre": registered_name(domain, scenario), "modelo_version": resolved.version,
"mlflow_run_id": resolved.run_id, **cohort} "mlflow_run_id": resolved.run_id, "desenlace": f"cin2_{window}m", "horizonte_anios": str(window / 12),
**cohort}
if resolved.modelo_sha: if resolved.modelo_sha:
provenance["modelo_sha"] = resolved.modelo_sha provenance["modelo_sha"] = resolved.modelo_sha
table = pa.Table.from_pandas(risks, preserve_index=False) table = pa.Table.from_pandas(risks, preserve_index=False)
+4 -3
View File
@@ -48,9 +48,10 @@ def model_sha(model_dir: str | Path) -> str:
def cohort_reference(metadata: dict[str, str], file_sha256: str) -> dict[str, str]: def cohort_reference(metadata: dict[str, str], file_sha256: str) -> dict[str, str]:
"""How a run, a version or an estimate points to the cohort build file it used: its cohort, who built it (`kit` or """How a run, a version or an estimate points to the cohort build file it used: its cohort, who built it (`kit` or
`dbt`), its number in that source and the file's hash. A kit build's number is its `armado_id`.""" `dbt`), its number in that source and the file's hash. Only a file whose producer is `dbt` is dbt's; any other is a kit
source = metadata.get("producer", "kit") build, numbered by its `armado_id`."""
build = metadata["armado_id"] if source == "kit" else metadata["build"] source = "dbt" if metadata.get("producer") == "dbt" else "kit"
build = metadata["build"] if source == "dbt" else metadata["armado_id"]
return {COHORT_URL_TAG: metadata["url"], COHORT_SOURCE_TAG: source, COHORT_BUILD_TAG: str(build), return {COHORT_URL_TAG: metadata["url"], COHORT_SOURCE_TAG: source, COHORT_BUILD_TAG: str(build),
COHORT_FILE_TAG: file_sha256} COHORT_FILE_TAG: file_sha256}
+8 -1
View File
@@ -1,5 +1,5 @@
"""Where the pipelines' data lives and how it's read and written: Parquet files (cohort builds and estimates), dbt's """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. manifest, a domain's Persistance repositories, and the batches of risks they store.
The kit's builds are `<root>/<domain>/<cohort>/<armado_id>.parquet`. The builds of dbt's rules go in a `dbt/` folder 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 beside them, numbered in order, so a lookup of the kit's builds never picks one up. Persistance is imported only where a
@@ -133,6 +133,13 @@ def read_queries(manifest: str | Path, url: str) -> CohortQueries:
date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}"))) date.fromisoformat(meta["cutoff"]), json.loads(meta.get("parameters", "{}")))
def store_risk_batch(domain: str, armado_id: int, provenance: dict, outcome: str, rows: list[tuple]) -> tuple[int, bool]:
"""Writes a batch of risks for a kit build through the domain's `cohorte_repository`: its `lote_id` and whether it's
new. The only write the pipelines make to the database; risks of anyone outside the build are refused."""
cohorts = importlib.import_module(f"persistance.{domain}").cohorte_repository
return cohorts.guardar_lote(armado_id, provenance, outcome, rows)
def resolve_repository(domain: str, entity: str): def resolve_repository(domain: str, entity: str):
"""`entity` is the repository's name in `persistance.<domain>` without """`entity` is the repository's name in `persistance.<domain>` without
the suffix, e.g. `"paciente"`, `"citologia_cervical"`.""" the suffix, e.g. `"paciente"`, `"citologia_cervical"`."""
+31
View File
@@ -0,0 +1,31 @@
"""Stores an estimate file as a batch of risks in the domain's database (`evaluacion_riesgo_lote`, `evaluacion_riesgo`).
The estimate's metadata carries everything the batch needs: the model version and its run (`modelo_nombre`,
`modelo_version`, `mlflow_run_id`, `modelo_sha`), the outcome and its horizon, and the cohort build it scored. A batch
points to its build by `armado_id`, so only builds with a row in `cohorte_armado` can be stored. Storing the same
estimate again adds nothing: Persistance finds the batch by its content.
"""
from pathlib import Path
import pandas as pd
from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG
from models.io.storage import read_metadata, store_risk_batch
from models.steps.risks import risk_rows
PROVENANCE = ("modelo_nombre", "modelo_version", "mlflow_run_id", "modelo_sha")
REQUIRED = (*PROVENANCE, "desenlace", "horizonte_anios", COHORT_SOURCE_TAG, COHORT_BUILD_TAG)
def store_estimate(estimate_path: str | Path, domain: str) -> tuple[int, bool]:
"""Returns the batch's `lote_id` and whether it was written now."""
metadata = read_metadata(estimate_path)
if missing := [key for key in REQUIRED if not metadata.get(key)]:
raise ValueError(f"{estimate_path} lacks {missing}: write it with `python -m models estimate`")
if metadata[COHORT_SOURCE_TAG] != "kit":
raise LookupError(f"{estimate_path} scores {metadata[COHORT_SOURCE_TAG]} build {metadata[COHORT_BUILD_TAG]}, "
"which has no row in cohorte_armado for its batch to point to")
rows = risk_rows(pd.read_parquet(estimate_path), float(metadata["horizonte_anios"]))
return store_risk_batch(domain, int(metadata[COHORT_BUILD_TAG]), {key: metadata[key] for key in PROVENANCE},
metadata["desenlace"], rows)
+17
View File
@@ -0,0 +1,17 @@
"""From an estimate's rows to the risks a batch stores: `(pac_id, horizonte_anios, probabilidad, ic_bajo, ic_alto)`."""
import pandas as pd
from models.io.contracts import ESTIMATE_COLUMNS
def risk_rows(estimate: pd.DataFrame, horizon_years: float) -> list[tuple]:
"""One risk per member at the model's horizon, without an interval; a member scored twice stops the batch."""
if tuple(estimate.columns) != ESTIMATE_COLUMNS:
raise ValueError(f"an estimate has {list(ESTIMATE_COLUMNS)}, not {list(estimate.columns)}")
if estimate["pac_id"].duplicated().any():
raise ValueError(f"members scored twice: {sorted(estimate.loc[estimate['pac_id'].duplicated(), 'pac_id'])[:10]}")
if not estimate["probabilidad"].between(0, 1).all():
raise ValueError("a probability outside 0..1")
return [(int(pac_id), float(horizon_years), float(probability), None, None)
for pac_id, probability in zip(estimate["pac_id"], estimate["probabilidad"])]
+16 -1
View File
@@ -7,7 +7,7 @@ Fixtures: none; each test builds its own small table or file.
import pyarrow as pa import pyarrow as pa
import pytest import pytest
from models.io.lineage import file_sha256, matches, registered_name, require_match, table_sha256 from models.io.lineage import cohort_reference, file_sha256, matches, registered_name, require_match, table_sha256
def test_a_table_hashes_by_its_rows_not_its_metadata(): def test_a_table_hashes_by_its_rows_not_its_metadata():
@@ -47,3 +47,18 @@ def test_a_mismatch_is_refused_with_both_sides():
def test_models_are_registered_as_domain_and_scenario(): 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.""" """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" assert registered_name("cacu", "cin2_logistic") == "cacu-cin2_logistic"
@pytest.mark.parametrize("metadata, expected", [
({"url": "u", "producer": "dbt", "build": "4"}, ("dbt", "4")),
({"url": "u", "producer": "kit", "armado_id": "2"}, ("kit", "2")),
({"url": "u", "producer": "kit build, timeline from dbt view", "armado_id": "1"}, ("kit", "1")),
({"url": "u", "armado_id": "3"}, ("kit", "3")),
])
def test_a_file_is_dbts_only_when_its_producer_says_dbt(metadata, expected):
"""Pins down: a cohort file's source is dbt only for `producer: dbt`; any other producer, or none, is a kit build
numbered by `armado_id`. Fails if an older kit file with a descriptive producer is read as dbt's and loses its
`armado_id`."""
reference = cohort_reference(metadata, "f" * 64)
assert (reference["cohort.source"], reference["cohort.build"]) == expected
+121
View File
@@ -0,0 +1,121 @@
"""What this module covers: storing an estimate file as a batch of risks (`models.steps.risks`,
`models.io.storage.store_risk_batch`, `models.pipelines.store_risks`) and the `models store` command: one risk per
member at the model's horizon, the batch's MLflow keys, no duplicate batch, and builds without a `cohorte_armado` row
refused.
Fixtures: `cacu_db` (conftest), an empty CaCu schema on SQLite; `kit_build`, kit build 1 with members 1 to 3;
`estimate_file`, an estimate of those members with the metadata `models estimate` writes.
"""
from datetime import date, datetime, timezone
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from sqlmodel import select
from models.__main__ import main
from models.pipelines.store_risks import store_estimate
from models.steps.risks import risk_rows
METADATA = {"modelo_nombre": "cacu-cin2_logistic", "modelo_version": "3", "mlflow_run_id": "run-a", "modelo_sha": "sha-a",
"desenlace": "cin2_12m", "horizonte_anios": "1.0", "cohort.url": "cacu/cohorte_vigilancia",
"cohort.source": "kit", "cohort.build": "1", "cohort.file_sha256": "f" * 64}
def _estimate(pac_ids=(1, 2, 3)):
return pd.DataFrame({"pac_id": list(pac_ids), "fecha_indice": [date(2025, 1, i) for i in pac_ids],
"probabilidad": [0.1 * i for i in pac_ids]})
def _write(frame, path, **metadata):
table = pa.Table.from_pandas(frame, preserve_index=False)
pq.write_table(table.replace_schema_metadata({**table.schema.metadata, **METADATA, **metadata}), path)
return path
@pytest.fixture
def kit_build(cacu_db):
"""Kit build 1 of the surveillance cohort, with members 1, 2 and 3 (and their `persona` rows)."""
from core.cacu.indicadores.models import CohorteArmado, CohorteMiembro, Persona
from persistance.db import get_cacu_session
with get_cacu_session() as session:
session.add_all(Persona(pac_id=i, pac_id_hospital=f"H{i}") for i in (1, 2, 3))
session.add(CohorteArmado(armado_id=1, url="cacu/cohorte_vigilancia", version="1", definicion_sha="d", reglas_sha="r",
parametros="{}", datos_as_of=date(2026, 12, 31), huella="h", marco_sha="m", n_miembros=3,
armado_en=datetime(2027, 1, 1, tzinfo=timezone.utc)))
session.add_all(CohorteMiembro(armado_id=1, pac_id=i, fecha_indice=date(2025, 1, i), indice_fuente_tabla="t",
indice_fuente_id=str(i)) for i in (1, 2, 3))
session.commit()
return 1
@pytest.fixture
def estimate_file(tmp_path):
return _write(_estimate(), tmp_path / "estimate.parquet")
def _stored():
from core.cacu.indicadores.models import EvaluacionRiesgo, EvaluacionRiesgoLote
from persistance.db import get_cacu_session
with get_cacu_session() as session:
return session.exec(select(EvaluacionRiesgoLote)).all(), session.exec(select(EvaluacionRiesgo)).all()
def test_each_member_becomes_one_risk_at_the_horizon():
"""Pins down: a risk is `(pac_id, horizonte_anios, probabilidad, None, None)`, one per member. Fails if the horizon is
dropped or the interval is filled with something the model didn't give."""
assert risk_rows(_estimate((1, 2)), 1.0) == [(1, 1.0, 0.1, None, None), (2, 1.0, 0.2, None, None)]
@pytest.mark.parametrize("frame", [_estimate((1, 1)), _estimate().assign(probabilidad=[0.1, 1.5, 0.2]),
_estimate().rename(columns={"probabilidad": "p"})])
def test_a_malformed_estimate_stops_the_batch(frame):
"""Pins down: a member scored twice, a probability outside 0..1, or other columns stop the batch before anything is
written. Fails if any of them reaches the database."""
with pytest.raises(ValueError):
risk_rows(frame, 1.0)
def test_storing_writes_one_batch_with_the_versions_keys(kit_build, estimate_file):
"""Pins down: the batch points to the kit build and to the MLflow version and run, holds the outcome, and its risks
are preliminary version 1 at the horizon. Fails if a key is lost or a risk is stored at another horizon."""
batch, written = store_estimate(estimate_file, "cacu")
batches, risks = _stored()
assert written and [b.lote_id for b in batches] == [batch]
assert (batches[0].armado_id, batches[0].modelo_version, batches[0].mlflow_run_id, batches[0].desenlace) == (1, "3", "run-a", "cin2_12m")
assert sorted((r.pac_id, r.horizonte_anios, r.estado, r.version) for r in risks) == [
(1, 1.0, "preliminary", 1), (2, 1.0, "preliminary", 1), (3, 1.0, "preliminary", 1)]
def test_storing_the_same_estimate_again_adds_nothing(kit_build, estimate_file, capsys):
"""Pins down: the command is idempotent: the second time it reports the existing batch. Fails if Persistance's
content check stops matching what this module sends."""
assert main(["store", "cacu", "cin2_logistic", "--input", str(estimate_file)]) == 0
assert main(["store", "cacu", "cin2_logistic", "--input", str(estimate_file)]) == 0
assert "already stored: batch 1" in capsys.readouterr().out
assert len(_stored()[0]) == 1
def test_a_dbt_build_has_no_batch_to_point_to(kit_build, tmp_path, capsys):
"""Pins down: an estimate of a dbt build is refused with the reason, since a batch needs a `cohorte_armado` row.
Fails if a dbt build's number is taken for a kit `armado_id`, which would point the batch to another build."""
path = _write(_estimate(), tmp_path / "dbt.parquet", **{"cohort.source": "dbt"})
assert main(["store", "cacu", "cin2_logistic", "--input", str(path)]) == 1
assert "cohorte_armado" in capsys.readouterr().err and not _stored()[0]
def test_an_estimate_without_its_keys_is_refused(kit_build, tmp_path):
"""Pins down: a file without the version's keys (a hand-made one, or one from an older `estimate`) isn't stored.
Fails if a batch could be written without knowing which model produced it."""
path = tmp_path / "bare.parquet"
pq.write_table(pa.Table.from_pandas(_estimate(), preserve_index=False), path)
with pytest.raises(ValueError, match="lacks"):
store_estimate(path, "cacu")