01e4406838
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
269 lines
11 KiB
Python
269 lines
11 KiB
Python
"""Where an uploaded notebook runs: a job folder, a runner and the executors that hand jobs to it (ML-04, ML-05).
|
|
|
|
A job is one folder named after the notebook's run, holding everything the notebook may see: the notebook
|
|
(`notebook.ipynb`), a copy of the cohort build's file (`cohorte.parquet`), the chosen version's saved model
|
|
(`model/`) and `job.json`. The notebook runs with that folder as its world: its MLflow is a throwaway store inside it
|
|
(`mlflow.db`, `artefactos/`), and every database URL is an empty in-memory database. The runner writes the page
|
|
(`page.html`) and `result.json`; what the notebook trained is imported afterwards by trusted code
|
|
(`models.reports.notebook_import`).
|
|
|
|
Executors are classes in `EXECUTORS`: `local` runs the job in this process, unsandboxed, for development;
|
|
`contenedor` leaves it in `NOTEBOOK_JOBS_DIR` for the runner container (`python -m models notebooks serve`), which
|
|
has no network and sees only that folder, and waits for its result. `NOTEBOOK_EXECUTOR` picks one; with
|
|
`NOTEBOOK_JOBS_DIR` set the default is `contenedor`, otherwise `local`.
|
|
|
|
Whatever the notebook wrote is untrusted: files are read only through `read_job_file`, which refuses symbolic links
|
|
and anything outside the job folder.
|
|
"""
|
|
|
|
import json
|
|
import os
|
|
import shutil
|
|
import stat
|
|
import tempfile
|
|
import time
|
|
from abc import ABC, abstractmethod
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from models.reports.rendering import CELL_TIMEOUT_ENV, RenderError, renderer, with_kernel
|
|
from models.notebook import COHORT_FILE_ENV, DOMAIN_ENV, MODEL_PATH_ENV, SCENARIO_ENV, VERSION_ENV
|
|
|
|
JOBS_DIR_ENV = "NOTEBOOK_JOBS_DIR"
|
|
EXECUTOR_ENV = "NOTEBOOK_EXECUTOR"
|
|
RUNNER_UID_ENV = "NOTEBOOK_RUNNER_UID"
|
|
JOB_TIMEOUT_ENV = "NOTEBOOK_JOB_TIMEOUT"
|
|
JOB_TIMEOUT = 6 * 3600
|
|
POLL_SECONDS = 2
|
|
|
|
JOB_FILE, NOTEBOOK_FILE, COHORT_FILE, MODEL_DIR = "job.json", "notebook.ipynb", "cohorte.parquet", "model"
|
|
STORE_FILE, STORE_ARTIFACTS, PAGE_FILE, RESULT_FILE = "mlflow.db", "artefactos", "page.html", "result.json"
|
|
CLAIM_DIR, WORK_DIR = "en_curso", "trabajo"
|
|
KERNEL = "python3"
|
|
# What a notebook inherits from the runner's environment; everything else is left out.
|
|
PASSED_ENV = ("PATH", "LANG", "LC_ALL", "TZ", "SYSTEMROOT", "MODELS_GIT_COMMIT", CELL_TIMEOUT_ENV,
|
|
"MLFLOW_DISABLE_TELEMETRY", "DO_NOT_TRACK", "MLFLOW_DISABLE_AGENT_HINT")
|
|
DATABASE_ENVS = ("CACU_DATABASE_URL", "CAMA_DATABASE_URL", "TEA_DATABASE_URL", "GOVERNANCE_DATABASE_URL")
|
|
EMPTY_DATABASE = "sqlite://"
|
|
|
|
|
|
class JobError(RuntimeError):
|
|
pass
|
|
|
|
|
|
def _absolute(path: Path) -> str:
|
|
"""The path as the job folder is reached, without resolving links on the way to it, so the trusted side and the
|
|
notebook name its files the same way (`inside`)."""
|
|
return os.path.abspath(path)
|
|
|
|
|
|
def store_uri(job: Path) -> str:
|
|
return f"sqlite:///{_absolute(job / STORE_FILE)}"
|
|
|
|
|
|
def prepare_job(root: Path, run_id: str, notebook: dict, cohort_path: Path, *, domain: str, scenario: str,
|
|
version: str | None, model_dir: Path | None = None) -> Path:
|
|
"""Writes the job folder, complete or not at all: it's assembled beside the others and renamed into place, so the
|
|
runner never picks up half a job."""
|
|
root.mkdir(parents=True, exist_ok=True)
|
|
partial = Path(tempfile.mkdtemp(prefix=f".{run_id}-", dir=root))
|
|
try:
|
|
(partial / NOTEBOOK_FILE).write_text(json.dumps(with_kernel(notebook, KERNEL), ensure_ascii=False))
|
|
shutil.copyfile(cohort_path, partial / COHORT_FILE)
|
|
if model_dir is not None:
|
|
shutil.copytree(model_dir, partial / MODEL_DIR)
|
|
(partial / JOB_FILE).write_text(json.dumps({"run_id": run_id, "domain": domain, "scenario": scenario,
|
|
"version": version}))
|
|
_hand_over(partial)
|
|
job = root / run_id
|
|
partial.rename(job)
|
|
except BaseException:
|
|
shutil.rmtree(partial, ignore_errors=True)
|
|
raise
|
|
return job
|
|
|
|
|
|
def _hand_over(folder: Path) -> None:
|
|
"""Gives the job to the runner's user (`NOTEBOOK_RUNNER_UID`) when it isn't this one."""
|
|
uid = os.environ.get(RUNNER_UID_ENV)
|
|
os.chmod(folder, 0o755)
|
|
if not uid or int(uid) == os.getuid():
|
|
return
|
|
for base, folders, files in os.walk(folder):
|
|
for name in [base, *(os.path.join(base, f) for f in folders + files)]:
|
|
os.chown(name, int(uid), int(uid), follow_symlinks=False)
|
|
|
|
|
|
def notebook_env(job: Path) -> dict[str, str]:
|
|
spec = json.loads((job / JOB_FILE).read_text())
|
|
private = job / ".entorno"
|
|
env = {name: os.environ[name] for name in PASSED_ENV if name in os.environ}
|
|
env.update({name: EMPTY_DATABASE for name in DATABASE_ENVS})
|
|
env.update({
|
|
COHORT_FILE_ENV: _absolute(job / COHORT_FILE), DOMAIN_ENV: spec["domain"], SCENARIO_ENV: spec["scenario"],
|
|
"MLFLOW_TRACKING_URI": store_uri(job), "MLFLOW_ARTIFACT_ROOT": _absolute(job / STORE_ARTIFACTS),
|
|
"HOME": _absolute(private), "TMPDIR": _absolute(private / "tmp"), "IPYTHONDIR": _absolute(private / "ipython"),
|
|
"JUPYTER_RUNTIME_DIR": _absolute(private / "jupyter"), "MPLCONFIGDIR": _absolute(private / "matplotlib"),
|
|
})
|
|
if spec.get("version"):
|
|
env[VERSION_ENV] = str(spec["version"])
|
|
if (job / MODEL_DIR).is_dir():
|
|
env[MODEL_PATH_ENV] = _absolute(job / MODEL_DIR)
|
|
return env
|
|
|
|
|
|
def run_job(job: Path) -> bool:
|
|
"""Runs the job's notebook and writes its page and `result.json`. Returns whether every cell ran."""
|
|
env = notebook_env(job)
|
|
for folder in ("HOME", "TMPDIR", "IPYTHONDIR", "JUPYTER_RUNTIME_DIR", "MPLCONFIGDIR"):
|
|
Path(env[folder]).mkdir(parents=True, exist_ok=True)
|
|
work = job / WORK_DIR
|
|
work.mkdir(exist_ok=True)
|
|
result: dict[str, Any] = {"ok": True, "error": None}
|
|
page = None
|
|
try:
|
|
page = renderer().render(json.loads((job / NOTEBOOK_FILE).read_text()), "notebook", work, env)
|
|
except RenderError as error:
|
|
page, result = error.page, {"ok": False, "error": str(error)}
|
|
except Exception as error:
|
|
result = {"ok": False, "error": f"{type(error).__name__}: {error}"}
|
|
if page is not None:
|
|
_write_atomically(job / PAGE_FILE, page)
|
|
_write_atomically(job / RESULT_FILE, json.dumps(result, ensure_ascii=False))
|
|
return result["ok"]
|
|
|
|
|
|
def _write_atomically(path: Path, text: str) -> None:
|
|
partial = path.with_name(f".{path.name}.parcial")
|
|
partial.write_text(text)
|
|
partial.replace(path)
|
|
|
|
|
|
def read_job_file(job: Path, relative: str) -> bytes | None:
|
|
"""A file the job left, or `None` if it isn't there. `JobError` for a symbolic link or a path that leaves the job
|
|
folder: those were planted to make the trusted side read its own files."""
|
|
path = job / relative
|
|
if not inside(job, path):
|
|
raise JobError(f"{relative} sale de la carpeta del trabajo")
|
|
try:
|
|
descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
|
|
except FileNotFoundError:
|
|
return None
|
|
except OSError as error:
|
|
raise JobError(f"{relative} no es un archivo regular") from error
|
|
with os.fdopen(descriptor, "rb") as handle:
|
|
if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
|
|
raise JobError(f"{relative} no es un archivo regular")
|
|
return handle.read()
|
|
|
|
|
|
def inside(job: Path, path: Path) -> bool:
|
|
"""Whether `path` is within `job` with no symbolic link on the way."""
|
|
base = Path(os.path.abspath(job))
|
|
try:
|
|
parts = Path(os.path.abspath(path)).relative_to(base).parts
|
|
except ValueError:
|
|
return False
|
|
current = base
|
|
for part in parts:
|
|
current = current / part
|
|
if current.is_symlink():
|
|
return False
|
|
return True
|
|
|
|
|
|
def result_of(job: Path) -> dict[str, Any] | None:
|
|
data = read_job_file(job, RESULT_FILE)
|
|
if data is None:
|
|
return None
|
|
try:
|
|
result = json.loads(data)
|
|
except json.JSONDecodeError:
|
|
return {"ok": False, "error": "result.json ilegible"}
|
|
return {"ok": result.get("ok") is True, "error": str(result.get("error") or "")[:20000] or None}
|
|
|
|
|
|
class NotebookExecutor(ABC):
|
|
name: str
|
|
sandboxed: bool
|
|
|
|
@abstractmethod
|
|
def jobs_root(self) -> Path: ...
|
|
|
|
@abstractmethod
|
|
def run(self, job: Path) -> None:
|
|
"""Returns once the job has its `result.json`; `JobError` if it never gets one."""
|
|
|
|
|
|
EXECUTORS: dict[str, type[NotebookExecutor]] = {}
|
|
|
|
|
|
def register_executor(cls: type[NotebookExecutor]) -> type[NotebookExecutor]:
|
|
EXECUTORS[cls.name] = cls
|
|
return cls
|
|
|
|
|
|
@register_executor
|
|
class LocalExecutor(NotebookExecutor):
|
|
"""Runs the job in this process's own kernel: nothing keeps the notebook from this machine's files or network."""
|
|
|
|
name, sandboxed = "local", False
|
|
|
|
def jobs_root(self) -> Path:
|
|
return Path(os.environ.get(JOBS_DIR_ENV) or Path(tempfile.gettempdir()) / "notebook-jobs")
|
|
|
|
def run(self, job: Path) -> None:
|
|
run_job(job)
|
|
|
|
|
|
@register_executor
|
|
class ContainerExecutor(NotebookExecutor):
|
|
"""Leaves the job for the runner container and waits for its result (`NOTEBOOK_JOB_TIMEOUT`, 6 h by default)."""
|
|
|
|
name, sandboxed = "contenedor", True
|
|
|
|
def jobs_root(self) -> Path:
|
|
if not os.environ.get(JOBS_DIR_ENV):
|
|
raise JobError(f"{JOBS_DIR_ENV} no está configurado: no hay carpeta compartida con el contenedor de notebooks")
|
|
return Path(os.environ[JOBS_DIR_ENV])
|
|
|
|
def run(self, job: Path) -> None:
|
|
deadline = time.monotonic() + int(os.environ.get(JOB_TIMEOUT_ENV, JOB_TIMEOUT))
|
|
while time.monotonic() < deadline:
|
|
if result_of(job) is not None:
|
|
return
|
|
time.sleep(POLL_SECONDS)
|
|
raise JobError("el contenedor de notebooks no terminó el trabajo a tiempo (¿está corriendo?)")
|
|
|
|
|
|
def executor() -> NotebookExecutor:
|
|
chosen = os.environ.get(EXECUTOR_ENV) or ("contenedor" if os.environ.get(JOBS_DIR_ENV) else "local")
|
|
if chosen not in EXECUTORS:
|
|
raise JobError(f"{EXECUTOR_ENV}={chosen!r}: use uno de {sorted(EXECUTORS)}")
|
|
return EXECUTORS[chosen]()
|
|
|
|
|
|
def claim(job: Path) -> bool:
|
|
"""Takes a ready job for this runner; `False` if it isn't ready or another runner has it."""
|
|
if not job.is_dir() or job.name.startswith(".") or not (job / JOB_FILE).exists() or (job / RESULT_FILE).exists():
|
|
return False
|
|
try:
|
|
(job / CLAIM_DIR).mkdir()
|
|
except FileExistsError:
|
|
return False
|
|
return True
|
|
|
|
|
|
def serve(root: Path, *, once: bool = False) -> None:
|
|
"""The runner's loop: runs each ready job in `root`, oldest first."""
|
|
while True:
|
|
for job in sorted((p for p in root.iterdir() if p.is_dir()), key=lambda p: p.stat().st_mtime):
|
|
if claim(job):
|
|
try:
|
|
run_job(job)
|
|
except Exception as error:
|
|
_write_atomically(job / RESULT_FILE, json.dumps({"ok": False, "error": f"{type(error).__name__}: {error}"}))
|
|
if once:
|
|
return
|
|
time.sleep(POLL_SECONDS)
|