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:
2026-11-19 20:44:34 -06:00
43 changed files with 2304 additions and 229 deletions
+63 -11
View File
@@ -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
+29 -19
View File
@@ -1,3 +1,4 @@
import mlflow.pyfunc
import pytest
@@ -44,35 +45,44 @@ def mlflow_tracking(tmp_path, monkeypatch):
yield
class Echo(mlflow.pyfunc.PythonModel):
"""A model whose class lives in a module, as a PROD run requires: it returns its input."""
def predict(self, context, model_input, params=None):
return model_input
def trained_run(domain: str, scenario: str, armado_id: int | None, metrics: dict, *, routines=None, model: bool = True):
"""A finished PROD run as training leaves it: each routine's record (all of them unless `routines` names some)
and, with `model`, a saved model."""
from core.governance.enums import Environment
from models.io.tracking import ROUTINE_KINDS, TrainingRun
run = TrainingRun(domain=domain, scenario=scenario, environment=Environment.PROD, cohorte_armado_id=armado_id)
for kind in ROUTINE_KINDS if routines is None else routines:
run.log_routine(kind, {"method": "prueba", "n": 8})
if model:
run.log_model(Echo())
return run.finish(metrics=metrics)
@pytest.fixture
def production_ready(governance_db, cacu_db, mlflow_tracking):
"""Factory: registers a PROD version that passes every promotion check,
returns (domain, scenario, version)."""
from core.governance.enums import ArtifactKind, Environment
"""Factory: registers a PROD version whose run recorded every routine and its model, with the three reports,
so it passes every promotion check; returns (domain, scenario, version)."""
from models.io.registry import registry
def make(tag: str, *, domain: str = "cacu", scenario: str = "tamizaje", metrics: dict | None = None):
version = registry.register(
domain=domain, scenario=scenario, environment=Environment.PROD,
cohorte_armado_id=armado(f"huella-{tag}"), metrics=metrics or {"auc": 0.8},
technical_validation_report_uri="docs/tecnica.pdf", clinical_validation_report_uri="docs/clinica.pdf",
run = trained_run(domain, scenario, armado(f"huella-{tag}"), metrics or {"auc": 0.8})
version = registry.register_run(
run, technical_validation_report_uri="docs/tecnica.pdf", clinical_validation_report_uri="docs/clinica.pdf",
interpretability_report_uri="docs/interpretabilidad.html",
)
registry.add_artifact(domain, scenario, version, kind=ArtifactKind.ONNX_CHECKPOINT, filename="model.onnx", data=tiny_onnx())
return domain, scenario, version
return make
def tiny_onnx() -> bytes:
import onnx.helper
node = onnx.helper.make_node("Identity", ["x"], ["y"])
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
return onnx.helper.make_model(onnx.helper.make_graph([node], "tiny", [x], [y]), producer_name="pytest").SerializeToString()
def armado(huella: str) -> int:
"""A CaCu cohort build with two attrition steps; returns its `armado_id`."""
from datetime import date, datetime, timezone
@@ -130,13 +140,13 @@ def predict_without_repository(tmp_path):
@pytest.fixture
def kit_stand_ins():
"""Factory: stand-ins of a domain's `cohorte_repository` and `timeline_repository` holding one kit build made of a
"""Factory: stand-ins of a domain's `cohort_repository` and `timeline_repository` holding one kit build made of a
long frame's members and events, with dates as text as the database returns them. The timeline records each read's
patients and cut-offs."""
from datetime import datetime, timezone
from types import SimpleNamespace
from persistance.aristas.oro import CohortBuild, CohortMember
from persistance.edges.gold import CohortBuild, CohortMember
def make(frame, build_id, cutoff, url="cacu/cohorte_vigilancia"):
index_dates = frame.groupby("pac_id")["fecha_indice"].first()
+97
View File
@@ -0,0 +1,97 @@
"""Each domain's extraction ranker in the model registry
(`models.io.extraction_ranker`): every batch it learns from is a new DEV
version continuing the latest, with its five routine records and its saved
model; extraction takes the version in production, else the latest, and
`EXTRACTION_RANKER` can restrict or turn that off.
Fixtures: `mlflow_tracking` (a SQLite MLflow per test) and `_fresh_cache`
(an empty ranker cache and no `EXTRACTION_RANKER`). Batches are built
inline by `_batch` from candidates with the features an extractor gives
them; no document is read.
"""
import json
import mlflow.artifacts
import pytest
from extraction.document import BBox
from extraction.nlp import FieldKind, FieldSpec
from extraction.nlp.fields import Evidence, ExtractedValue
from extraction.nlp.ranking import examples_for
from models.io import extraction_ranker
from models.io.extraction_ranker import Batch, current, learn
from models.io.registry import registry
from models.io.tracking import ROUTINES_PATH
GRADO = FieldSpec("bx_cin_grado", FieldKind.CHOICE, choices={"NIC I": "LIEBG", "NIC II": "LIEAG"})
def _batch(right: str = "LIEBG") -> Batch:
evidence = Evidence("reporte.pdf", 1, "Diagnóstico: NIC I", BBox(0, 0, 1, 0.1).as_list())
candidates = [
ExtractedValue("LIEBG", 0.5, "etiqueta", "NIC I", evidence, {"assertion": "afirmado", "section": "resultado"}),
ExtractedValue("LIEAG", 0.6, "texto_libre", "NIC II", evidence, {"assertion": "afirmado", "section": "general"}),
]
examples = examples_for([GRADO], {"bx_cin_grado": candidates}, {"bx_cin_grado": right})
return Batch(examples, "revision", documents=1, records=1, unreachable={})
@pytest.fixture(autouse=True)
def _fresh_cache(monkeypatch):
"""No ranker cached from another test, and the default selection."""
monkeypatch.setattr(extraction_ranker, "_cache", {})
monkeypatch.delenv(extraction_ranker.SELECTION_ENV, raising=False)
def test_each_batch_is_a_new_dev_version_with_its_routines(mlflow_tracking):
"""Fails if learning stops registering a DEV version, its run loses one
of the five routine records or its saved model, which ML-01a and ML-01b
require to promote it."""
version = learn("cacu", _batch())
described = registry.get("cacu", extraction_ranker.SCENARIO, version)
assert described.tags["environment"] == "DEV"
checks = {c.code: c.passed for c in registry.checks("cacu", extraction_ranker.SCENARIO, version)}
assert checks["ML-01a"] and checks["ML-01b"]
def test_routine_records_hold_counts_never_document_text(mlflow_tracking):
"""What a ranker stores can be shared: weights and counts. Fails if a
routine record or the ranker's state carries a raw reading or the line
it came from."""
version = learn("cacu", _batch())
run_id = registry.get("cacu", extraction_ranker.SCENARIO, version).run_id
stored = json.dumps(mlflow.artifacts.load_dict(f"runs:/{run_id}/{extraction_ranker.RANKER_PATH}"))
for kind in ("MUESTREO", "DATOS_FALTANTES", "METODO_ANALITICO", "BALANCE_CLASES", "CONFIANZA_SALIDA"):
stored += mlflow.artifacts.load_text(f"runs:/{run_id}/{ROUTINES_PATH}/{kind}.json")
assert "NIC I" not in stored and "Diagnóstico" not in stored and "reporte.pdf" not in stored
def test_learning_continues_from_the_latest_version(mlflow_tracking):
"""Fails if a new batch starts from scratch instead of the latest
version, which would forget every earlier correction."""
learn("cacu", _batch())
second = learn("cacu", _batch())
ranker = current("cacu")
assert ranker.version == f"{extraction_ranker.SCENARIO}:{second}"
assert ranker.examples == 2 * len(_batch().examples)
def test_extraction_takes_production_first_and_can_be_turned_off(mlflow_tracking, monkeypatch):
"""With a version in production that one is used even when newer DEV
versions exist; `produccion` refuses DEV-only registries and `ninguno`
turns the ranker off. Fails if the selection order changes."""
assert current("cacu") is None
first = learn("cacu", _batch())
learn("cacu", _batch())
registry.client.set_registered_model_alias("cacu-extraccion", "produccion", first)
assert current("cacu").version == f"{extraction_ranker.SCENARIO}:{first}"
monkeypatch.setenv(extraction_ranker.SELECTION_ENV, "ninguno")
assert current("cacu") is None
monkeypatch.setenv(extraction_ranker.SELECTION_ENV, "produccion")
assert current("tea") is None
def test_an_empty_batch_registers_nothing(mlflow_tracking):
"""Fails if a review without usable examples creates a version."""
assert learn("cacu", Batch([], "revision", 0, 0, {})) is None
assert registry.versions("cacu", extraction_ranker.SCENARIO) == []
+49 -16
View File
@@ -1,4 +1,16 @@
"""What this module covers: the registry's promotion checks, promotion and retirement, the lineage of a version, and
what its run stored (`registry.artifacts`, `registry.artifact`, `registry.routines`).
Fixtures: `production_ready` (from `conftest.py`), a PROD version whose run recorded every routine and its model;
`governance_db`, `cacu_db` and `mlflow_tracking` (from `conftest.py`); `trained_run` and `armado` (from `conftest.py`)
build runs missing a routine or the model.
"""
import io
import json
import zipfile
import pytest
from conftest import armado, trained_run
from core.governance.enums import ArtifactKind, Environment
from models.io.registry import PromotionBlocked, registry
@@ -9,7 +21,7 @@ def test_dev_version_cannot_be_promoted_and_says_why(governance_db, mlflow_track
with pytest.raises(PromotionBlocked) as blocked:
registry.promote("cacu", "tamizaje", version)
failed = {check.code for check in blocked.value.checks if not check.passed}
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01b"}
assert failed == {"ML-02", "ML-03", "MLD-01", "MLD-01b", "MLD-03", "ML-01a", "ML-01b"}
def test_promotion_retires_the_previous_version_of_the_scenario(production_ready):
@@ -35,10 +47,44 @@ def test_reports_can_be_attached_after_training(production_ready):
registry.attach_reports(domain, scenario, version, metrics="{}")
def test_artifacts_are_logged_to_the_run(production_ready):
def test_lineage_lists_every_stored_file_and_each_routine_record(production_ready):
"""The lineage lists files inside folders (the saved model) and reads back each routine's record. Fails if
`run_files` stops descending into folders or `routines` stops reading `rutinas/`."""
domain, scenario, version = production_ready("v1")
lineage = registry.lineage(domain, scenario, version)
assert any(path.startswith(ArtifactKind.ONNX_CHECKPOINT.value) for path in lineage["artifacts"])
paths = {item["path"] for item in lineage["artifacts"]}
assert "model/MLmodel" in paths and "rutinas/MUESTREO.json" in paths
assert lineage["routines"]["BALANCE_CLASES"] == {"method": "prueba", "n": 8}
@pytest.mark.parametrize("routines, model, failing", [
([ArtifactKind.MUESTREO], True, "ML-01a"),
(None, False, "ML-01b"),
])
def test_promotion_needs_what_the_training_run_itself_recorded(governance_db, cacu_db, mlflow_tracking, routines, model,
failing):
"""A run that skipped routine records, or saved no model, is not promoted, whatever else is in order. Fails if
the ML-01a check stops requiring every kind in `ROUTINE_KINDS` or the ML-01b check stops requiring `modelo_sha`."""
run = trained_run("cacu", "incompleta", armado("huella-x"), {"auc": 0.8}, routines=routines, model=model)
version = registry.register_run(run, technical_validation_report_uri="t", clinical_validation_report_uri="c",
interpretability_report_uri="i")
failed = [check for check in registry.checks("cacu", "incompleta", version) if not check.passed]
assert [check.code for check in failed] == [failing]
if failing == "ML-01a":
assert "DATOS_FALTANTES" in failed[0].detail
def test_an_artifact_downloads_as_a_file_and_a_folder_as_a_zip(production_ready):
"""ML-01b: a stored file comes back as itself; the model folder as a zip of its files. Fails if `run_file`
stops zipping folders or starts accepting a path the run doesn't list."""
domain, scenario, version = production_ready("v1")
name, data = registry.artifact(domain, scenario, version, "rutinas/MUESTREO.json")
assert name == "MUESTREO.json" and json.loads(data)["n"] == 8
name, data = registry.artifact(domain, scenario, version, "model")
assert name == "model.zip" and "model/MLmodel" in zipfile.ZipFile(io.BytesIO(data)).namelist()
for wrong in ("../mlflow.db", "", "rutinas/OTRO.json"):
with pytest.raises(LookupError):
registry.artifact(domain, scenario, version, wrong)
def test_retire_and_lineage(production_ready):
@@ -55,19 +101,6 @@ def test_retire_and_lineage(production_ready):
registry.retire(domain, scenario, second)
def test_invalid_onnx_checkpoint_is_rejected(production_ready):
from models.io.tracking import inspect_onnx_metadata
with pytest.raises(ValueError, match="ONNX"):
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "x.onnx"
path.write_bytes(b"weights")
inspect_onnx_metadata(path)
@pytest.mark.parametrize("domain, scenario", [("cacu' OR '1'='1", None), ("cacu", "x' OR name LIKE '%")])
def test_version_filters_reject_anything_but_known_names(mlflow_tracking, domain, scenario):
with pytest.raises(ValueError):
+5 -5
View File
@@ -19,11 +19,11 @@ def test_dev_run_does_not_require_a_cohort_build(mlflow_tracking):
def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path):
checkpoint = tmp_path / "model.onnx"
checkpoint.write_bytes(b"fake-onnx-bytes")
notes = tmp_path / "notas.json"
notes.write_text("{}")
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
run.log_artifact(ArtifactKind.ONNX_CHECKPOINT, checkpoint, metadata={"opset": 17})
run.log_artifact(ArtifactKind.OTRO, notes, metadata={"origen": "prueba"})
version = registry.register_run(run.finish(metrics={"auc": 0.81}))
mv = registry.get("cacu", "tamizaje", version)
@@ -31,8 +31,8 @@ def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path)
metrics = registry.client.get_run(mv.run_id).data.metrics
assert metrics["auc"] == 0.81
artifacts = [a.path for a in registry.client.list_artifacts(mv.run_id, path=ArtifactKind.ONNX_CHECKPOINT.value)]
assert any(path.endswith("model.onnx") for path in artifacts)
artifacts = [a.path for a in registry.client.list_artifacts(mv.run_id, path=ArtifactKind.OTRO.value)]
assert any(path.endswith("notas.json") for path in artifacts)
def test_read_only_repository_blocks_writes(cacu_db):
-60
View File
@@ -1,60 +0,0 @@
import onnx
import onnx.helper
import pytest
from models.io.tracking import inspect_onnx_metadata
def _tiny_onnx_bytes() -> bytes:
node = onnx.helper.make_node("Identity", ["x"], ["y"])
x = onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
graph = onnx.helper.make_graph([node], "tiny", [x], [y])
model = onnx.helper.make_model(graph, producer_name="pytest-fixture")
return model.SerializeToString()
def test_inspect_onnx_metadata_reads_producer_and_io(tmp_path):
path = tmp_path / "model.onnx"
path.write_bytes(_tiny_onnx_bytes())
metadata = inspect_onnx_metadata(path)
assert metadata["available"] is True
assert metadata["producer_name"] == "pytest-fixture"
assert metadata["graph_inputs"] == ["x"]
assert metadata["graph_outputs"] == ["y"]
def test_inspect_onnx_metadata_rejects_structurally_invalid_model(tmp_path):
"""A protobuf-valid but structurally broken graph (a node reading an
input the graph never declares) must be rejected: `onnx.load` alone
only parses the protobuf and would let this through."""
node = onnx.helper.make_node("Identity", ["undeclared_input"], ["y"])
y = onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])
graph = onnx.helper.make_graph([node], "broken", [], [y])
model = onnx.helper.make_model(graph, producer_name="pytest-fixture")
path = tmp_path / "model.onnx"
path.write_bytes(model.SerializeToString())
with pytest.raises(ValueError, match="no es un modelo ONNX válido"):
inspect_onnx_metadata(path)
def test_inspect_onnx_metadata_without_onnx_available(monkeypatch, tmp_path):
import builtins
real_import = builtins.__import__
def fake_import(name, *args, **kwargs):
if name == "onnx":
raise ImportError("onnx not installed")
return real_import(name, *args, **kwargs)
monkeypatch.setattr(builtins, "__import__", fake_import)
path = tmp_path / "model.onnx"
path.write_bytes(b"irrelevant")
assert inspect_onnx_metadata(path) == {
"available": False,
"reason": "el paquete 'onnx' no está instalado (extra 'export')",
}
+226
View File
@@ -0,0 +1,226 @@
"""What this module covers: notebooks run on a cohort build's file as MLflow runs (`models.pipelines.experiment`), the
job folder and its executors (`models.io.notebook_jobs`), the import of what a notebook trained
(`models.io.notebook_import`), the API notebooks use inside (`models.notebook`) and the Jupyter renderer: what the
notebook can reach, what the run keeps, a notebook that fails, a notebook that tries to reach past its job, the runner
as the container runs it, and listing and reading runs back.
Fixtures: `cohort_file`, a dbt build's file of two members with its metadata; `jupyter`, the Jupyter renderer chosen
and MLflow's artifacts kept under the test's folder; `mlflow_tracking` (conftest), a SQLite-backed MLflow. Notebooks
are built inline with `_notebook`, naming a kernel the server doesn't have, as an author's would; they run in a real
kernel, the platform's own (fails if `notebook_jobs.KERNEL` stops replacing it). `Echo` (conftest) is the saved
model a notebook is given.
"""
import json
from datetime import date, datetime, timezone
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from models.io.contracts import COHORT_SCHEMA
from models.io.registry import registry
from models.pipelines import experiment
def _notebook(*sources: str) -> dict:
return {"cells": [{"cell_type": "code", "metadata": {}, "execution_count": None, "outputs": [], "source": [s]}
for s in sources],
"metadata": {"kernelspec": {"name": "un-kernel-local", "display_name": "local", "language": "python"}},
"nbformat": 4, "nbformat_minor": 5}
@pytest.fixture
def cohort_file(tmp_path):
rows = [{"pac_id": pac_id, "fecha_indice": date(2025, 1, pac_id), "fecha": date(2025, 1, pac_id),
"conocida_en": datetime(2026, 1, 1, tzinfo=timezone.utc), "clase": "procedimiento", "tipo": "citologia",
"codigo": "citologia", "valor_codigo": None, "valor_numerico": None, "fuente_tabla": "citologiacervical",
"fuente_id": f"S{pac_id}"} for pac_id in (1, 2)]
table = pa.Table.from_pandas(pd.DataFrame(rows, columns=COHORT_SCHEMA.names), schema=COHORT_SCHEMA, preserve_index=False)
path = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt" / "3.parquet"
path.parent.mkdir(parents=True)
metadata = {"url": "cacu/cohorte_vigilancia", "producer": "dbt", "build": "3", "datos_as_of": "2025-12-31"}
pq.write_table(table.replace_schema_metadata(metadata), path)
return path
@pytest.fixture
def jupyter(tmp_path, monkeypatch, mlflow_tracking):
monkeypatch.setenv("NOTEBOOK_RENDERER", "jupyter")
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(tmp_path / "artefactos"))
monkeypatch.setenv("CACU_DATABASE_URL", f"sqlite:///{tmp_path / 'real-cacu.db'}")
def test_a_notebook_reads_its_build_and_no_database(jupyter, cohort_file):
"""The notebook gets the build's file through `models.notebook` and only an empty in-memory database, whatever the
server's own URLs are. Fails if `notebook_env` starts passing the server's environment or the build's file stops
reaching the kernel."""
notebook = _notebook("import os\nfrom models.notebook import experiment\nexp = experiment()",
"print('members', exp.cohort().pac_id.nunique(), os.environ['CACU_DATABASE_URL'] or 'none')")
run_id, ok = experiment.run_notebook(notebook, "lee.ipynb", cohort_file, "cacu", "exploracion")
assert ok, experiment.describe(run_id)["error"]
page = experiment.page(run_id)
assert "members 2 sqlite://" in page and "real-cacu" not in page
def test_the_run_keeps_the_notebook_its_page_and_its_inputs(jupyter, cohort_file):
"""The run is tagged with the notebook's hash and the build, and keeps the notebook as uploaded and its page.
Fails if `start` stops tagging the inputs or storing the source."""
run_id, _ = experiment.run_notebook(_notebook("print(1 + 1)"), "../../otro/suma.ipynb", cohort_file, "cacu", "exploracion")
run = experiment.describe(run_id)
assert run["status"] == "terminado" and run["notebook"] == "suma"
assert run["cohort"] == {"url": "cacu/cohorte_vigilancia", "source": "dbt", "build": "3"}
assert {a["path"] for a in run["artifacts"]} == {"notebook/suma.ipynb", "report/suma.html", "importado.json"}
assert run["sandbox"] == "local"
name, data = experiment.artifact(run_id, "notebook/suma.ipynb")
assert json.loads(data)["cells"][0]["source"] == ["print(1 + 1)"]
def test_a_failing_cell_fails_the_run_and_keeps_what_ran(jupyter, cohort_file):
"""A cell that raises ends the run as failed with the error, and the page shows the cells up to it. Fails if
`execute` loses the partial page or leaves the run open."""
run_id, ok = experiment.run_notebook(_notebook("print('antes')", "1 / 0", "print('despues')"), "falla", cohort_file,
"cacu", "exploracion")
run = experiment.describe(run_id)
assert not ok and run["status"] == "fallido" and "ZeroDivisionError" in run["error"]
assert "antes" in experiment.page(run_id) and "despues" not in experiment.page(run_id).split("ZeroDivisionError")[0]
def test_a_notebook_can_train_and_register_a_dev_version(jupyter, cohort_file):
"""Through `models.notebook`, a notebook opens a DEV run linked to its build, records a routine and registers it;
the import brings run and version into the platform's MLflow. Fails if `Experiment.training_run` stops linking
the build, or `import_job` stops copying runs, their files or their versions."""
notebook = _notebook("from models.notebook import experiment\nexp = experiment()\nrun = exp.training_run()\n"
"run.log_routine('MUESTREO', {'n': 2})\nprint('version', exp.register(run.finish(metrics={'n': 2})))")
run_id, ok = experiment.run_notebook(notebook, "entrena", cohort_file, "cacu", "prueba_nb")
assert ok, experiment.describe(run_id)["error"]
stored = registry.get("cacu", "prueba_nb", "1")
assert stored.tags["environment"] == "DEV" and stored.tags["cohort.build"] == "3"
assert registry.routines(stored.run_id) == {"MUESTREO": {"n": 2}}
assert stored.tags["notebook.run_id"] == run_id
def test_runs_are_listed_by_scenario_and_only_notebook_runs_are_read(jupyter, cohort_file):
"""Listing finds notebook runs by domain and scenario; reading a run that isn't a notebook's is refused. Fails if
`experiments` mixes scenarios or `describe` serves any run."""
first, _ = experiment.run_notebook(_notebook("1"), "a", cohort_file, "cacu", "uno")
experiment.run_notebook(_notebook("2"), "b", cohort_file, "cacu", "dos")
assert [r["run_id"] for r in experiment.experiments("cacu", "uno")] == [first]
assert len(experiment.experiments("cacu")) == 2
with pytest.raises(ValueError):
experiment.experiments("cacu", "x' OR '1'='1")
from mlflow import MlflowClient
other = MlflowClient().create_run("0").info.run_id
with pytest.raises(LookupError):
experiment.describe(other)
@pytest.mark.parametrize("notebook", [{"cells": "x"}, {"cells": [], "nbformat": 3}, []])
def test_what_isnt_a_notebook_is_refused(notebook, jupyter, cohort_file):
"""Fails if `check_notebook` lets through something nbclient can't run."""
with pytest.raises(ValueError):
experiment.start(notebook, "x", cohort_file, "cacu", "exploracion")
def test_a_notebook_cannot_reach_the_platforms_mlflow_or_put_a_version_in_production(jupyter, cohort_file):
"""The notebook's MLflow is its job's own store; a version it registers as PROD with the production alias comes
across as DEV with no alias, and the cohort tags are the build it really had. Fails if the job's environment
starts pointing at the platform's MLflow, or `import_job` starts trusting the notebook's tags or aliases."""
notebook = _notebook(
"import mlflow\nfrom mlflow import MlflowClient\nfrom models.notebook import experiment\nexp = experiment()\n"
"print('tracking', 'mlflow.db' in mlflow.get_tracking_uri() and 'trabajo' not in mlflow.get_tracking_uri())",
"from models.io.tracking import TrainingRun\nfrom models.io.registry import registry\n"
"run = TrainingRun(domain='cacu', scenario='colado', environment='DEV')\n"
"MlflowClient().set_tag(run.run_id, 'cohort.build', '999')\n"
"version = registry.register_run(run.finish(metrics={'auc': 0.99}))\n"
"MlflowClient().set_model_version_tag('cacu-colado', version, 'environment', 'PROD')\n"
"MlflowClient().set_registered_model_alias('cacu-colado', 'produccion', version)")
run_id, ok = experiment.run_notebook(notebook, "colado", cohort_file, "cacu", "colado")
assert ok, experiment.describe(run_id)["error"]
assert "tracking True" in experiment.page(run_id)
stored = registry.get("cacu", "colado", "1")
assert stored.tags["environment"] == "DEV" and stored.tags["cohort.build"] == "3"
with pytest.raises(LookupError):
registry.resolve("cacu", "colado")
def test_files_a_notebook_links_outside_its_job_are_never_read(jupyter, cohort_file, tmp_path):
"""A run whose files hold a symbolic link to a file of the server is left out, and the file's content never
reaches MLflow. Fails if `import_job` follows links while copying a run's files."""
secret = tmp_path / "secreto.txt"
secret.write_text("CONTENIDO-PRIVADO")
notebook = _notebook(
"import os\nfrom pathlib import Path\nfrom models.notebook import experiment\nexp = experiment()\n"
"run = exp.training_run()\nrun.log_routine('MUESTREO', {'n': 1})\n"
"folder = Path(run.client.get_run(run.run_id).info.artifact_uri)\n"
f"os.symlink({str(secret)!r}, folder / 'robado.txt')\nrun.finish()")
run_id, ok = experiment.run_notebook(notebook, "enlace", cohort_file, "cacu", "enlace")
assert ok
summary = json.loads(experiment.artifact(run_id, "importado.json")[1])
assert summary["runs"] == [] and "enlace" in summary["skipped"][0]["reason"]
def test_read_job_file_refuses_links_and_paths_out_of_the_job(tmp_path):
"""Fails if `read_job_file` follows a symbolic link or a `..` path out of the job folder."""
from models.io.notebook_jobs import JobError, read_job_file
job = tmp_path / "job"
job.mkdir()
(tmp_path / "fuera.txt").write_text("x")
(job / "page.html").symlink_to(tmp_path / "fuera.txt")
for relative in ("page.html", "../fuera.txt"):
with pytest.raises(JobError):
read_job_file(job, relative)
assert read_job_file(job, "no-existe.json") is None
def test_the_runner_runs_jobs_left_for_the_container(cohort_file, tmp_path, monkeypatch, mlflow_tracking):
"""With a jobs folder, the WebApi side leaves the job and waits; a separate `models notebooks serve` process with
no MLflow or database settings runs it, and the run says it ran in the container. Fails if the executor stops
waiting for `result.json`, or the runner needs anything but the jobs folder."""
import subprocess
import sys
jobs = tmp_path / "trabajos"
jobs.mkdir()
monkeypatch.setenv("NOTEBOOK_JOBS_DIR", str(jobs))
monkeypatch.setenv("NOTEBOOK_JOB_TIMEOUT", "120")
clean = {k: v for k, v in __import__("os").environ.items()
if not k.startswith(("MLFLOW_", "CACU_", "CAMA_", "TEA_", "GOVERNANCE_", "NOTEBOOK_JOBS"))}
clean["NOTEBOOK_RENDERER"] = "jupyter"
runner = subprocess.Popen([sys.executable, "-m", "models", "notebooks", "serve", "--jobs", str(jobs)], env=clean,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
run_id, ok = experiment.run_notebook(_notebook("print('desde el contenedor')"), "cont", cohort_file, "cacu",
"contenedor")
finally:
runner.terminate()
runner.wait(10)
run = experiment.describe(run_id)
assert ok and run["sandbox"] == "contenedor"
assert "desde el contenedor" in experiment.page(run_id)
assert list(jobs.iterdir()) == []
def test_a_notebook_given_a_version_loads_its_copy_of_the_model(jupyter, cohort_file):
"""The chosen version's saved model is copied into the job and `exp.model()` loads it there, with no access to
the registry. Fails if `execute` stops copying the model or `Experiment.model` stops preferring `MODEL_PATH`."""
import cloudpickle
import conftest
from models.io.tracking import TrainingRun
cloudpickle.register_pickle_by_value(conftest)
try:
run = TrainingRun(domain="cacu", scenario="probada", environment="DEV")
run.log_model(conftest.Echo())
version = registry.register_run(run.finish())
finally:
cloudpickle.unregister_pickle_by_value(conftest)
notebook = _notebook("import os, pandas as pd\nfrom models.notebook import experiment\n"
"model = experiment().model()\n"
"print('copia', os.environ['MODEL_PATH'].endswith('/model'), model.predict(pd.DataFrame({'a': [7]}))['a'][0])")
run_id, ok = experiment.run_notebook(notebook, "usa", cohort_file, "cacu", "probada", version)
assert ok, experiment.describe(run_id)["error"]
assert "copia True 7" in experiment.page(run_id)
+4 -4
View File
@@ -2,7 +2,7 @@
run by a Hamilton driver built from that module alone, and their place in the asset graph.
Fixtures: `repositories`, an in-memory SQLite database with the CaCu tables, one cohort build and a plain
`timeline_events` table; it returns the `CohorteRepository` and a `TimelineRepository` bound to
`timeline_events` table; it returns the `CohortRepository` and a `TimelineRepository` bound to
`timeline_query`, which stands in for the kit's query over that table. `_run` builds the driver and
executes the requested nodes.
"""
@@ -22,8 +22,8 @@ from core.cacu.indicadores.models import (
)
from core.indicadores.cohortes import TablasCohorte
from hamilton import driver
from persistance.aristas.oro import CohorteRepository
from persistance.aristas.plata import TIMELINE_COLUMNS, TimelineRepository
from persistance.edges.gold import CohortRepository
from persistance.edges.silver import TIMELINE_COLUMNS, TimelineRepository
from persistance.assets import Asset, InvalidGraph, validate
from sqlalchemy import Column, Date, DateTime, Float, Integer, MetaData, String, Table, insert, select
from sqlalchemy.pool import StaticPool
@@ -102,7 +102,7 @@ def repositories():
session.connection().execute(insert(events), EVENTS)
session.commit()
factory = lambda: Session(engine) # noqa: E731
return CohorteRepository(factory, TABLES), TimelineRepository(factory).with_query(timeline_query)
return CohortRepository(factory, TABLES), TimelineRepository(factory).with_query(timeline_query)
def _run(repositories, build_id, nodes=("members", "timeline")):
+1 -1
View File
@@ -10,7 +10,7 @@ import json
from datetime import date
import pytest
from persistance.aristas.dbt import DbtQueryRepository
from persistance.edges.dbt import DbtQueryRepository
from sqlalchemy import create_engine, text
from sqlmodel import Session
+2 -2
View File
@@ -14,8 +14,8 @@ from types import SimpleNamespace
import pandas as pd
import pyarrow.parquet as pq
import pytest
from persistance.aristas.oro import CohortBuild, CohortMember
from persistance.aristas.dbt import DbtQueryRepository
from persistance.edges.gold import CohortBuild, CohortMember
from persistance.edges.dbt import DbtQueryRepository
from sqlalchemy import create_engine, text
from sqlmodel import Session
+3 -2
View File
@@ -91,10 +91,11 @@ def test_rendering_gets_the_environment_and_the_kernel(fake_quarto, tmp_path):
def test_a_failing_notebook_or_missing_quarto_is_a_render_error(fake_quarto, tmp_path, monkeypatch):
"""Pins down: a cell that raises, and Quarto not being installed, end as `RenderError` with the reason. Fails if a
broken report is logged or the error is a bare `FileNotFoundError`."""
"""Pins down: a cell that raises, and Quarto not being installed when it's the renderer asked for, end as
`RenderError` with the reason. Fails if a broken report is logged or the error is a bare `FileNotFoundError`."""
with pytest.raises(RenderError, match="a cell raised"):
render_notebook(_notebook("fail"), "01_eda", tmp_path / "page.html")
monkeypatch.setenv("NOTEBOOK_RENDERER", "quarto")
monkeypatch.setenv("QUARTO_BIN", "")
monkeypatch.setenv("PATH", str(tmp_path / "empty"))
with pytest.raises(RenderError, match="isn't installed"):