Files
models/tests/test_report_eda.py
2026-11-13 11:52:51 -06:00

150 lines
7.2 KiB
Python

"""What this module covers: an exploratory notebook as an MLflow report (`models.steps.report`, `models.io.rendering`,
`models.io.tracking.find_run`/`record_report`, `models.pipelines.report_eda`) and `models report eda`: the content hash,
rendering with the build's file in the environment, one run per notebook and file, and its artifacts.
Fixtures: `fake_quarto`, a stand-in `quarto` (through `QUARTO_BIN`) that writes a page naming the kernel and the
`COHORT_FILE` it was given, or fails when the notebook says so; `notebook`, a two-cell notebook with outputs;
`cohort`, a dbt build's file with its metadata; `mlflow_tracking` (conftest), a SQLite-backed MLflow.
"""
import json
import os
import stat
import sys
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from mlflow import MlflowClient
from models.__main__ import main
from models.io.rendering import RenderError, render_notebook
from models.pipelines.report_eda import report_eda
from models.steps.report import notebook_sha256, without_outputs
FAKE = '''#!{python}
import json, os, pathlib, sys
source = pathlib.Path(sys.argv[2])
notebook = json.loads(source.read_text())
if "fail" in json.dumps(notebook["cells"]):
sys.exit("a cell raised")
kernel = notebook["metadata"]["kernelspec"]["name"]
source.with_suffix(".html").write_text(f"<html>kernel={{kernel}} cohort={{os.environ.get('COHORT_FILE')}}</html>")
'''
@pytest.fixture
def fake_quarto(tmp_path, monkeypatch):
path = tmp_path / "quarto"
path.write_text(FAKE.format(python=sys.executable))
path.chmod(path.stat().st_mode | stat.S_IEXEC)
monkeypatch.setenv("QUARTO_BIN", str(path))
return path
def _notebook(source="print(1)"):
return {"cells": [{"cell_type": "markdown", "metadata": {}, "source": ["# EDA"]},
{"cell_type": "code", "metadata": {}, "execution_count": 3, "source": [source],
"outputs": [{"output_type": "stream", "name": "stdout", "text": ["1\n"]}]}],
"metadata": {"kernelspec": {"name": "isssteleon-webapi", "display_name": "k", "language": "python"}},
"nbformat": 4, "nbformat_minor": 5}
@pytest.fixture
def notebook(tmp_path):
path = tmp_path / "notebooks" / "01_eda.ipynb"
path.parent.mkdir()
path.write_text(json.dumps(_notebook()))
return path
def _cohort(path, build):
path.parent.mkdir(parents=True, exist_ok=True)
table = pa.table({"pac_id": [1, 2]})
pq.write_table(table.replace_schema_metadata({"url": "cacu/cohorte_vigilancia", "producer": "dbt", "build": str(build)}), path)
return path
@pytest.fixture
def cohort(tmp_path):
return _cohort(tmp_path / "cohorts" / "dbt" / "1.parquet", 1)
def test_the_hash_follows_the_sources_not_the_outputs():
"""Pins down: running a notebook again (new outputs, counts) keeps its hash; editing a cell changes it. Fails if
outputs enter the hash, which would make every rendering a new report."""
ran_again = _notebook()
ran_again["cells"][1].update(outputs=[], execution_count=9)
assert notebook_sha256(ran_again) == notebook_sha256(_notebook())
assert notebook_sha256(_notebook("print(2)")) != notebook_sha256(_notebook())
assert without_outputs(_notebook())["cells"][1]["outputs"] == []
def test_rendering_gets_the_environment_and_the_kernel(fake_quarto, tmp_path):
"""Pins down: the page is rendered with the extra environment (the build's file) and with `kernel` when given.
Fails if either is lost on the way to Quarto."""
page = render_notebook(_notebook(), "01_eda", tmp_path / "out" / "01_eda.html", env={"COHORT_FILE": "/x.parquet"},
kernel="models")
assert page.read_text() == "<html>kernel=models cohort=/x.parquet</html>"
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 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"):
render_notebook(_notebook(), "01_eda", tmp_path / "page.html")
def test_a_report_is_a_run_of_the_notebooks_experiment_with_its_page(fake_quarto, notebook, cohort, mlflow_tracking):
"""Pins down: the run is in `<domain>-<scenario>/<notebook>`, tagged with the notebook's hash and the build's file,
and holds the page (rendered on that file) and the notebook without outputs. Fails if the page or the source is
missing, or the run can't be traced to its inputs."""
run_id, written = report_eda(notebook, cohort, "cacu", "cin2_logistic")
client = MlflowClient()
run = client.get_run(run_id)
assert written and client.get_experiment(run.info.experiment_id).name == "cacu-cin2_logistic/01_eda"
assert run.data.tags["notebook.sha256"] == notebook_sha256(_notebook())
assert (run.data.tags["cohort.source"], run.data.tags["cohort.build"]) == ("dbt", "1")
assert sorted(a.path for a in client.list_artifacts(run_id)) == ["notebook", "report"]
page = Path(client.download_artifacts(run_id, "report/01_eda.html")).read_text()
assert str(cohort.resolve()) in page
source = json.loads(Path(client.download_artifacts(run_id, "notebook/01_eda.ipynb")).read_text())
assert source["cells"][1]["outputs"] == []
def test_the_same_notebook_and_file_are_reported_once(fake_quarto, notebook, cohort, mlflow_tracking, tmp_path):
"""Pins down: reporting again reuses the run; an edited notebook or another build's file makes a new one. Fails if
the check ignores either input, or renders every time."""
first, _ = report_eda(notebook, cohort, "cacu", "cin2_logistic")
again, written = report_eda(notebook, cohort, "cacu", "cin2_logistic")
other_build, _ = report_eda(notebook, _cohort(tmp_path / "cohorts" / "dbt" / "2.parquet", 2), "cacu", "cin2_logistic")
notebook.write_text(json.dumps(_notebook("print(2)")))
edited, _ = report_eda(notebook, cohort, "cacu", "cin2_logistic")
assert again == first and not written
assert len({first, other_build, edited}) == 3
def test_the_command_reports_on_the_latest_dbt_build(fake_quarto, notebook, tmp_path, monkeypatch, mlflow_tracking, capsys):
"""Pins down: `models report eda` takes dbt's latest exported build by default and the notebook given. Fails if it
reads the kit's builds by default, or ignores `--notebook`."""
folder = tmp_path / "cohorts" / "cacu" / "cohorte_vigilancia" / "dbt"
_cohort(folder / "1.parquet", 1)
_cohort(folder / "2.parquet", 2)
monkeypatch.setenv("COHORTS_DIR", str(tmp_path / "cohorts"))
assert main(["report", "eda", "cacu", "cin2_logistic", "--notebook", str(notebook)]) == 0
assert "reported" in capsys.readouterr().out
run = MlflowClient().search_runs([MlflowClient().get_experiment_by_name("cacu-cin2_logistic/01_eda").experiment_id])[0]
assert run.data.tags["cohort.build"] == "2"