Cycle: answer each measure's latest periods after a run, so the first reader finds them stored

This commit is contained in:
Roberto Treviño Cervantes
2026-11-23 00:06:33 -06:00
parent 1048175531
commit bd8c7aa55a
2 changed files with 41 additions and 0 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
+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)