Governance TEA EEG: reference cohorts, baselines export and import, cluster health, training and analysis jobs with progress, EDF upload, EEG queries
This commit is contained in:
+36
-35
@@ -24,6 +24,7 @@ import os
|
||||
import signal
|
||||
import threading
|
||||
import time
|
||||
from contextlib import contextmanager
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -48,34 +49,21 @@ def _short(value: Any) -> str:
|
||||
return text if len(text) <= _SUMMARY_MAX else text[:_SUMMARY_MAX] + "…"
|
||||
|
||||
|
||||
def _warm_models(dominio: str) -> dict[str, Any]:
|
||||
"""Leaves the members of the domain's live models labelled over the new build, so the API reads them instead of the build,
|
||||
and their scenario points computed by the pipeline over those members."""
|
||||
from webapi.model_analysis import refresh_subgroups, warm
|
||||
@contextmanager
|
||||
def _cluster_override(cluster: dict | None):
|
||||
"""Applies a cluster choice to this process's environment while a run lasts, then restores it."""
|
||||
if not cluster:
|
||||
yield
|
||||
return
|
||||
from webapi.detached_jobs import cluster_environment
|
||||
|
||||
started = time.monotonic()
|
||||
saved = dict(os.environ)
|
||||
try:
|
||||
resumen = {"cargados": warm(dominio), "escenarios_recalculados": refresh_subgroups(dominio)}
|
||||
except Exception as exc: # the indicators are already saved
|
||||
log.exception("no se pudieron preparar los modelos de %s", dominio)
|
||||
resumen = f"error: {type(exc).__name__}"
|
||||
return {"paso": "modelos", "segundos": round(time.monotonic() - started, 2), "resumen": _short(resumen)}
|
||||
|
||||
|
||||
def _answer_measures(dominio: str) -> dict[str, Any]:
|
||||
"""Leaves each measure's latest periods answered with what this run loaded (`webapi.kpis.answer_latest`)."""
|
||||
from importlib import import_module
|
||||
|
||||
from webapi.kpis import answer_latest
|
||||
|
||||
started = time.monotonic()
|
||||
manifest = os.environ.get("DBT_MANIFEST")
|
||||
try:
|
||||
resumen = answer_latest(dominio, import_module(f"persistance.{dominio}"), Path(manifest)) if manifest else "sin DBT_MANIFEST"
|
||||
except Exception as exc: # the indicators are already saved
|
||||
log.exception("no se pudieron responder los indicadores de %s", dominio)
|
||||
resumen = f"error: {type(exc).__name__}"
|
||||
return {"paso": "respuestas", "segundos": round(time.monotonic() - started, 2), "resumen": _short(resumen)}
|
||||
cluster_environment({"cluster": cluster}, os.environ)
|
||||
yield
|
||||
finally:
|
||||
os.environ.clear()
|
||||
os.environ.update(saved)
|
||||
|
||||
|
||||
class RecomputationQueue:
|
||||
@@ -92,11 +80,20 @@ class RecomputationQueue:
|
||||
def _status_path(self) -> Path:
|
||||
return self.base / "estado.json"
|
||||
|
||||
def request_run(self, dominio: str) -> None:
|
||||
def request_run(self, dominio: str, cluster: dict | None = None) -> None:
|
||||
"""Queues a run; `cluster` (`{mode, scheduler?}`) picks where the EEG analysis of that run executes."""
|
||||
if dominio not in DOMAINS:
|
||||
raise ValueError(f"dominio desconocido: {dominio!r}")
|
||||
self._pending.mkdir(parents=True, exist_ok=True)
|
||||
(self._pending / dominio).write_text(_now(), encoding="utf-8")
|
||||
(self._pending / dominio).write_text(json.dumps({"at": _now(), "cluster": cluster}), encoding="utf-8")
|
||||
|
||||
def requested_cluster(self, dominio: str) -> dict | None:
|
||||
"""The cluster choice of the queued request, or none for a plain one."""
|
||||
try:
|
||||
marker = json.loads((self._pending / dominio).read_text(encoding="utf-8"))
|
||||
except (FileNotFoundError, json.JSONDecodeError):
|
||||
return None
|
||||
return marker.get("cluster") if isinstance(marker, dict) else None
|
||||
|
||||
def pending(self) -> list[str]:
|
||||
if not self._pending.exists():
|
||||
@@ -133,8 +130,10 @@ class RecomputationQueue:
|
||||
tmp.write_text(json.dumps(status, ensure_ascii=False, indent=2, default=str), encoding="utf-8")
|
||||
tmp.replace(self._status_path)
|
||||
|
||||
def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None) -> dict[str, Any]:
|
||||
"""Runs the domain's graph (without `migrate`: the API migrates on startup)."""
|
||||
def run(self, dominio: str, *, desde: int | None = None, hasta: int | None = None,
|
||||
cluster: dict | None = None) -> dict[str, Any]:
|
||||
"""Runs the domain's graph (without `migrate`: the API migrates on startup). `cluster` overrides where the
|
||||
EEG analysis runs, for this run only."""
|
||||
from webapi.orchestration import Context, run, steps_of
|
||||
from webapi.orchestration.eeg import live_ados2_relation, live_ados2_scoring, live_eeg_analysis
|
||||
from webapi.orchestration.estimators import live_estimators
|
||||
@@ -146,10 +145,11 @@ class RecomputationQueue:
|
||||
self._save_status(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]})
|
||||
entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]}
|
||||
try:
|
||||
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio),
|
||||
eeg_analysis=live_eeg_analysis(dominio), ados2_relation=live_ados2_relation(dominio),
|
||||
ados2_scoring=live_ados2_scoring(dominio))
|
||||
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
|
||||
with _cluster_override(cluster):
|
||||
ctx = Context(dominio, desde, hasta, allow_undecided=True, estimators=live_estimators(dominio),
|
||||
eeg_analysis=live_eeg_analysis(dominio), ados2_relation=live_ados2_relation(dominio),
|
||||
ados2_scoring=live_ados2_scoring(dominio))
|
||||
pasos = run(ctx, only=[p for p in steps_of(dominio) if p != "migrate"])
|
||||
entrada.update(
|
||||
estado="ok",
|
||||
pasos=[{"paso": p.name, "segundos": round(p.seconds, 2), "resumen": _short(p.summary)} for p in pasos],
|
||||
@@ -171,8 +171,9 @@ class RecomputationQueue:
|
||||
"""Runs every pending domain once; returns the ones it ran."""
|
||||
ran = []
|
||||
for dominio in self.pending():
|
||||
choice = self.requested_cluster(dominio)
|
||||
if self.take(dominio):
|
||||
self.run(dominio)
|
||||
self.run(dominio, cluster=choice)
|
||||
ran.append(dominio)
|
||||
return ran
|
||||
|
||||
|
||||
Reference in New Issue
Block a user