Merge dev into the Hamilton dataflow: the governance routines and the notebook runner on scenarios declared in model.toml
dev's 1b45bc6 (governance requirements, sandboxed notebooks) was written on the per-scenario driver that this branch
replaced with models.dags; it is carried over in that shape:
- cin2_logistic: the five ML-01a routines (sampling, missing_data, analytic_method, class_balance, output_confidence)
and `routines` are nodes of the scenario's dataflow, on its node names (windowed_outcomes, train_set, test_set,
fitted_pipeline, test_probabilities); `calibration_bins` is a config input with a default.
- io/adapters, dags/training: the saver writes each routine with TrainingRun.log_routine before logging the model;
the driver hands it `routines` when the dataflow has that node. Without it a scenario still trains, but the registry
won't promote it (ROUTINE_KINDS).
- io/tracking: dev's log_routine, run_files and run_file next to this branch's log_model (scikit-learn or pyfunc,
pinned requirements).
- reports/rendering: dev's Quarto and Jupyter renderers (io/rendering.py, followed as a rename) with this branch's
notebook hash; notebook_jobs and experiment import it from there, and cohort_reference and file_sha256 from
io/storage.
- cin2_logistic/train.py: a delegate to models.dags.training for callers of the old driver.
- Persistance's English names from dev: persistance.edges.gold, cohort_repository.
Tests: 219 passed against the monorepo's dev Persistance, Extraction and Core (OCR with tesseract deselected).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
This commit is contained in:
@@ -5,7 +5,8 @@ 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.
|
||||
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
|
||||
@@ -156,7 +157,7 @@ def test_the_graph_takes_exactly_its_config_and_the_cohort():
|
||||
required, optional = training.external_inputs(dataflow(*SCENARIO.modules, config=CONFIG))
|
||||
|
||||
assert required == {"cohort", "cohort_lineage", "event_grades", "horizons_years", "predictor_columns", "train_fraction"}
|
||||
assert optional == {"classifier", "max_iter", "split_order", "target_column"}
|
||||
assert optional == {"calibration_bins", "classifier", "max_iter", "split_order", "target_column"}
|
||||
|
||||
|
||||
def test_the_dataflow_reaches_its_metrics_without_mlflow(cohort_frame):
|
||||
@@ -194,6 +195,21 @@ def test_training_registers_a_version_with_its_lineage(cohort_file, 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."""
|
||||
@@ -281,6 +297,30 @@ 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."""
|
||||
@@ -300,11 +340,17 @@ def test_run_only_does_the_steps_it_is_given(exported, mlflow_tracking, tmp_path
|
||||
registry.resolve("cacu", "cin2_logistic")
|
||||
|
||||
|
||||
def test_repeating_every_step_changes_nothing(exported, mlflow_tracking, tmp_path, capsys):
|
||||
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", "--promote", "--estimate", "--output", str(output)]
|
||||
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()
|
||||
@@ -341,14 +387,17 @@ def test_another_models_version_trains_again(exported, mlflow_tracking, monkeypa
|
||||
|
||||
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."""
|
||||
`--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
|
||||
assert main([*RUN, "--promote", "--version", "1", "--estimate", "--output", str(output)]) == 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"
|
||||
|
||||
assert main([*RUN, "--promote", "--version", "2", "--estimate", "--output", str(output)]) == 0
|
||||
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"
|
||||
|
||||
@@ -404,11 +453,14 @@ def test_training_on_a_dbt_build_records_its_file_not_a_kit_build(dbt_exported,
|
||||
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."""
|
||||
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(["run", "cacu", "cin2_logistic", "--read", "file", "--source", "dbt", "--build", "1", "--environment", "prod",
|
||||
"--train", "--promote", "--estimate", "--output", str(output)]) == 0
|
||||
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"
|
||||
@@ -443,7 +495,7 @@ def test_by_default_the_command_reads_the_kit_build_from_the_database(cohort_fra
|
||||
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.cohorte_repository", cohorts)
|
||||
monkeypatch.setattr("persistance.cacu.cohort_repository", cohorts)
|
||||
monkeypatch.setattr("persistance.cacu.timeline_repository", timeline)
|
||||
|
||||
assert main(["train", "cacu", "cin2_logistic"]) == 0
|
||||
|
||||
Reference in New Issue
Block a user