Compare commits

..

3 Commits

Author SHA1 Message Date
Roberto Treviño Cervantes 5831fcd9d9 Cycle: skip the scenarios whose definition turns off batch_estimates 2026-11-23 00:14:14 -06:00
Roberto Treviño Cervantes bd8c7aa55a Cycle: answer each measure's latest periods after a run, so the first reader finds them stored 2026-11-23 00:06:33 -06:00
Roberto Treviño Cervantes 1048175531 CaMa survival figure: the whole cohort's points from the pipeline's survival stage 2026-11-22 23:46:57 -06:00
4 changed files with 52 additions and 6 deletions
+24
View File
@@ -124,3 +124,27 @@ def _last_load(repositories) -> datetime | None:
"""The start of the domain's last load: what's known now, and stable until the next load."""
_, ((last,),) = repositories.dbt_query_repository.rows(select(func.max(LOADS.c.inicio)))
return last
def answer_latest(project: str, repositories, manifest: Path, *, kinds: tuple[str, ...] = ("semestre", "mes"), latest: int = 2,
today: date | None = None) -> int:
"""Answers and stores each measure's `latest` periods of each kind started by `today`, asked as the dashboard asks them
(every fact dated, what is known at the last load), so the first reader after a load finds them stored. The answers it
gave; a measure whose rule is still undecided is skipped."""
today = today or date.today()
known = _last_load(repositories)
periods = [p for kind in kinds
for p in sorted((p for p in repositories.dim_periodo_repository.list(limit=10000, tipo=kind) if p.inicio <= today),
key=lambda p: p.inicio)[-latest:]]
given = 0
for definition in definitions_of(project, manifest).values():
answer_of, _ = ANSWERS[scoring_of(definition)]
for period in periods:
try:
answer_of(project, definition, Question(definition.url, period.periodo_id, None, known),
parameters=repositories.def_parametro_repository, periods=repositories.dim_periodo_repository,
history=repositories.history_repository, queries=repositories.dbt_query_repository)
except UndecidedRule:
break
given += 1
return given
+7 -4
View File
@@ -133,7 +133,9 @@ def refresh_subgroups(domain: str) -> list[str]:
def _subgroup_rows(domain: str, scenario: str, version: str) -> list[dict]:
"""The scenario points of the latest build computed by the cycle (`refresh_subgroups`), or the ones the version published
when it trained while the cycle hasn't computed them."""
when it trained while the cycle hasn't computed them, the whole cohort's among them as `WHOLE_COHORT`."""
from models.cama.survival.development import WHOLE_COHORT
current = _current_build(domain, scenario)
if current is not None and current[0] == str(version):
path = _subgroups_path(domain, scenario, *current)
@@ -142,7 +144,8 @@ def _subgroup_rows(domain: str, scenario: str, version: str) -> list[dict]:
return json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
log.warning("no se pudo leer %s", path)
return _summary(domain, scenario, version, table="subgrupos_puntos")
return _summary(domain, scenario, version, table="subgrupos_puntos") + [
{**row, "subgrupo": WHOLE_COHORT} for row in _summary(domain, scenario, version, table="cohorte_puntos")]
def warm(domain: str) -> list[str]:
@@ -243,7 +246,7 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
name = (request.get_json(silent=True) or {}).get("escenario")
try:
spec, model, labelled, version = _live_context(domain, scenario)
spec, _, labelled, version = _live_context(domain, scenario)
except LookupError as error:
return jsonify({"error": f"sin curvas: {error}"}), 404
published = live.published_points(_subgroup_rows(domain, scenario, version), name)
@@ -252,7 +255,7 @@ def model_analysis_blueprint(domain: str, scenario: str) -> Blueprint:
record = _ANSWERS.get(key)
if record is None:
try:
record = live.curves(spec, model, labelled, name, published)
record = live.curves(spec, labelled, name, published)
except live.QueryError as error:
return jsonify({"error": str(error)}), 422
with _LOCK:
+4 -2
View File
@@ -63,8 +63,8 @@ class ScenarioEstimator:
def live_estimators(domain: str) -> dict[str, list[ScenarioEstimator]]:
"""The estimators of a domain's cohorts, by cohort url: one per scenario with a version in production in the
registry, so promoting or retiring a version is what adds or drops it. A registered name with no scenario
definition in `models` is skipped. Empty where none is in production, the same as no estimator being
configured: `estimate` then does nothing."""
definition in `models`, or one whose definition turns off `batch_estimates`, is skipped. Empty where none is in
production, the same as no estimator being configured: `estimate` then does nothing."""
from models.dags.training import Scenario
from models.io.registry import registry
@@ -74,5 +74,7 @@ def live_estimators(domain: str) -> dict[str, list[ScenarioEstimator]]:
scenario = Scenario.load(domain, name)
except LookupError:
continue
if not scenario.batch_estimates:
continue
found.setdefault(scenario.cohort, []).append(ScenarioEstimator(domain, name))
return found
+17
View File
@@ -62,6 +62,22 @@ def _warm_models(dominio: str) -> dict[str, Any]:
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)}
class RecomputationQueue:
"""Marker-file queue and status of the indicator recomputations."""
@@ -138,6 +154,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(_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)