models report eda: the exploratory notebook run on a build's file, rendered with Quarto and kept as an MLflow run of the notebook's experiment

This commit is contained in:
2026-11-06 00:28:47 -06:00
parent 761b5b03bc
commit 15ffeb3efe
7 changed files with 341 additions and 7 deletions
+36
View File
@@ -94,6 +94,29 @@ def _store(args: argparse.Namespace) -> int:
return _store_step(args, args.input)
def _report_eda(args: argparse.Namespace) -> int:
"""Runs the model's exploratory notebook on a build's file and keeps the rendered page as an MLflow report."""
from pathlib import Path
from models.io.rendering import RenderError
from models.pipelines.report_eda import report_eda
if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)):
return 1
notebook = Path(args.notebook) if args.notebook else (
Path(model.__file__).parents[1] / "notebooks" / args.scenario / "01_eda.ipynb")
if not notebook.exists():
print(f"no notebook at {notebook}", file=sys.stderr)
return 1
try:
run_id, written = report_eda(notebook, path, args.domain, args.scenario, kernel=args.kernel)
except RenderError as error:
print(error, file=sys.stderr)
return 1
print(f"{'reported' if written else 'already reported'}: run {run_id}, {notebook.name} on {path}")
return 0
def _estimate(args: argparse.Namespace) -> int:
"""Scores the build's file with a registered version and writes the output file."""
if not (model := _model_module(args, "model")) or not (path := _cohort_file(args, model)):
@@ -286,6 +309,19 @@ def build_parser() -> argparse.ArgumentParser:
estimate.add_argument("--version", help="the model version; the one in production by default")
estimate.set_defaults(run=_estimate)
report = commands.add_parser("report", help="notebooks run on a build's file and kept as MLflow reports")
report.set_defaults(run=lambda args: _show_help(report))
reports = report.add_subparsers(dest="action", metavar="<report>")
eda = reports.add_parser("eda", help="render the exploratory notebook with Quarto and log it to MLflow")
eda.add_argument("domain", choices=["cacu", "cama", "tea"])
eda.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
eda.add_argument("--notebook", help="the notebook; the scenario's notebooks/<scenario>/01_eda.ipynb by default")
eda.add_argument("--build", "--armado", dest="armado", type=int,
help="the build's number: a kit build's armado_id, or a dbt build's; the latest exported by default")
eda.add_argument("--source", choices=["kit", "dbt"], default="dbt", help="whose builds: the kit's or dbt's rules'")
eda.add_argument("--kernel", help="the Jupyter kernel to run it with; the notebook's own by default")
eda.set_defaults(run=_report_eda)
store = commands.add_parser("store", help="store an estimate file as a batch of risks in the domain's database")
store.add_argument("domain", choices=["cacu", "cama", "tea"])
store.add_argument("scenario", help="the model's folder, e.g. cin2_logistic")
+49
View File
@@ -0,0 +1,49 @@
"""Renders a notebook to a self-contained HTML page with Quarto, running it first.
`QUARTO_BIN` names the `quarto` executable when it isn't on the `PATH`. Quarto runs notebooks through a Python that has
Jupyter (`nbformat`, `nbclient`); under `uv run` the first one on the `PATH` is this package's, which doesn't, so
`QUARTO_PYTHON` names one that does. The notebook runs with the kernel its metadata
names, or `kernel` if given, in the environment given: that's how a report points the notebook at a database, a
cohort folder and a build's file. Quarto writes next to its input, so the notebook is copied to a temporary folder
first and the source folder is left untouched.
"""
import json
import os
import shutil
import subprocess
import tempfile
from pathlib import Path
QUARTO_ENV = "QUARTO_BIN"
class RenderError(RuntimeError):
"""Quarto failed: a cell raised, the kernel is missing, or Quarto isn't installed."""
def quarto() -> str:
found = os.environ.get(QUARTO_ENV) or shutil.which("quarto")
if not found:
raise RenderError(f"quarto isn't installed: put it on the PATH or set {QUARTO_ENV}")
return found
def render_notebook(notebook: dict, name: str, output: Path, *, env: dict[str, str] | None = None,
kernel: str | None = None) -> Path:
"""Runs and renders `notebook` (its JSON) as `name`, and writes the page to `output`."""
command = quarto()
if kernel:
notebook = {**notebook, "metadata": {**notebook.get("metadata", {}),
"kernelspec": {"name": kernel, "display_name": kernel, "language": "python"}}}
with tempfile.TemporaryDirectory(prefix="render-") as folder:
source = Path(folder) / f"{name}.ipynb"
source.write_text(json.dumps(notebook, ensure_ascii=False))
done = subprocess.run([command, "render", source.name, "--execute", "--to", "html", "-M", "embed-resources:true"],
cwd=folder, env={**os.environ, **(env or {})}, capture_output=True, text=True)
page = source.with_suffix(".html")
if done.returncode or not page.exists():
raise RenderError(f"quarto couldn't render {name}: {(done.stderr or done.stdout)[-2000:]}")
output.parent.mkdir(parents=True, exist_ok=True)
shutil.move(page, output)
return output
+38 -7
View File
@@ -11,6 +11,9 @@ process never interfere.
`MLFLOW_ARTIFACT_ROOT`, when set, is where new experiments keep their
artifacts (MLflow's own default is `./mlruns`, relative to the working directory).
Reports are runs too: `record_report` keeps a rendered notebook and its source as artifacts, in an experiment of
their own, and `find_run` finds one already made from the same inputs.
A run that logs a model (`log_model`) registers `runs:/<run_id>/model`, tagged
with its `modelo_sha`: the hash of the stored artifact, which identifies the exact
model that produced a risk. Which code trained it is recorded apart: every run is
@@ -29,7 +32,7 @@ import mlflow.pyfunc
from core.governance.enums import ArtifactKind, Environment
from mlflow import MlflowClient
from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, code_version, model_sha, registered_name
from models.io.lineage import ARMADO_TAG, DOMAINS, MODEL_SHA_TAG, code_version, matches, model_sha, registered_name
from models.io.storage import ReadOnlyRepository, resolve_repository
ARTIFACT_ROOT_ENV = "MLFLOW_ARTIFACT_ROOT"
@@ -70,6 +73,39 @@ def log_artifact_file(client: MlflowClient, run_id: str, kind: str, path: str |
client.log_dict(run_id, metadata, f"{kind}/{Path(path).name}.meta.json")
def experiment_id(client: MlflowClient, name: str) -> str:
"""The experiment `name`, created if it doesn't exist, under `MLFLOW_ARTIFACT_ROOT` when that's set."""
experiment = client.get_experiment_by_name(name)
if experiment:
return experiment.experiment_id
root = os.environ.get(ARTIFACT_ROOT_ENV)
return client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None)
def find_run(client: MlflowClient, experiment: str, expected: dict[str, str]) -> str | None:
"""The newest finished run of `experiment` whose tags hold every expected value, or `None`."""
found = client.get_experiment_by_name(experiment)
if found is None:
return None
for run in client.search_runs([found.experiment_id], order_by=["attributes.start_time DESC"]):
if run.info.status == "FINISHED" and matches(run.data.tags, expected):
return run.info.run_id
return None
def record_report(client: MlflowClient, experiment: str, tags: dict[str, str], files: dict[str, Path]) -> str:
"""A finished run of `experiment` with `tags`, the code version, and each file logged under its kind's folder."""
run = client.create_run(experiment_id(client, experiment), tags={**code_version(), **tags})
try:
for kind, path in files.items():
log_artifact_file(client, run.info.run_id, kind, path)
except Exception:
client.set_terminated(run.info.run_id, "FAILED")
raise
client.set_terminated(run.info.run_id, "FINISHED")
return run.info.run_id
class TrainingRun:
"""One instance per training execution, wrapping one MLflow run. PROD
runs name the cohort build they were trained on, so their metrics trace
@@ -112,12 +148,7 @@ class TrainingRun:
self.client.set_tag(self.run_id, tag, value)
def _experiment_id(self) -> str:
name = registered_name(self.domain, self.scenario)
experiment = self.client.get_experiment_by_name(name)
if experiment:
return experiment.experiment_id
root = os.environ.get(ARTIFACT_ROOT_ENV)
return self.client.create_experiment(name, artifact_location=str(Path(root) / name) if root else None)
return experiment_id(self.client, registered_name(self.domain, self.scenario))
def repository(self, entity: str) -> ReadOnlyRepository:
"""ML-04: read-only access to `persistance.<domain>.<entity>_repository`."""
+48
View File
@@ -0,0 +1,48 @@
"""An exploratory notebook as an MLflow report: run on a build's file, rendered with Quarto, kept as artifacts.
Each notebook is an experiment, `<domain>-<scenario>/<notebook>` (`cacu-cin2_logistic/01_eda`), and each report a run
in it, tagged with the notebook's content hash and the build's file (`models.io.lineage.cohort_reference`). Its
artifacts are the rendered page (`report/`) and the notebook without outputs (`notebook/`). A notebook and a file that
were already reported together are not rendered again.
The notebook reads the build's file from `COHORT_FILE`, set here, and the database and cohort folder from the
environment it inherits.
"""
import json
import tempfile
from pathlib import Path
from mlflow import MlflowClient
from models.io.lineage import cohort_reference, file_sha256, registered_name
from models.io.rendering import render_notebook
from models.io.storage import read_metadata
from models.io.tracking import find_run, record_report
from models.steps.report import notebook_sha256, without_outputs
COHORT_FILE_ENV = "COHORT_FILE"
NOTEBOOK_TAG, NOTEBOOK_SHA_TAG, REPORT_TAG = "notebook", "notebook.sha256", "report"
def report_experiment(domain: str, scenario: str, notebook: Path) -> str:
return f"{registered_name(domain, scenario)}/{notebook.stem}"
def report_eda(notebook_path: str | Path, cohort_path: str | Path, domain: str, scenario: str,
kernel: str | None = None) -> tuple[str, bool]:
"""Returns the report's run id and whether it was rendered now."""
notebook_path, cohort_path = Path(notebook_path), Path(cohort_path)
notebook = json.loads(notebook_path.read_text())
experiment = report_experiment(domain, scenario, notebook_path)
tags = {REPORT_TAG: "eda", NOTEBOOK_TAG: notebook_path.name, NOTEBOOK_SHA_TAG: notebook_sha256(notebook),
**cohort_reference(read_metadata(cohort_path), file_sha256(cohort_path))}
client = MlflowClient()
if existing := find_run(client, experiment, tags):
return existing, False
with tempfile.TemporaryDirectory(prefix="report-") as folder:
page = render_notebook(notebook, notebook_path.stem, Path(folder) / f"{notebook_path.stem}.html",
env={COHORT_FILE_ENV: str(cohort_path.resolve())}, kernel=kernel)
source = Path(folder) / notebook_path.name
source.write_text(json.dumps(without_outputs(notebook), ensure_ascii=False, indent=1))
return record_report(client, experiment, tags, {"report": page, "notebook": source}), True
+21
View File
@@ -0,0 +1,21 @@
"""What identifies a notebook's content: its cells' sources, without outputs or execution counts."""
import copy
import hashlib
import json
def without_outputs(notebook: dict) -> dict:
"""The notebook as written: code cells keep their source and lose their outputs."""
cleared = copy.deepcopy(notebook)
for cell in cleared["cells"]:
if cell["cell_type"] == "code":
cell["outputs"], cell["execution_count"] = [], None
return cleared
def notebook_sha256(notebook: dict) -> str:
"""Changes when a cell's type or source changes, not when the notebook is run again."""
cells = [[cell["cell_type"], "".join(cell["source"]) if isinstance(cell["source"], list) else cell["source"]]
for cell in notebook["cells"]]
return hashlib.sha256(json.dumps(cells, ensure_ascii=False).encode()).hexdigest()