227 lines
13 KiB
Python
227 lines
13 KiB
Python
"""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)
|