Files
models/models/reports/notebook_import.py
T
edgar 01e4406838 The notebook runner moves to reports/: experiment, notebook_jobs and notebook_import next to rendering and eda
They run a notebook on a build's file and keep it as an MLflow run, as eda does; io/ keeps the storage and MLflow
boundary and pipelines/ the cohort pipelines. Moved whole with git mv, imports repointed; models.notebook, the API
notebooks import, stays where it is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-19 20:50:46 -06:00

138 lines
7.1 KiB
Python

"""Copies what a notebook trained, in its job's own MLflow store, into the platform's (ML-02, ML-03).
The notebook wrote that store itself, so nothing in it is taken at its word. Only runs of the job's domain
(`<domain>-<scenario>` experiments) come across; each becomes a new run tagged DEV, with the cohort reference of the
build the job actually had, the notebook's run (`notebook.run_id`) and the model's hash computed here. Registered
versions come across as DEV versions of their run, never with an alias, so a notebook can't put anything in
production. Files are copied by walking the job folder without following symbolic links, and the store is opened
from a copy, so nothing outside the job folder is ever read.
"""
import os
import re
import shutil
import tempfile
from pathlib import Path
from typing import Any
from urllib.parse import unquote, urlparse
from mlflow import MlflowClient
from mlflow.entities import Metric, Param
from models.io.lineage import MODEL_SHA_TAG, code_version, model_sha
from models.reports.notebook_jobs import STORE_FILE, JobError, inside, read_job_file
from models.io.tracking import MODEL_PATH, experiment_id
NOTEBOOK_RUN_TAG = "notebook.run_id"
# Above this many bytes of files across a job's runs, nothing more is copied.
MAX_IMPORT_BYTES_ENV = "NOTEBOOK_MAX_IMPORT_MB"
MAX_IMPORT_MB = 500
KEPT_SYSTEM_TAGS = ("mlflow.note.content",)
def import_job(job: Path, notebook_run_id: str, domain: str, cohort: dict[str, str]) -> dict[str, Any]:
"""Imports the job's runs and versions; returns what came across and what was left out, and why."""
summary: dict[str, Any] = {"runs": [], "versions": [], "skipped": []}
data = read_job_file(job, STORE_FILE)
if not data:
return summary
with tempfile.TemporaryDirectory(prefix="notebook-store-") as tmp:
copy = Path(tmp) / STORE_FILE
copy.write_bytes(data)
local = MlflowClient(tracking_uri=f"sqlite:///{copy}", registry_uri=f"sqlite:///{copy}")
target = MlflowClient()
budget = int(os.environ.get(MAX_IMPORT_BYTES_ENV, MAX_IMPORT_MB)) * 1024 * 1024
runs: dict[str, str] = {}
for experiment in local.search_experiments():
if not re.fullmatch(rf"{domain}-[\w-]{{1,100}}", experiment.name):
summary["skipped"].append({"experiment": experiment.name, "reason": "no es un escenario del dominio"})
continue
for run in local.search_runs([experiment.experiment_id]):
try:
new_id, budget = _copy_run(local, target, job, run, experiment.name, notebook_run_id, cohort, budget)
except JobError as error:
summary["skipped"].append({"run": run.info.run_id, "reason": str(error)})
continue
runs[run.info.run_id] = new_id
summary["runs"].append({"run_id": new_id, "experiment": experiment.name})
for model in local.search_registered_models():
for version in local.search_model_versions(f"name='{model.name}'"):
if version.run_id not in runs or not model.name.startswith(f"{domain}-"):
summary["skipped"].append({"version": f"{model.name}:{version.version}",
"reason": "su corrida no se importó"})
continue
summary["versions"].append(_copy_version(target, model.name, runs[version.run_id], notebook_run_id))
return summary
def _artifact_dir(job: Path, run) -> Path:
uri = run.info.artifact_uri
path = Path(unquote(urlparse(uri).path)) if "://" in uri else Path(uri)
if not inside(job, path):
raise JobError(f"los archivos de la corrida están fuera de la carpeta del trabajo: {uri}")
return path
def _files(job: Path, folder: Path) -> list[Path]:
"""The regular files under `folder`, refusing any symbolic link."""
found = []
for base, folders, files in os.walk(folder, followlinks=False):
for name in folders + files:
path = Path(base) / name
if path.is_symlink() or not inside(job, path):
raise JobError(f"enlace simbólico en los archivos de la corrida: {path.name}")
if name in files:
found.append(path)
return found
def _copy_run(local: MlflowClient, target: MlflowClient, job: Path, run, experiment: str, notebook_run_id: str,
cohort: dict[str, str], budget: int) -> tuple[str, int]:
folder = _artifact_dir(job, run)
files = _files(job, folder) if folder.exists() else []
size = sum(path.stat().st_size for path in files)
if size > budget:
raise JobError(f"sus archivos ({size // 1_000_000} MB) exceden el límite de {MAX_IMPORT_BYTES_ENV}")
tags = {k: v for k, v in run.data.tags.items() if not k.startswith("mlflow.") or k in KEPT_SYSTEM_TAGS}
tags.update({**cohort, **code_version(), "domain": experiment.split("-", 1)[0],
"scenario": experiment.split("-", 1)[1], "environment": "DEV", NOTEBOOK_RUN_TAG: notebook_run_id})
tags.pop(MODEL_SHA_TAG, None)
tags.pop("kit.armado_id", None)
new = target.create_run(experiment_id(target, experiment), tags=tags, run_name=run.info.run_name)
new_id = new.info.run_id
params = [Param(k, v) for k, v in run.data.params.items()]
metrics = [Metric(m.key, m.value, m.timestamp, m.step) for key in run.data.metrics
for m in local.get_metric_history(run.info.run_id, key)]
for start in range(0, max(len(params), len(metrics)), 100):
target.log_batch(new_id, metrics=metrics[start:start + 100], params=params[start:start + 100])
with tempfile.TemporaryDirectory(prefix="notebook-files-") as staging:
for path in files:
destination = Path(staging) / path.relative_to(folder)
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(path, destination, follow_symlinks=False)
if files:
target.log_artifacts(new_id, staging)
if (Path(staging) / MODEL_PATH / "python_model.pkl").exists():
target.set_tag(new_id, MODEL_SHA_TAG, model_sha(Path(staging) / MODEL_PATH))
target.set_terminated(new_id, run.info.status if run.info.status in ("FINISHED", "FAILED") else "KILLED")
return new_id, budget - size
def _copy_version(target: MlflowClient, name: str, run_id: str, notebook_run_id: str) -> dict[str, str]:
from mlflow import MlflowException
try:
target.create_registered_model(name)
except MlflowException as error:
if error.error_code != "RESOURCE_ALREADY_EXISTS":
raise
run = target.get_run(run_id)
keep = ("domain", "scenario", "environment", MODEL_SHA_TAG, "cohort.url", "cohort.source", "cohort.build",
"cohort.file_sha256")
tags = {k: run.data.tags[k] for k in keep if k in run.data.tags}
tags[NOTEBOOK_RUN_TAG] = notebook_run_id
has_model = MODEL_SHA_TAG in run.data.tags
source = f"runs:/{run_id}/{MODEL_PATH}" if has_model else f"runs:/{run_id}"
version = target.create_model_version(name, source=source, run_id=run_id, tags=tags)
return {"name": name, "version": str(version.version), "run_id": run_id}