diff --git a/Dockerfile b/Dockerfile index 257c5e0..40b80d1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -49,6 +49,8 @@ ENV MLFLOW_DISABLE_TELEMETRY=true DO_NOT_TRACK=true # Aggregate import log and the live indicator queue (webapi.recomputation). ENV WEBAPI_REPORT_DIR=/data/reportes ENV INDICADORES_DIR=/data/indicadores +# Each API worker loads the live models' members as it starts (`webapi.model_analysis.warm`). +ENV WEBAPI_PRECALENTAR_MODELOS=1 ENV MLFLOW_DISABLE_AGENT_HINT=1 # Without it the measure routes (//indicadores, //fhir) aren't # registered. The entrypoint replaces it with one compiled against the diff --git a/tests/test_model_analysis.py b/tests/test_model_analysis.py index 1eb2880..f2cae90 100644 --- a/tests/test_model_analysis.py +++ b/tests/test_model_analysis.py @@ -207,3 +207,36 @@ def test_without_a_recurrence_version_it_is_a_404(recurrence_client): recurrence_client.holder.production = None assert recurrence_client.get("/cama/modelo/recurrencia").status_code == 404 + + +def test_the_members_are_computed_once_per_build_and_version_and_read_from_their_file_after(tmp_path, monkeypatch): + """Pins down: the first reader of a build's labelled members computes them from the build and leaves them in + `INDICADORES_DIR/modelos`; the next reader (another worker, or the API after the cycle) reads that file without touching the + build, and a new build replaces the old file. Fails if every worker reads the build again, or old builds pile up.""" + import pandas as pd + from models.cama.survival import live + from models.io import storage + from webapi import model_analysis + + monkeypatch.setenv("INDICADORES_DIR", str(tmp_path)) + reads = [] + + class Build: + def __init__(self, domain, build_id): + reads.append(build_id) + + def frame(self): + return pd.DataFrame() + + def lineage(self): + return {} + + monkeypatch.setattr(storage, "KitBuild", Build) + monkeypatch.setattr(live, "members", lambda spec, frame, lineage: pd.DataFrame({"pac_id": [1, 2], "stage": ["I", None]})) + + first = model_analysis._members("spec", "cama", "survival", "3", 8) + again = model_analysis._members("spec", "cama", "survival", "3", 8) + model_analysis._members("spec", "cama", "survival", "3", 9) + + assert reads == [8, 9] and again.equals(first) + assert [p.name for p in (tmp_path / "modelos").iterdir()] == ["cama-survival-v3-armado9.parquet"] diff --git a/webapi/__init__.py b/webapi/__init__.py index 3ce811c..7137e86 100644 --- a/webapi/__init__.py +++ b/webapi/__init__.py @@ -1,4 +1,5 @@ import datetime as _dt +import logging import os from decimal import Decimal @@ -111,4 +112,22 @@ def create_app() -> Flask: app.register_blueprint(model_analysis_blueprint("cama", "survival"), url_prefix="/cama") app.register_blueprint(recurrence_blueprint(), url_prefix="/cama") + if os.environ.get("WEBAPI_PRECALENTAR_MODELOS") == "1": + _warm_in_background() return app + + +def _warm_in_background() -> None: + """Loads the live models' members in each worker as it starts, so the first patient opened doesn't wait for them.""" + import threading + + from webapi.model_analysis import LIVE_SCENARIOS, warm + + def run(): + for domain in LIVE_SCENARIOS: + try: + warm(domain) + except Exception: # the request that needs them will try again and say why + logging.getLogger(__name__).exception("no se pudieron precargar los modelos de %s", domain) + + threading.Thread(target=run, name="precarga-modelos", daemon=True).start() diff --git a/webapi/model_analysis.py b/webapi/model_analysis.py index cee4fdc..5acabf5 100644 --- a/webapi/model_analysis.py +++ b/webapi/model_analysis.py @@ -7,7 +7,10 @@ data are simulated. 404 while the scenario has no version in production, or its """ import json +import logging +import os from collections import OrderedDict +from pathlib import Path from threading import Lock from flask import Blueprint, jsonify, request @@ -19,6 +22,40 @@ _LIVE: dict = {} _ANSWERS: OrderedDict = OrderedDict() _LOCK = Lock() MAX_ANSWERS = 64 +# The scenarios whose members are scored over the data ingested so far, by domain. +LIVE_SCENARIOS = {"cama": ("survival",)} +log = logging.getLogger(__name__) + + +def _members_path(domain: str, scenario: str, version: str, build_id: int) -> Path: + folder = Path(os.environ.get("INDICADORES_DIR", "indicadores")) / "modelos" + return folder / f"{domain}-{scenario}-v{version}-armado{build_id}.parquet" + + +def _members(spec, domain: str, scenario: str, version: str, build_id: int): + """The build's members labelled for the version: read from the file the first reader left (the cycle or another API worker), or + computed from the build and saved for the next. Reading the build takes minutes; the file, a fraction of a second.""" + import pandas as pd + + from models.cama.survival import live + from models.io.storage import KitBuild + + path = _members_path(domain, scenario, version, build_id) + if path.exists(): + try: + return pd.read_parquet(path) + except (OSError, ValueError): + log.warning("no se pudo leer %s; se recalcula", path) + build = KitBuild(domain, build_id) + labelled = live.members(spec, build.frame(), build.lineage()) + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp") + labelled.to_parquet(tmp) + tmp.replace(path) + for old in path.parent.glob(f"{domain}-{scenario}-v*-armado*.parquet"): + if old != path: + old.unlink(missing_ok=True) + return labelled def _live_context(domain: str, scenario: str): @@ -31,7 +68,6 @@ def _live_context(domain: str, scenario: str): from models.cama.survival import live from models.dags.training import Scenario from models.io.registry import registry - from models.io.storage import KitBuild resolved = registry.resolve(domain, scenario) spec = Scenario.load(domain, scenario) @@ -41,13 +77,25 @@ def _live_context(domain: str, scenario: str): key = (resolved.version, build_id) with _LOCK: if _LIVE.get("key") != key: - build = KitBuild(domain, build_id) model = live.rehydrate(mlflow.sklearn.load_model(resolved.model_uri).steps[-1][1]) - _LIVE.update(key=key, value=(spec, model, live.members(spec, build.frame(), build.lineage()), resolved.version)) + _LIVE.update(key=key, value=(spec, model, _members(spec, domain, scenario, resolved.version, build_id), resolved.version)) _ANSWERS.clear() return _LIVE["value"] +def warm(domain: str) -> list[str]: + """Loads the live context of each of the domain's live scenarios (`LIVE_SCENARIOS`), leaving their members' file for every + reader; the scenarios it loaded. One without a version in production or a build is skipped.""" + loaded = [] + for scenario in LIVE_SCENARIOS.get(domain, ()): + try: + _live_context(domain, scenario) + except LookupError: + continue + loaded.append(scenario) + return loaded + + def _summary(domain: str, scenario: str, version: str, artifact: str = "analisis/desarrollo.json", table: str = "escenarios_resumen") -> list[dict]: """The rows of the scenario summary a version published (`escenarios_resumen`): one per scenario, and for recurrence one per cohort, scenario and horizon. `[]` for a version that published none (trained before the summary existed).""" diff --git a/webapi/recomputation.py b/webapi/recomputation.py index b3819bb..aabffb6 100644 --- a/webapi/recomputation.py +++ b/webapi/recomputation.py @@ -48,6 +48,19 @@ 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.""" + from webapi.model_analysis import warm + + started = time.monotonic() + try: + resumen = warm(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)} + + class RecomputationQueue: """Marker-file queue and status of the indicator recomputations.""" @@ -123,6 +136,7 @@ class RecomputationQueue: estado="ok", pasos=[{"paso": p.name, "segundos": round(p.seconds, 2), "resumen": _short(p.summary)} for p in pasos], ) + 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))})