Files
models/tests/cacu/test_cin2_logistic.py
edgar 410de1d3b7 Each scenario's index and rules in its pipeline, matching dbt's cohorts
models/steps/indexing.py: a scenario that lists it gets its source cohort as `source_cohort`, and the node `cohort`
re-indexes it by `[config.index]` of its model.toml: the surveillance kind (first cytology) and the post-colposcopy
kind (visit k), with dbt's rules in dbt's order and names, the recruitment window taken from the source cohort's
parameters. Every kind ends with `observacion_previa_insuficiente`, a threshold on the days observed before the index
(0 for now: the data are left-truncated, so rules on earlier events read only what was recorded). On the synthetic
copy the pipeline gives dbt's patients, index dates and attrition for cin2_pim and cin2_logistic (surveillance) and
cin2_pim_post_colposcopy (visit 1, now on cacu/cohorte_total). cin2_logistic's MUESTREO records the index attrition and
the prior history; a stored build's lineage carries its parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 21:54:47 -06:00

522 lines
28 KiB
Python

"""What this module covers: `models.cacu.cin2_logistic`: its outcome (a CIN2+ biopsy within the window, with members
whose window isn't complete left out) and predictors (the index sample's results), its temporal split, that training on
a build's file registers a version with its lineage, and the `models train`, `models estimate` and `models run`
commands over it, repeating no step.
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`; `dbt_exported`, builds 1 and 2
of dbt's rules; `mlflow_tracking` (conftest), a SQLite-backed MLflow; `cacu_db` (conftest), an empty CaCu database for
the promotion checks.
"""
from datetime import date, datetime, timedelta, timezone
import mlflow.pyfunc
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from models.__main__ import main
from models.cacu.cin2_logistic import model
from models.dags import training
from models.dags.training import Scenario, dataflow, find_trained, train
from models.io.contracts import COHORT_SCHEMA as SCHEMA
from models.io.lineage import ARMADO_TAG, MODEL_SHA_TAG
from models.io.registry import PRODUCTION_ALIAS, registry
from models.io.storage import CohortFile
from models.steps.model_fitting import train_test_split
CUTOFF = date(2027, 6, 30)
SCENARIO = Scenario.load("cacu", "cin2_logistic")
CONFIG = SCENARIO.config
PREDICTORS, GRADES = CONFIG["predictor_columns"], CONFIG["event_grades"]
def _outcomes(frame):
return model.windowed_outcomes(frame, CUTOFF, [1.0], GRADES)
def _row(pac_id, index, days, tipo, valor=None, sample=None, numero=None):
clase = {"citologia": "procedimiento", "biopsia": "medicion"}.get(tipo, "medicion")
return {"pac_id": pac_id, "fecha_indice": index, "fecha": index + timedelta(days=days),
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": clase, "tipo": tipo, "codigo": tipo,
"valor_codigo": valor, "valor_numerico": numero, "fuente_tabla": "citologiacervical",
"fuente_id": sample or f"{pac_id}-{tipo}-{days}"}
def _member(pac_id, index, bethesda, vph, biopsy=None, biopsy_day=60):
"""The index cytology, its Bethesda and HPV results (same sample, reported on day 7), and a biopsy if given."""
sample = f"S{pac_id}"
rows = [_row(pac_id, index, 0, "citologia", sample=sample), _row(pac_id, index, 7, "bethesda", bethesda, sample),
_row(pac_id, index, 7, "vph", vph, sample)]
if biopsy:
rows.append(_row(pac_id, index, biopsy_day, "biopsia", biopsy))
return rows
@pytest.fixture
def cohort_frame():
"""Odd members: LIEAG and HPV positive at the index sample, then a LIEAG biopsy on day 60 (the event). Even members:
NORMAL and HPV negative, then a second cytology on day 400 graded LIEAG, which the predictors must ignore."""
rows = []
for pac_id in range(1, 21):
index = date(2025, 1, 1) + timedelta(days=pac_id)
if pac_id % 2:
rows += _member(pac_id, index, "LIEAG", "POSITIVO", biopsy="LIEAG")
else:
rows += _member(pac_id, index, "NORMAL", "NEGATIVO")
rows += [_row(pac_id, index, 400, "citologia", sample=f"T{pac_id}"),
_row(pac_id, index, 405, "bethesda", "LIEAG", f"T{pac_id}")]
return pd.DataFrame(rows, columns=SCHEMA.names)
def _write(frame, path, metadata):
table = pa.Table.from_pandas(frame, schema=SCHEMA, preserve_index=False)
path.parent.mkdir(parents=True, exist_ok=True)
lineage = {"url": "cacu/cohorte_vigilancia", "datos_as_of": CUTOFF.isoformat(), **metadata}
pq.write_table(table.replace_schema_metadata({k: str(v) for k, v in lineage.items()}), path)
return path
@pytest.fixture
def cohort_file(cohort_frame, tmp_path):
"""The frame as build 7's file."""
return _write(cohort_frame, tmp_path / "7.parquet", {"armado_id": 7})
@pytest.fixture
def exported(cohort_frame, tmp_path, monkeypatch):
"""Builds 7 and 12 under `COHORTS_DIR`, in the folder the export writes to."""
folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia"
_write(cohort_frame, folder / "7.parquet", {"armado_id": 7})
_write(cohort_frame, folder / "12.parquet", {"armado_id": 12})
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
return folder
def test_predictors_are_the_index_sample_results(cohort_frame):
"""Pins down: each member's predictors come from the sample of the index cytology, matched by its source row, and a
result the sample doesn't have is `(none)`. Fails if a later sample's result (member 2's LIEAG on day 405) is
taken, or a missing result becomes NaN, which the encoder would reject."""
found = model.index_sample_results(cohort_frame, PREDICTORS).set_index("pac_id")
assert len(found) == 20
assert found.loc[1, ["bethesda", "vph", "vph_16_18"]].tolist() == ["LIEAG", "POSITIVO", "(none)"]
assert found.loc[2, ["bethesda", "vph"]].tolist() == ["NORMAL", "NEGATIVO"]
def test_the_genotype_is_read_from_its_number():
"""Pins down: the HPV 16/18 result is stored as 1 or 0 in `valor_numerico`, and becomes POSITIVO or NEGATIVO. Fails
if the genotype is read from `valor_codigo`, which is empty for it."""
index = date(2025, 1, 1)
frame = pd.DataFrame(_member(1, index, "ASC-US", "POSITIVO")
+ [_row(1, index, 7, "vph_genotipo_16_18", sample="S1", numero=1.0)], columns=SCHEMA.names)
assert model.index_sample_results(frame, PREDICTORS).loc[0, "vph_16_18"] == "POSITIVO"
@pytest.mark.parametrize("grade, day, expected", [("LIEAG", 60, 1), ("CARCINOMA", 300, 1), ("LIEBG", 60, 0),
("LIEAG", 400, 0)])
def test_the_outcome_is_a_cin2_biopsy_within_the_window(grade, day, expected):
"""Pins down: `y` is 1 only for a biopsy graded LIEAG, CIS or CARCINOMA within 12 months of the index date. Fails if
a lower grade counts, or a biopsy after the window does."""
frame = pd.DataFrame(_member(1, date(2025, 1, 1), "NORMAL", "NEGATIVO", biopsy=grade, biopsy_day=day),
columns=SCHEMA.names)
assert _outcomes(frame).loc[0, "y"] == expected
def test_a_member_without_a_complete_window_is_scored_but_not_trained_on():
"""Pins down: a member with no event and less than the window's follow-up to the cut-off isn't known and is left out
of `labelled_members`; one with the event is kept however short the follow-up. Fails if unknown members train as negatives,
which biases the risk down."""
late = date(2027, 3, 1)
frame = pd.DataFrame(_member(1, late, "NORMAL", "NEGATIVO") + _member(2, late, "LIEAG", "POSITIVO", biopsy="CIS",
biopsy_day=30), columns=SCHEMA.names)
outcome = _outcomes(frame).set_index("pac_id")
assert outcome["known"].tolist() == [False, True]
assert model.labelled_members(model.index_sample_results(frame, PREDICTORS), _outcomes(frame))["pac_id"].tolist() == [2]
def test_split_trains_on_the_oldest_index_dates(cohort_frame):
"""Pins down: the split is temporal: 70 % oldest train, the rest test, with no member in both. Fails if the split
is random or follows another column."""
labelled = model.labelled_members(model.index_sample_results(cohort_frame, PREDICTORS), _outcomes(cohort_frame))
parts = train_test_split(labelled, CONFIG["train_fraction"])
assert (len(parts["train_set"]), len(parts["test_set"])) == (14, 6)
assert parts["train_set"]["fecha_indice"].max() < parts["test_set"]["fecha_indice"].min()
def test_the_graph_takes_exactly_its_config_and_the_cohort():
"""Pins down the driver's external inputs: the loaders' `source_cohort` (re-indexed into `cohort` by the scenario's index) and `cohort_lineage` and the config's keys, and
nothing else. Fails if a node's parameter silently matches no node (a typo, a renamed node) and becomes an input,
or a module added to the driver rewires a parameter."""
required, optional = training.external_inputs(dataflow(*SCENARIO.modules, config=CONFIG))
assert required == {"source_cohort", "cohort_lineage", "event_grades", "horizons_years", "predictor_columns", "train_fraction"}
assert optional == {"calibration_bins", "classifier", "index", "max_iter", "split_order", "target_column"}
def test_the_dataflow_reaches_its_metrics_without_mlflow(cohort_frame):
"""Pins down: the scenario's graph, without the driver's adapters, runs from a frame to its metrics and its fitted
model with no file and no MLflow, and that model takes the long frame: one row per member, in `pac_id` order, the
same probabilities the fitted pipeline gives the test set. Fails if a node starts reading, writing or logging, a
node name stops matching `models.steps.model_fitting`'s, or `IndexSampleResults` orders members differently."""
lineage = {"datos_as_of": CUTOFF.isoformat()}
found = dataflow(*SCENARIO.modules, config=CONFIG).execute(
["metrics", "fitted_model", "test_set", "test_probabilities"],
inputs={"source_cohort": cohort_frame, "cohort_lineage": lineage})
assert found["metrics"]["n_train"] == 14 and found["metrics"]["n_test"] == 6
probabilities = found["fitted_model"].predict_proba(cohort_frame)
assert probabilities.shape == (20, 2)
test_rows = found["test_set"]["pac_id"].to_numpy() - 1
assert probabilities[test_rows, 1] == pytest.approx(found["test_probabilities"].to_numpy())
def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame, mlflow_tracking):
"""Pins down: the whole chain: a version with the build's id, metrics, `modelo_sha`, the file's hash, the outcome's
window and the note that it's a prototype, and a model that takes the long frame. Fails if any is lost, or if the
driver stops reaching `registered_model`."""
version = train(SCENARIO, CohortFile(cohort_file))
resolved = registry.resolve("cacu", "cin2_logistic", version)
stored = registry.get("cacu", "cin2_logistic", version)
run = registry.client.get_run(stored.run_id).data
assert stored.tags[ARMADO_TAG] == "7" and stored.tags[MODEL_SHA_TAG] == resolved.modelo_sha
assert "Prototipo" in stored.description and run.params["horizons_years"] == "[1.0]"
assert run.metrics["n_train"] == 14 and run.metrics["n_test"] == 6 and "auc" in run.metrics
assert len(run.params["cohort.file_sha256"]) == 64
probabilities = mlflow.pyfunc.load_model(resolved.model_uri).predict(cohort_frame)
assert probabilities.shape == (20, 2) and ((probabilities >= 0) & (probabilities <= 1)).all()
def test_training_records_each_routine_as_it_ran(cohort_file, cacu_db, mlflow_tracking):
"""ML-01a: the run holds what sampling, missing data, the method, class balance and calibration actually did, in
counts that add up to the split. Fails if a routine node stops being logged by `registered_model` or records
something other than this training's own numbers."""
version = train(SCENARIO, CohortFile(cohort_file))
routines = registry.routines(registry.get("cacu", "cin2_logistic", version).run_id)
assert set(routines) == {"MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"}
assert routines["MUESTREO"]["train"]["n"] == 14 and routines["MUESTREO"]["test"]["n"] == 6
assert sum(routines["BALANCE_CLASES"]["train"].values()) == 14
assert sum(b["n"] for b in routines["CONFIANZA_SALIDA"]["bins"]) == 6
assert routines["METODO_ANALITICO"]["coefficients"]
failed = {check.code for check in registry.checks("cacu", "cin2_logistic", version) if not check.passed}
assert "ML-01a" not in failed and "ML-01b" not in failed
def test_the_command_trains_on_the_latest_exported_build(exported, mlflow_tracking, capsys):
"""Pins down: with no `--armado`, the command uses the highest build number, not the last by name, and registers a
DEV version. Fails if builds sort as text (7 after 12), or the default environment changes."""
assert main(["train", "cacu", "cin2_logistic", "--read", "file"]) == 0
assert "version 1" in capsys.readouterr().out
stored = registry.get("cacu", "cin2_logistic", "1")
assert stored.tags[ARMADO_TAG] == "12" and stored.tags["environment"] == "DEV"
def test_the_command_trains_on_the_build_it_is_given_as_prod(exported, mlflow_tracking):
"""Pins down: `--armado` chooses the file and `--environment prod` tags the version PROD. Fails if either option
is ignored."""
assert main(["train", "cacu", "cin2_logistic", "--read", "file", "--armado", "7", "--environment", "prod"]) == 0
stored = registry.get("cacu", "cin2_logistic", "1")
assert stored.tags[ARMADO_TAG] == "7" and stored.tags["environment"] == "PROD"
def test_prod_without_a_build_is_refused(capsys):
"""Pins down: a prod run has to name its build (ML-03), and it's refused before anything loads. Fails if prod falls
back to the latest file."""
with pytest.raises(SystemExit) as stopped:
main(["train", "cacu", "cin2_logistic", "--read", "file", "--environment", "prod"])
assert stopped.value.code == 2 and "--build" in capsys.readouterr().err
@pytest.mark.parametrize("arguments, message", [
(["cacu", "ninguno"], "no such model: cacu/ninguno"),
(["cacu", "cin2_logistic", "--read", "file", "--armado", "99"], "export it"),
])
def test_what_is_missing_is_named(exported, arguments, message, capsys):
"""Pins down: an unknown model or a build with no file ends with exit 1 and says which, with no traceback and no
version. Fails if the command lets the import error through, or trains on another file."""
assert main(["train", *arguments]) == 1
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", "--read", "file"])
main(["train", "cacu", "cin2_logistic", "--read", "file"])
registry.client.set_registered_model_alias("cacu-cin2_logistic", PRODUCTION_ALIAS, "1")
output = tmp_path / "risks" / "output.parquet"
assert main(["estimate", "cacu", "cin2_logistic", "--read", "file", "--output", str(output)]) == 0
assert "version 1" in capsys.readouterr().out
risks = pd.read_parquet(output)
assert list(risks.columns) == ["pac_id", "fecha_indice", "horizonte_anios", "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"cohort.build"] == b"12" and metadata[b"cohort.source"] == b"kit"
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", "--read", "file"])
output = tmp_path / "output.parquet"
assert main(["estimate", "cacu", "cin2_logistic", "--read", "file", "--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", "--read", "file"])
output = tmp_path / "output.parquet"
assert main(["estimate", "cacu", "cin2_logistic", "--read", "file", "--output", str(output)]) == 1
assert "no version in production" in capsys.readouterr().err and not output.exists()
RUN = ["run", "cacu", "cin2_logistic", "--read", "file"]
def _versions():
return registry.client.search_model_versions("name='cacu-cin2_logistic'")
def _armado(armado_id: int) -> None:
"""A `CohorteArmado` row at this exact id, matching a build fixture's `armado_id` metadata: `registry.checks`'s
ML-03 looks the tag up by id, so promoting a kit-sourced version needs the row to exist, not just the tag."""
from datetime import date, datetime, timezone
from core.cacu.indicadores.models import CohorteArmado
from persistance.db import get_cacu_session
with get_cacu_session() as session:
session.add(CohorteArmado(
armado_id=armado_id, url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r",
parametros="{}", datos_as_of=date(2025, 12, 31), huella=f"huella-{armado_id}", marco_sha="m",
n_miembros=20, armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc)))
session.commit()
def _promotable(domain: str, scenario: str, version: str) -> None:
"""The three reports a fresh training run never carries (MLD-01/01b/03: attached by a human after training,
not by the training code), so the version clears every promotion check."""
registry.attach_reports(domain, scenario, version, technical_validation_report_uri="docs/tecnica.pdf",
clinical_validation_report_uri="docs/clinica.pdf",
interpretability_report_uri="docs/interpretabilidad.html")
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, cacu_db, 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", "--armado", "12", "--environment", "prod", "--promote", "--estimate", "--output",
str(output)]
_armado(12)
assert main([*RUN, "--train", "--armado", "12", "--environment", "prod"]) == 0
_promotable("cacu", "cin2_logistic", "1")
capsys.readouterr()
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", {"armado_id": 12})
assert main([*RUN, "--train", "--armado", "12"]) == 0
assert len(_versions()) == 3
def test_another_models_version_trains_again(exported, mlflow_tracking, monkeypatch):
"""Pins down: a version trained by another release of `models` isn't reused. Fails if the check stops comparing the
installed package's version."""
assert main([*RUN, "--train"]) == 0
assert find_trained(SCENARIO, CohortFile(exported / "12.parquet")) == "1"
monkeypatch.setattr(training, "code_version", lambda: {"models.version": "9.9.9"})
assert find_trained(SCENARIO, CohortFile(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. The alias is moved directly (not through `--promote`, which needs its
own promotion checklist satisfied, covered separately): this test is about `--estimate`'s own version tracking."""
output = tmp_path / "output.parquet"
assert main(["train", "cacu", "cin2_logistic", "--read", "file"]) == 0
assert main(["train", "cacu", "cin2_logistic", "--read", "file"]) == 0
registry.client.set_registered_model_alias("cacu-cin2_logistic", PRODUCTION_ALIAS, "1")
assert main([*RUN, "--estimate", "--output", str(output)]) == 0
assert pq.read_metadata(output).metadata[b"modelo_version"] == b"1"
registry.client.set_registered_model_alias("cacu-cin2_logistic", PRODUCTION_ALIAS, "2")
assert main([*RUN, "--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()
@pytest.fixture
def dbt_exported(cohort_frame, tmp_path, monkeypatch):
"""Builds 1 and 2 of dbt's rules under `COHORTS_DIR`, in the `dbt/` folder the export writes to; build 2 lacks member 1."""
folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt"
for number, frame in ((1, cohort_frame), (2, cohort_frame[cohort_frame["pac_id"] != 1])):
path = folder / f"{number}.parquet"
path.parent.mkdir(parents=True, exist_ok=True)
_write(frame, path, {"build": number, "producer": "dbt"})
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
return folder
def test_training_on_a_dbt_build_records_its_file_not_a_kit_build(dbt_exported, mlflow_tracking, capsys):
"""Pins down: `--source dbt` trains on the latest dbt build, and the version points to that file (cohort, source,
number, hash) with no kit `armado_id`, which would name a kit build that doesn't exist. Fails if the dbt folder is
ignored, or the version loses its cohort file."""
assert main(["train", "cacu", "cin2_logistic", "--read", "file", "--source", "dbt"]) == 0
tags = registry.get("cacu", "cin2_logistic", "1").tags
assert ARMADO_TAG not in tags
assert (tags["cohort.source"], tags["cohort.build"], tags["cohort.url"]) == ("dbt", "2", "cacu/cohorte_vigilancia")
assert len(tags["cohort.file_sha256"]) == 64 and "dbt/2.parquet" in capsys.readouterr().out
def test_a_prod_run_on_dbt_names_its_build_and_estimates_from_it(dbt_exported, mlflow_tracking, tmp_path):
"""Pins down: a PROD version from dbt build 1 is linked to that build (ML-03) without a kit build, and estimating
it writes the same file reference. Fails if PROD still demands a kit `armado_id`, or `--build` stops choosing the
dbt file. Also pins down that ML-03 (`registry.checks`) accepts a dbt cohort link, not only the kit's
`armado_id`: without that, `--promote` below would always be refused for a dbt-trained version."""
output = tmp_path / "output.parquet"
base = ["run", "cacu", "cin2_logistic", "--read", "file", "--source", "dbt", "--build", "1", "--environment", "prod"]
assert main([*base, "--train"]) == 0
_promotable("cacu", "cin2_logistic", "1")
assert main([*base, "--promote", "--estimate", "--output", str(output)]) == 0
tags = registry.get("cacu", "cin2_logistic", "1").tags
assert tags["environment"] == "PROD" and tags["cohort.build"] == "1"
metadata = pq.read_metadata(output).metadata
assert metadata[b"cohort.source"] == b"dbt" and metadata[b"cohort.build"] == b"1"
assert metadata[b"cohort.file_sha256"].decode() == tags["cohort.file_sha256"]
def test_a_missing_dbt_build_says_how_to_export_it(dbt_exported, capsys):
"""Pins down: a dbt build that isn't exported ends with exit 1 and the dbt export command. Fails if the kit's
command is suggested or another build is used."""
assert main(["train", "cacu", "cin2_logistic", "--read", "file", "--source", "dbt", "--build", "9"]) == 1
assert "--source dbt" in capsys.readouterr().err
def test_the_registered_artifact_runs_without_this_repository(cohort_file, cohort_frame, mlflow_tracking,
predict_without_repository):
"""Pins down: the version scores the long frame in a Python that can't import `models`, with the same probabilities
as in this one. Fails if `IndexSampleResults` starts using a function outside the scenario's package, which would
be pickled by reference."""
uri = registry.resolve("cacu", "cin2_logistic", train(SCENARIO, CohortFile(cohort_file))).model_uri
outside = predict_without_repository(uri, cohort_frame)
inside = mlflow.pyfunc.load_model(uri).predict(cohort_frame)
assert outside.to_numpy() == pytest.approx(inside)
def test_by_default_the_command_reads_the_kit_build_from_the_database(cohort_frame, kit_stand_ins, mlflow_tracking,
monkeypatch, capsys):
"""Pins down: with no `--read`, `train` reads the latest kit build's members and timeline through the domain's
repositories, cut at the build's date, writes no file, and the version points to the build with no file hash.
Fails if the default goes back to the exported file, or the source's reference keeps a hash it can't have."""
cohorts, timeline = kit_stand_ins(cohort_frame, 7, CUTOFF)
monkeypatch.setattr("persistance.cacu.cohort_repository", cohorts)
monkeypatch.setattr("persistance.cacu.timeline_repository", timeline)
assert main(["train", "cacu", "cin2_logistic"]) == 0
assert "from kit build 7" in capsys.readouterr().out
assert [read["until"] for read in timeline.reads] == [CUTOFF]
tags = registry.get("cacu", "cin2_logistic", "1").tags
assert (tags["cohort.source"], tags["cohort.build"], tags[ARMADO_TAG]) == ("kit", "7", "7")
assert "cohort.file_sha256" not in tags
def test_no_member_value_reaches_mlflow(cohort_frame, tmp_path, mlflow_tracking, mlflow_store_leaks):
"""Pins down the outcome the logger's and the saver's allowlists are there for: after training, no `pac_id` and no
source row id of the training data is in MLflow's database or artifacts, as text or as an integer. Fails if a
node's rows are logged, the model keeps the training frame, or an error message carries values."""
frame = cohort_frame.assign(pac_id=cohort_frame["pac_id"] + 987_650_000,
fuente_id="CANARY-" + cohort_frame["fuente_id"])
path = _write(frame, tmp_path / "input" / "7.parquet", {"armado_id": 7})
train(SCENARIO, CohortFile(path))
leaks = mlflow_store_leaks(tmp_path, texts=["CANARY-"], integers=frame["pac_id"].unique(), skip=("input",))
assert leaks == []