"""Model training started from governance: the scenarios that can be trained and the jobs that train them. A job is the same pipeline the `entrenar` compose profile runs (`models run --export --source dbt --environment prod --train --promote`), in a detached process that the request does not wait for. Its state lives in files under `INDICADORES_DIR/entrenamientos//` (`job.json`, `stdout.log`, `stderr.log` and `exit` once it ends), so any worker of the server answers for any job and a restart does not lose them. A job whose process is gone without an exit code is `interrumpido`. """ import json import os import subprocess import sys import tomllib import uuid from datetime import datetime, timezone from pathlib import Path TAIL_CHARS = 4000 # A domain whose scenarios train on a reference cohort and not on a dbt cohort build. OWN_STEPS = {"tea": "Entrena con la cohorte de referencia de EEG (requiere el clúster o --reference-dir)."} def _models_root() -> Path: import models return Path(models.__file__).parent def catalog() -> list[dict]: """The scenarios that have a `model.toml` of their own, with the cohort each trains on.""" found = [] for path in sorted(_models_root().glob("*/*/model.toml")): spec = tomllib.loads(path.read_text(encoding="utf-8")) domain = spec.get("domain") if domain is None: continue own = domain in OWN_STEPS if not own and "scenario" not in spec: continue found.append({ "domain": domain, "scenario": spec.get("scenario", path.parent.name), "cohort": spec.get("cohort"), "outcome": spec.get("outcome"), "description": " ".join(str(spec.get("description", OWN_STEPS.get(domain, ""))).split()), "kind": "referencia" if own else "cohorte", }) return found def _base() -> Path: return Path(os.environ.get("INDICADORES_DIR", "indicadores")) / "entrenamientos" def _command(domain: str, scenario: str) -> list[str]: argv = [sys.executable, "-m", "models", "run", domain, scenario, "--environment", "prod", "--train", "--promote"] if domain not in OWN_STEPS: argv += ["--export", "--source", "dbt", "--manifest", os.environ["DBT_MANIFEST"]] return argv def _alive(pid: int) -> bool: try: os.kill(pid, 0) except ProcessLookupError: return False except PermissionError: return True return True def _tail(path: Path) -> str: return path.read_text(encoding="utf-8", errors="replace")[-TAIL_CHARS:].strip() if path.exists() else "" def _state(folder: Path) -> dict: job = json.loads((folder / "job.json").read_text(encoding="utf-8")) out, err = _tail(folder / "stdout.log"), _tail(folder / "stderr.log") exit_file = folder / "exit" if exit_file.exists(): code = int(exit_file.read_text().strip() or 1) state = ("completado" if code == 0 else "entrenado_sin_promover" if "not promoted, missing" in err else "fallido") elif _alive(job["pid"]): code, state = None, "en_curso" else: code, state = None, "interrumpido" return {**job, "estado": state, "codigo": code, "salida": out, "error": err} def running(domain: str, scenario: str) -> dict | None: return next((j for j in jobs() if j["estado"] == "en_curso" and (j["domain"], j["scenario"]) == (domain, scenario)), None) def start(domain: str, scenario: str) -> dict: """Starts a job. `LookupError` for a scenario that cannot be trained, `RuntimeError` with no dbt manifest.""" if (domain, scenario) not in {(s["domain"], s["scenario"]) for s in catalog()}: raise LookupError(f"no such model: {domain}/{scenario}") if domain not in OWN_STEPS and not os.environ.get("DBT_MANIFEST"): raise RuntimeError("No hay un manifest de dbt configurado.") job_id = f"{datetime.now(timezone.utc):%Y%m%dT%H%M%S}-{uuid.uuid4().hex[:6]}" folder = _base() / job_id folder.mkdir(parents=True) shell = '{ "$@" > stdout.log 2> stderr.log; echo $? > exit; }' process = subprocess.Popen(["sh", "-c", shell, "sh", *_command(domain, scenario)], cwd=folder, start_new_session=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) job = {"id": job_id, "domain": domain, "scenario": scenario, "pid": process.pid, "iniciado": datetime.now(timezone.utc).isoformat(timespec="seconds")} (folder / "job.json").write_text(json.dumps(job), encoding="utf-8") return _state(folder) def get(job_id: str) -> dict: folder = _base() / job_id if "/" in job_id or not (folder / "job.json").exists(): raise LookupError(f"no such training job: {job_id}") return _state(folder) def jobs(limit: int = 50) -> list[dict]: """The latest jobs, newest first.""" folders = sorted((p for p in _base().glob("*") if (p / "job.json").exists()), reverse=True) if _base().exists() else [] return [_state(p) for p in folders[:limit]]