"""A notebook uploaded to the platform, run on a cohort build's file and kept as an MLflow run (ML-01a, ML-04, ML-05). Each run belongs to the experiment `-/experimentos` and is tagged with the notebook's name and content hash, the build's file (`models.io.lineage.cohort_reference`), the model version it was given, if any, the code version and where it ran (`sandbox`: `contenedor` or `local`). It holds the notebook as uploaded (`notebook/`), the page with its outputs (`report/`), what was imported from it (`importado.json`) and, when it failed, `error.txt`. `start` creates the run; `execute` runs the notebook through an executor and closes the run, so a caller can run it in the background and hand out the run's id at once. The notebook runs in a job folder of its own (`models.reports.notebook_jobs`) with the build's file as its only data and an MLflow store of its own; what it trained is copied into the platform's MLflow as DEV afterwards (`models.reports.notebook_import`). Where it runs is the executor's: the runner container, with no network and no view of the server's files, or this process for development. """ import json import os import re import shutil import tempfile from datetime import datetime, timedelta, timezone from pathlib import Path from typing import Any from mlflow import MlflowClient from mlflow.entities import RunStatus from models.io.lineage import COHORT_BUILD_TAG, COHORT_SOURCE_TAG, COHORT_URL_TAG, DOMAINS, code_version, \ registered_name from models.reports.notebook_import import import_job from models.reports.notebook_jobs import JOB_TIMEOUT, JOB_TIMEOUT_ENV, PAGE_FILE, executor, prepare_job, read_job_file, \ result_of from models.io.storage import cohort_reference, file_sha256, read_metadata from models.io.tracking import MODEL_PATH, experiment_id, run_file, run_files from models.reports.rendering import notebook_sha256, without_outputs EXPERIMENT_SUFFIX = "experimentos" KIND_TAG, KIND = "experiment", "notebook" NOTEBOOK_TAG, NOTEBOOK_SHA_TAG, VERSION_TAG = "notebook", "notebook.sha256", "model.version" DOMAIN_TAG, SCENARIO_TAG, SANDBOX_TAG = "domain", "scenario", "sandbox" ERROR_PATH, IMPORT_PATH = "error.txt", "importado.json" KEEP_JOBS_ENV = "NOTEBOOK_KEEP_JOBS" # A run still marked as running this long after its job's timeout was cut off (a restart, a killed worker). STALE_MARGIN = timedelta(minutes=30) def experiment_name(domain: str, scenario: str) -> str: return f"{registered_name(domain, scenario)}/{EXPERIMENT_SUFFIX}" def check_names(domain: str | None, scenario: str | None) -> None: if domain is not None and domain not in DOMAINS: raise ValueError(f"dominio desconocido: {domain!r}") if scenario is not None and not re.fullmatch(r"[\w-]{1,100}", scenario): raise ValueError(f"escenario inválido: {scenario!r}") def notebook_name(filename: str) -> str: """The name a notebook's files are stored under: its file name without folders or extension, in safe characters.""" stem = Path(filename.replace("\\", "/")).name.removesuffix(".ipynb") return re.sub(r"[^\w.-]+", "_", stem).strip("._")[:80] or "notebook" def check_notebook(notebook: Any) -> dict: """A Jupyter notebook (nbformat 4), or `ValueError` saying why not.""" if not isinstance(notebook, dict) or not isinstance(notebook.get("cells"), list): raise ValueError("el archivo no es un notebook de Jupyter (.ipynb)") if notebook.get("nbformat") != 4: raise ValueError(f"solo se aceptan notebooks en formato 4, no {notebook.get('nbformat')!r}") return notebook def start(notebook: dict, name: str, cohort_path: str | Path, domain: str, scenario: str, version: str | None = None) -> str: """Creates the run, stores the notebook as uploaded and returns the run's id; the notebook hasn't run yet.""" check_names(domain, scenario) check_notebook(notebook) name = notebook_name(name) client = MlflowClient() tags = {KIND_TAG: KIND, NOTEBOOK_TAG: name, NOTEBOOK_SHA_TAG: notebook_sha256(notebook), DOMAIN_TAG: domain, SCENARIO_TAG: scenario, **cohort_reference(read_metadata(cohort_path), file_sha256(cohort_path)), **code_version()} if version: tags[VERSION_TAG] = str(version) run = client.create_run(experiment_id(client, experiment_name(domain, scenario)), tags=tags, run_name=name) client.log_text(run.info.run_id, json.dumps(without_outputs(notebook), ensure_ascii=False, indent=1), f"notebook/{name}.ipynb") return run.info.run_id def execute(run_id: str, notebook: dict, name: str, cohort_path: str | Path, domain: str, scenario: str, version: str | None = None) -> bool: """Runs the notebook through the executor, imports what it trained, stores its page (the cells that ran, when it failed) and closes the run. Returns whether every cell ran.""" client = MlflowClient() runner = executor() client.set_tag(run_id, SANDBOX_TAG, runner.name) job = None try: with tempfile.TemporaryDirectory(prefix="notebook-model-") as tmp: model = _model_copy(client, domain, scenario, version, Path(tmp)) job = prepare_job(runner.jobs_root(), run_id, notebook, Path(cohort_path), domain=domain, scenario=scenario, version=version, model_dir=model) runner.run(job) result = result_of(job) or {"ok": False, "error": "el notebook terminó sin resultado"} if page := read_job_file(job, PAGE_FILE): client.log_text(run_id, page.decode("utf-8", "replace"), f"report/{name}.html") cohort = {k: v for k, v in client.get_run(run_id).data.tags.items() if k.startswith("cohort.")} client.log_dict(run_id, import_job(job, run_id, domain, cohort), IMPORT_PATH) except Exception as error: result = {"ok": False, "error": f"{type(error).__name__}: {error}"} finally: if job is not None and not os.environ.get(KEEP_JOBS_ENV): shutil.rmtree(job, ignore_errors=True) if not result["ok"]: client.log_text(run_id, result["error"] or "falló", ERROR_PATH) client.set_terminated(run_id, RunStatus.to_string(RunStatus.FINISHED if result["ok"] else RunStatus.FAILED)) return result["ok"] def _model_copy(client: MlflowClient, domain: str, scenario: str, version: str | None, folder: Path) -> Path | None: """The chosen version's saved model, downloaded for the job; `None` without a version or a saved model.""" if not version: return None from models.io.registry import registry resolved = registry.resolve(domain, scenario, version) if not resolved.modelo_sha: return None return Path(client.download_artifacts(resolved.run_id, MODEL_PATH, str(folder))) def run_notebook(notebook: dict, name: str, cohort_path: str | Path, domain: str, scenario: str, version: str | None = None) -> tuple[str, bool]: run_id = start(notebook, name, cohort_path, domain, scenario, version) return run_id, execute(run_id, notebook, notebook_name(name), cohort_path, domain, scenario, version) def _status(run) -> str: status = run.info.status if status == "RUNNING": started = datetime.fromtimestamp(run.info.start_time / 1000, tz=timezone.utc) timeout = timedelta(seconds=int(os.environ.get(JOB_TIMEOUT_ENV, JOB_TIMEOUT))) return "interrumpido" if datetime.now(timezone.utc) - started > timeout + STALE_MARGIN else "en_curso" return {"FINISHED": "terminado", "FAILED": "fallido", "KILLED": "interrumpido"}.get(status, status.lower()) def _iso(epoch_millis: int | None) -> str | None: return datetime.fromtimestamp(epoch_millis / 1000, tz=timezone.utc).isoformat() if epoch_millis else None def _describe(run) -> dict[str, Any]: tags = run.data.tags return {"run_id": run.info.run_id, "notebook": tags.get(NOTEBOOK_TAG), "domain": tags.get(DOMAIN_TAG), "scenario": tags.get(SCENARIO_TAG), "version": tags.get(VERSION_TAG), "cohort": {"url": tags.get(COHORT_URL_TAG), "source": tags.get(COHORT_SOURCE_TAG), "build": tags.get(COHORT_BUILD_TAG)}, "notebook_sha256": tags.get(NOTEBOOK_SHA_TAG), "sandbox": tags.get(SANDBOX_TAG), "status": _status(run), "started_at": _iso(run.info.start_time), "ended_at": _iso(run.info.end_time)} def experiments(domain: str | None = None, scenario: str | None = None) -> list[dict[str, Any]]: """Notebook runs, newest first; `scenario` needs `domain`.""" check_names(domain, scenario) client = MlflowClient() pattern = f"{registered_name(domain, scenario) if scenario else (domain + '-%' if domain else '%')}/{EXPERIMENT_SUFFIX}" found = client.search_experiments(filter_string=f"name LIKE '{pattern}'") if not found: return [] runs = client.search_runs([e.experiment_id for e in found], filter_string=f"tags.{KIND_TAG} = '{KIND}'", order_by=["attributes.start_time DESC"], max_results=500) return [_describe(run) for run in runs] def _run(client: MlflowClient, run_id: str): try: run = client.get_run(run_id) except Exception as error: raise LookupError(f"no existe la corrida {run_id!r}") from error if run.data.tags.get(KIND_TAG) != KIND: raise LookupError(f"la corrida {run_id!r} no es de un notebook") return run def describe(run_id: str) -> dict[str, Any]: """One notebook run with its files and, if it failed, the error.""" client = MlflowClient() run = _run(client, run_id) files = run_files(client, run_id) error = None if any(item["path"] == ERROR_PATH for item in files): error = run_file(client, run_id, ERROR_PATH)[1].decode("utf-8", "replace") return {**_describe(run), "artifacts": files, "error": error} def artifact(run_id: str, path: str) -> tuple[str, bytes]: client = MlflowClient() _run(client, run_id) return run_file(client, run_id, path) def page(run_id: str) -> str | None: """The rendered page, or `None` while there's none.""" client = MlflowClient() _run(client, run_id) pages = [item["path"] for item in run_files(client, run_id, "report") if item["path"].endswith(".html")] return run_file(client, run_id, pages[0])[1].decode("utf-8") if pages else None