fix governance reqs; allow for sandboxed jupyter notebooks for testing

This commit is contained in:
Roberto Treviño Cervantes
2026-11-13 11:52:51 -06:00
parent ae2310754f
commit 1b45bc61d7
19 changed files with 1340 additions and 171 deletions
+17 -1
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,6 +157,21 @@ def test_training_registers_a_version_with_its_lineage(cohort_file, cohort_frame
assert sorted(risks["pac_id"]) == list(range(1, 21)) and risks["probabilidad"].between(0, 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(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."""
+27 -17
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
+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)
+3 -2
View File
@@ -92,10 +92,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"):