"""Recomputes a domain's indicators after its staging tables change. A successful import asks for a recomputation (`RecomputationQueue.request_run`), which only drops a marker file. A separate process (`python -m webapi.recomputation`, the `indicadores` compose service) watches the markers' directory and, on any change there, runs every pending domain's cycle (`webapi.orchestration.run`): catalogs -> staging to facts -> views -> registry -> definitions -> event models -> cohorts -> estimates, with the live estimators of the models in production (`webapi.orchestration.estimators`). A periodic check (`INDICADORES_INTERVALO_S`) stays as a fallback for a missed or coalesced filesystem event; it no longer sets the normal reaction time. Requests that arrive while a domain is running are folded into one more run. State lives in files under `INDICADORES_DIR`: `pendiente/` markers and `estado.json`; each run is also appended, as counts only, to `indicadores.jsonl` in the import report directory. """ from __future__ import annotations import fcntl import json import logging 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 from watchdog.events import FileSystemEventHandler from watchdog.observers import Observer from webapi.imports.audit import JsonlAuditSink, report_dir, sanitize_message DOMAINS = ("cacu", "cama", "tea") # the domains whose measures the cycle computes _SUMMARY_MAX = 400 log = logging.getLogger(__name__) def _now() -> str: return datetime.now(timezone.utc).isoformat(timespec="seconds") def _short(value: Any) -> str: text = str(value) return text if len(text) <= _SUMMARY_MAX else text[:_SUMMARY_MAX] + "…" @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 saved = dict(os.environ) try: cluster_environment({"cluster": cluster}, os.environ) yield finally: os.environ.clear() os.environ.update(saved) class RecomputationQueue: """Marker-file queue and status of the indicator recomputations.""" def __init__(self, base: Path | None = None): self.base = Path(base or os.environ.get("INDICADORES_DIR", "indicadores")) @property def _pending(self) -> Path: return self.base / "pendiente" @property def _status_path(self) -> Path: return self.base / "estado.json" 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(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(): return [] return sorted(p.name for p in self._pending.iterdir() if p.name in DOMAINS) def take(self, dominio: str) -> bool: """Consumes the marker; a request made from now on queues one more run.""" try: (self._pending / dominio).unlink() return True except FileNotFoundError: return False def status(self) -> dict[str, Any]: try: status = json.loads(self._status_path.read_text(encoding="utf-8")) except (FileNotFoundError, json.JSONDecodeError): status = {} pending = set(self.pending()) return {d: {**status.get(d, {"estado": "sin_correr"}), "pendiente": d in pending} for d in DOMAINS} def _save_status(self, dominio: str, entrada: dict[str, Any]) -> None: self.base.mkdir(parents=True, exist_ok=True) lock = self.base / ".estado.lock" with open(lock, "w") as handle: fcntl.flock(handle, fcntl.LOCK_EX) try: status = json.loads(self._status_path.read_text(encoding="utf-8")) except (FileNotFoundError, json.JSONDecodeError): status = {} status[dominio] = entrada tmp = self._status_path.with_suffix(".tmp") 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, 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 desde = desde or int(os.environ.get("INDICADORES_DESDE", date.today().year - 5)) hasta = hasta or int(os.environ.get("INDICADORES_HASTA", date.today().year)) inicio = _now() started = time.monotonic() self._save_status(dominio, {"estado": "en_curso", "inicio": inicio, "anios": [desde, hasta]}) entrada: dict[str, Any] = {"inicio": inicio, "anios": [desde, hasta]} try: 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], ) entrada["pasos"].append(_answer_measures(dominio)) entrada["pasos"].append(_warm_models(dominio)) except Exception as exc: # the worker must survive a failing domain log.exception("recálculo de %s falló", dominio) entrada.update(estado="error", error={"tipo": type(exc).__name__, "mensaje": sanitize_message(str(exc))}) entrada.update(fin=_now(), duracion_s=round(time.monotonic() - started, 2)) self._save_status(dominio, entrada) try: JsonlAuditSink(report_dir() / "indicadores.jsonl").write({"dominio": dominio, **entrada}) except OSError: pass return entrada def serve(self) -> list[str]: """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, cluster=choice) ran.append(dominio) return ran class _Waker(FileSystemEventHandler): """Wakes the main loop on any change in the pending-markers directory.""" def __init__(self, wake: threading.Event): self._wake = wake def on_any_event(self, event) -> None: self._wake.set() def main() -> None: logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") cola = RecomputationQueue() cola._pending.mkdir(parents=True, exist_ok=True) fallback_s = float(os.environ.get("INDICADORES_INTERVALO_S", "20")) if os.environ.get("INDICADORES_AL_INICIAR", "1") == "1": for dominio in DOMAINS: cola.request_run(dominio) stop = threading.Event() wake = threading.Event() def _stop(*_): stop.set() wake.set() signal.signal(signal.SIGTERM, _stop) signal.signal(signal.SIGINT, _stop) observer = Observer() observer.schedule(_Waker(wake), str(cola._pending), recursive=False) observer.start() log.info("indicadores en vivo: observando %s (respaldo cada %.0f s)", cola._pending, fallback_s) try: while True: for dominio in cola.serve(): log.info("%s: %s", dominio, cola.status()[dominio].get("estado")) if stop.is_set(): break wake.wait(fallback_s) wake.clear() if stop.is_set(): break finally: observer.stop() observer.join() if __name__ == "__main__": main()