English names: orchestration (cycle, context, runner, repositories), its steps, fields and CLI, recomputation, follow_up and reports
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
"""Each domain's cycle (CaCu, CaMa): from the staging the import leaves to the silver tables, the reference tables, the
|
||||
publication catalog and the views dbt compiled, which the measures are answered over. [Hamilton](https://hamilton.apache.org/)
|
||||
runs it.
|
||||
|
||||
Each step is a function of `cycle.py`. It takes the `Context` and, as parameters, the steps that must run before it;
|
||||
Hamilton builds the graph from those names. Steps pass no data: everything goes through the database, by
|
||||
Persistance's repositories (`ctx.repos`), so each one can run on its own.
|
||||
|
||||
migrate -> catalogs, registry, definitions
|
||||
catalogs -> load, check_silver
|
||||
load -> views, event_models, observe, check_silver
|
||||
registry -> observe
|
||||
event_models -> cohorts (only where there are cohorts: CaCu)
|
||||
cohorts -> estimate
|
||||
|
||||
uv run python -m webapi.orchestration cycle cacu --from 2024 --to 2026
|
||||
uv run python -m webapi.orchestration cycle cama --from 2025 --to 2025 --only event_models
|
||||
uv run python -m webapi.orchestration confirm-risks cacu 3 --reason "revisado por clínica"
|
||||
|
||||
The `indicadores` service (`webapi.recomputation`) runs the same cycle, without `migrate`, each time an import writes
|
||||
data.
|
||||
|
||||
Module | What it does
|
||||
------------------|-------------
|
||||
`cycle.py` | The steps
|
||||
`runner.py` | `run(ctx, only=...)`: builds Hamilton's driver and runs the steps asked, in order
|
||||
`context.py` | The `Context`: project, years, cut-off, rules file and repositories
|
||||
`repositories.py` | `repositories_of(project)`: Persistance's repositories, by layer
|
||||
`project.py` | A project's period types and cohort definitions
|
||||
`connection.py` | Points Persistance at another database in the same process (tests)
|
||||
`semantic_layer.py` | dbt's views a project's measures read, and the publication catalog
|
||||
"""
|
||||
|
||||
from webapi.orchestration.context import Context
|
||||
from webapi.orchestration.runner import Step, run, steps_of
|
||||
|
||||
__all__ = ["Context", "Step", "run", "steps_of"]
|
||||
@@ -0,0 +1,63 @@
|
||||
"""La línea de comandos de la orquestación.
|
||||
|
||||
uv run python -m webapi.orchestration cycle cacu --from 2024 --to 2026 [--cutoff 2026-01-01] [--allow-undecided]
|
||||
uv run python -m webapi.orchestration cycle cama --from 2025 --to 2025 --only event_models
|
||||
uv run python -m webapi.orchestration confirm-risks cacu 3 --reason "revisado por clínica" [--void]
|
||||
|
||||
La base es la de `<PROYECTO>_DATABASE_URL`, como en Persistance.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import logging
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
|
||||
from webapi.orchestration.context import Context
|
||||
from webapi.orchestration.runner import run
|
||||
|
||||
PROJECTS = ("cacu", "cama")
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> None:
|
||||
lector = argparse.ArgumentParser(prog="orchestration", description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ordenes = lector.add_subparsers(dest="orden", required=True)
|
||||
c = ordenes.add_parser("cycle", help="corre los pasos del proyecto en orden")
|
||||
c.add_argument("project", choices=PROJECTS)
|
||||
c.add_argument("--from", dest="year_from", type=int, required=True, help="primer año de periodos")
|
||||
c.add_argument("--to", dest="year_to", type=int, required=True, help="último año de periodos")
|
||||
c.add_argument("--cutoff", type=date.fromisoformat, default=None)
|
||||
c.add_argument("--allow-undecided", action="store_true")
|
||||
c.add_argument("--parameters", type=Path, default=None, help="otro archivo de parámetros (por omisión, el del kit)")
|
||||
c.add_argument("--only", nargs="+", default=None, help="solo estos pasos")
|
||||
r = ordenes.add_parser("confirm-risks", help="confirma (final) o anula un lote de riesgos (ADR-MD-008)")
|
||||
r.add_argument("project", choices=PROJECTS)
|
||||
r.add_argument("lote_id", type=int)
|
||||
r.add_argument("--reason", required=True, help="por qué se confirma o se anula; queda en cada evaluación")
|
||||
r.add_argument("--void", action="store_true", help="anular (entered-in-error) en vez de confirmar")
|
||||
args = lector.parse_args(argv)
|
||||
|
||||
if args.orden == "confirm-risks":
|
||||
cambiadas = confirm_risks(args.project, args.lote_id, args.reason, void=args.void)
|
||||
print(f"lote {args.lote_id}: {cambiadas} evaluaciones {'anuladas' if args.void else 'confirmadas'}")
|
||||
return
|
||||
logging.basicConfig(level=logging.INFO, format="%(message)s")
|
||||
ctx = Context(args.project, args.year_from, args.year_to, args.cutoff, args.allow_undecided, args.parameters)
|
||||
for paso in run(ctx, only=args.only):
|
||||
print(f"{paso.name:20} {paso.seconds:6.1f} s")
|
||||
|
||||
|
||||
def confirm_risks(project: str, lote_id: int, reason: str, *, void: bool = False) -> int:
|
||||
"""Pasa las evaluaciones vigentes del lote a `final` (o a `entered-in-error`), cada una con una versión nueva.
|
||||
|
||||
No es un paso del ciclo: es una decisión de alguien, con su motivo (ADR-MD-008).
|
||||
"""
|
||||
from persistance.edges.gold import ERROR, FINAL
|
||||
|
||||
from webapi.orchestration.repositories import repositories_of
|
||||
|
||||
return repositories_of(project).gold.cohorts.change_state(lote_id, ERROR if void else FINAL, reason)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Apuntar Persistance a la base de un proyecto. Es lo que hace `<PROYECTO>_DATABASE_URL`.
|
||||
|
||||
Persistance lee su configuración al importarse; para cambiar de base en el
|
||||
mismo proceso (pruebas, dev-data) se cambia el ajuste en memoria y se limpia la
|
||||
caché del motor. Igual que `dev_data.ingesta.apuntar`.
|
||||
"""
|
||||
|
||||
from persistance.settings import settings
|
||||
|
||||
from persistance import db
|
||||
|
||||
|
||||
def point_to(proyecto: str, url: str) -> None:
|
||||
motor = getattr(db, f"get_{proyecto}_engine")
|
||||
if motor.cache_info().currsize:
|
||||
motor().dispose()
|
||||
setattr(settings, f"{proyecto}_database_url", url)
|
||||
motor.cache_clear()
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Lo que recibe cada paso del ciclo."""
|
||||
|
||||
import os
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import date
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
|
||||
def dbt_manifest_path() -> Path | None:
|
||||
"""The deployment's dbt manifest, from `DBT_MANIFEST`."""
|
||||
ruta = os.environ.get("DBT_MANIFEST")
|
||||
return Path(ruta) if ruta else None
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Context:
|
||||
"""Lo que recibe un paso: el proyecto y las opciones del ciclo.
|
||||
|
||||
`anio_inicio` y `anio_fin` son los años de los periodos que se registran y
|
||||
calculan. `corte` es la fecha hasta la que llegan los datos; sin ella, cada
|
||||
paso del kit toma la de la última carga. `permitir_sin_definir` deja correr
|
||||
con parámetros que nadie ha decidido: hay que pedirlo a propósito, como en
|
||||
el kit. `parametros` es el archivo de parámetros que carga `registry`; sin
|
||||
él, el `parametros.toml` del kit. `repos` es todo lo que el paso usa
|
||||
para tocar la base: nunca abre una sesión por su cuenta (`repositories.py`).
|
||||
"""
|
||||
|
||||
project: str
|
||||
year_from: int
|
||||
year_to: int
|
||||
cutoff: date | None = None
|
||||
allow_undecided: bool = False
|
||||
parameters: Path | None = None
|
||||
# The `manifest.json` of `dbt compile`: the measures are defined there (`webapi.metrics`), and from it the cycle
|
||||
# creates their event models (`event_models`) and seeds the publication catalog (`definitions`).
|
||||
dbt_manifest: Path | None = field(default_factory=dbt_manifest_path)
|
||||
# Los estimadores de riesgo por cohorte (`cohorte_url` -> objeto con `estimate(columnas, filas)`, `procedencia()`
|
||||
# y `desenlace`; ADR-MD-008). Sin ellos, el paso `estimate` no hace nada.
|
||||
estimators: Mapping[str, Any] = field(default_factory=dict, compare=False, repr=False)
|
||||
# Los repositorios del proyecto (`repositorios.Repositorios`); el ejecutor los pone si faltan.
|
||||
repos: Any = field(default=None, compare=False, repr=False)
|
||||
@@ -0,0 +1,229 @@
|
||||
"""Los pasos del ciclo de un proyecto, como funciones de Hamilton.
|
||||
|
||||
Cada paso recibe el `Context` y, como parámetros, los pasos que tienen que
|
||||
correr antes; de esos nombres sale el grafo. Los pasos no se pasan datos entre
|
||||
sí: todo va por la base, a través de `ctx.repos`, así que cada uno se puede
|
||||
correr solo (`ejecutor.correr(ctx, solo=[...])`).
|
||||
|
||||
El kit calcula (funciones puras, o funciones de una sesión) y los repositorios
|
||||
de `persistance.edges` escriben, cada operación en una sesión (ADR-MD-005).
|
||||
Bronce lo escribe la ingesta, fuera del ciclo.
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import date, datetime
|
||||
from functools import partial
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
|
||||
from hamilton.function_modifiers import config
|
||||
from indicadores_kit.calidad.plata import verificar_plata as calidad_de_la_plata
|
||||
from indicadores_kit.oro.cohortes.armado import armado_de, leer_marco, ultimo_armado
|
||||
from indicadores_kit.oro.cohortes.definicion import leer_definicion
|
||||
from indicadores_kit.plata.carga import carga_desde_staging, tablas_de_staging
|
||||
from indicadores_kit.plata.periodo_observacion import periodos_de_observacion
|
||||
from indicadores_kit.plata.vistas import ddl_de_vistas as ddl_de_v_persona
|
||||
from indicadores_kit.registry.apoyo import (
|
||||
CLAVE_DIM_FECHA_DESDE,
|
||||
filas_de_dim_fecha,
|
||||
grupos_de_edad_de,
|
||||
)
|
||||
from indicadores_kit.registry.catalogos import catalogo_desde_toml, ruta_de_catalogo
|
||||
from indicadores_kit.registry.parametros import (
|
||||
RUTA_PARAMETROS,
|
||||
leer_parametros,
|
||||
valores_del_archivo,
|
||||
)
|
||||
from indicadores_kit.registry.periodos import periodos_de_tipos
|
||||
from indicadores_kit.tablas import tablas_de
|
||||
from persistance.edges.silver import save_load_in
|
||||
from sqlmodel import SQLModel, func, select
|
||||
|
||||
from webapi.orchestration.context import Context
|
||||
from webapi.orchestration.semantic_layer import catalog_layers, event_views
|
||||
from webapi.orchestration.project import cohort_definitions, period_types
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def migrate(ctx: Context) -> str:
|
||||
"""`alembic upgrade head` del dominio, con el `alembic.ini` de Persistance."""
|
||||
from alembic import command
|
||||
from alembic.config import Config
|
||||
|
||||
import persistance
|
||||
|
||||
ini = Path(persistance.__file__).parent / ctx.project / "alembic.ini"
|
||||
raiz = logging.getLogger()
|
||||
manejadores, nivel = raiz.handlers[:], raiz.level
|
||||
estado = [(r, r.disabled) for r in logging.root.manager.loggerDict.values() if isinstance(r, logging.Logger)]
|
||||
command.upgrade(Config(str(ini)), "head")
|
||||
# `env.py` llama a `fileConfig`, que apaga los registradores ya creados y cambia los de la raíz.
|
||||
for registrador, apagado in estado:
|
||||
registrador.disabled = apagado
|
||||
raiz.handlers[:], raiz.level = manejadores, nivel
|
||||
return "head"
|
||||
|
||||
|
||||
def catalogs(migrate: str, ctx: Context) -> dict[str, int]:
|
||||
"""`core/catalogos/<proyecto>.toml` -> `cat_estudio`, `cat_resultado`, `cat_valor`: agrega, actualiza y retira; no borra."""
|
||||
catalogo = catalogo_desde_toml(ruta_de_catalogo(ctx.project), tablas=tablas_de(ctx.project))
|
||||
return ctx.repos.silver.catalogs.sync(catalogo.estudios, catalogo.resultados, catalogo.valores)
|
||||
|
||||
|
||||
def load(catalogs: dict[str, int], ctx: Context) -> SQLModel:
|
||||
"""`carga`, `persona`, `procedimiento` y `observacion_clinica` desde staging (T-20c).
|
||||
|
||||
Incremental por la llave lógica de cada procedimiento (`save_load_in`): repetir no cambia nada.
|
||||
"""
|
||||
tablas, staging = tablas_de(ctx.project), tablas_de_staging(ctx.project)
|
||||
|
||||
def leer(sesion):
|
||||
filas = {modelo.__tablename__: list(sesion.exec(select(modelo))) for modelo in staging}
|
||||
return carga_desde_staging(filas, proyecto=ctx.project)
|
||||
|
||||
def escribir(sesion, datos):
|
||||
return save_load_in(sesion, carga=tablas.Carga, persona=tablas.Persona, procedimiento=tablas.Procedimiento,
|
||||
observacion=tablas.Observacion, fuente=datos.fuente, personas=datos.personas,
|
||||
plata=datos.plata)
|
||||
|
||||
return ctx.repos.materializer.materialize(leer, escribir)
|
||||
|
||||
|
||||
def views(load: SQLModel, ctx: Context) -> int:
|
||||
"""`v_persona`, with the project's person columns: what the follow-up list reads. Returns the views in the base."""
|
||||
return len(ctx.repos.silver.views.build_all(ddl_de_v_persona(tablas_de(ctx.project).Persona)))
|
||||
|
||||
|
||||
def registry(migrate: str, ctx: Context) -> list[str]:
|
||||
"""`parametros.toml` (o `ctx.parameters`) -> `def_parametro` (se reemplaza), los periodos que falten en
|
||||
`dim_periodo` y las tablas de apoyo `dim_fecha` y `dim_grupo_edad` (se reemplazan; I-MD27).
|
||||
|
||||
El archivo se lee y valida antes de escribir. Los periodos no se reemplazan:
|
||||
los reportes guardados apuntan a ellos. `dim_fecha` va de `comun.dim_fecha.desde` al fin
|
||||
de `ctx.year_to` o del año del corte, el mayor; `dim_grupo_edad`, de los cortes de `<proyecto>.grupos_edad`, si el
|
||||
proyecto los tiene (TEA no).
|
||||
"""
|
||||
tablas, tipos = tablas_de(ctx.project), period_types(ctx.project, _manifest(ctx))
|
||||
ruta = ctx.parameters or RUTA_PARAMETROS
|
||||
parametros = leer_parametros(ruta, tablas=tablas)
|
||||
periodos = periodos_de_tipos(tipos, ctx.year_from, ctx.year_to, tablas=tablas)
|
||||
valores = valores_del_archivo(ruta)
|
||||
# Hasta el fin del último año del ciclo o del año del corte (por omisión, la última carga: hoy), el que sea mayor.
|
||||
hasta = date(max(ctx.year_to, (ctx.cutoff or date.today()).year), 12, 31)
|
||||
desde = date.fromisoformat(valores[CLAVE_DIM_FECHA_DESDE])
|
||||
grupos = grupos_de_edad_de(ctx.project, valores, tablas=tablas)
|
||||
gold = ctx.repos.gold
|
||||
gold.parameters.replace_all(parametros)
|
||||
gold.periods.add_missing(periodos)
|
||||
if gold.dates is not None and not _covers(gold.dates, desde, hasta):
|
||||
gold.dates.replace_in_bulk(filas_de_dim_fecha(valores, hasta, proyecto=ctx.project))
|
||||
if gold.age_groups is not None and grupos is not None:
|
||||
gold.age_groups.replace_all(grupos)
|
||||
return tipos
|
||||
|
||||
|
||||
def _covers(fechas, desde: date, hasta: date) -> bool:
|
||||
"""`dim_fecha` ya es exactamente de `desde` a `hasta`: tiene los dos extremos y un día por fecha."""
|
||||
return (fechas.get(desde) is not None and fechas.get(hasta) is not None
|
||||
and fechas.count() == (hasta - desde).days + 1)
|
||||
|
||||
|
||||
def definitions(migrate: str, ctx: Context) -> dict[str, int]:
|
||||
"""The publication catalog (`cat_measure*`, `cat_estrato`) from the measures in dbt's manifest.
|
||||
|
||||
It's synchronized: what a report's unit uses isn't deleted.
|
||||
"""
|
||||
capas = catalog_layers(ctx.project, _manifest(ctx))
|
||||
return {"definitions": len(capas[0]), **ctx.repos.gold.publication.sync(capas)}
|
||||
|
||||
|
||||
def event_models(load: SQLModel, ctx: Context) -> int:
|
||||
"""The event models the measures are asked over, created from dbt's compiled SQL. Returns the views in the base."""
|
||||
return len(ctx.repos.silver.views.build_all(event_views(_manifest(ctx), ctx.project)))
|
||||
|
||||
|
||||
def _manifest(ctx: Context) -> Path:
|
||||
if ctx.dbt_manifest is None:
|
||||
raise ValueError("the cycle needs dbt's manifest (`dbt_manifest`): the measures are defined there")
|
||||
return ctx.dbt_manifest
|
||||
|
||||
|
||||
def observe(load: SQLModel, registry: list[str], ctx: Context) -> int:
|
||||
"""`periodo_observacion`: desde y hasta cuándo hay datos de cada paciente."""
|
||||
return ctx.repos.silver.observation.observar(partial(
|
||||
periodos_de_observacion, proyecto=ctx.project, corte=ctx.cutoff,
|
||||
permitir_sin_definir=ctx.allow_undecided,
|
||||
))
|
||||
|
||||
|
||||
def check_silver(load: SQLModel, catalogs: dict[str, int], ctx: Context) -> dict[str, int]:
|
||||
"""Lo que está mal en `procedimiento` y `observacion` (`plata.calidad`). Solo lee; avisa en el registro."""
|
||||
conteos = ctx.repos.silver.links.check(partial(calidad_de_la_plata, tablas=tablas_de(ctx.project)))
|
||||
for nombre, n in conteos.items():
|
||||
if n:
|
||||
log.warning("%s, plata de dos tablas: %d %s.", ctx.project, n, nombre.replace("_", " "))
|
||||
return conteos
|
||||
|
||||
|
||||
@config.when(with_cohorts=True)
|
||||
def cohorts(event_models: int, ctx: Context) -> dict[str, tuple[int, bool]]:
|
||||
"""Arma cada cohorte del proyecto con la ventana de los años del contexto y el corte (o la última carga).
|
||||
|
||||
Reads dbt's timeline (`event_models` creates it), the same the models and the measures' strata read.
|
||||
"""
|
||||
tablas = tablas_de(ctx.project)
|
||||
tablas_cohorte = import_module(f"indicadores_kit.{ctx.project}.tablas").COHORTES
|
||||
inicio, fin = date(ctx.year_from, 1, 1), date(ctx.year_to + 1, 1, 1)
|
||||
|
||||
def armado(definicion, sesion):
|
||||
corte = ctx.cutoff or _last_load_date(sesion, tablas)
|
||||
return armado_de(sesion, definicion, inicio, fin, corte, cohortes=tablas_cohorte,
|
||||
linea=ctx.repos.silver.timeline.query)
|
||||
|
||||
armados = {}
|
||||
for ruta in cohort_definitions(ctx.project):
|
||||
definicion = leer_definicion(ruta)
|
||||
armados[definicion.url] = ctx.repos.gold.cohorts.assemble(partial(armado, definicion))
|
||||
return armados
|
||||
|
||||
|
||||
@config.when(with_cohorts=True)
|
||||
def estimate(cohorts: dict[str, tuple[int, bool]], ctx: Context) -> dict[str, tuple[int, bool]]:
|
||||
"""El riesgo de los miembros del armado más reciente de cada cohorte que tiene estimador (ADR-MD-008).
|
||||
|
||||
Lee el marco ancho del armado (`leer_marco`) en una sesión de lectura, se lo da al estimador
|
||||
(`ctx.estimators[url]`: `estimate(columnas, filas)`, `procedencia()` y `desenlace`) y escribe sus riesgos como
|
||||
un lote `preliminary` (`CohortRepository.guardar_lote`). Estimar lo mismo otra vez no duplica.
|
||||
Devuelve, por cohorte, (`lote_id`, si es nuevo). Confirmar o anular un lote es la orden
|
||||
`confirm-risks`, no este paso.
|
||||
"""
|
||||
tablas_cohorte = import_module(f"indicadores_kit.{ctx.project}.tablas").COHORTES
|
||||
lotes = {}
|
||||
for ruta in cohort_definitions(ctx.project):
|
||||
definicion = leer_definicion(ruta)
|
||||
estimador = ctx.estimators.get(definicion.url)
|
||||
if estimador is None:
|
||||
continue
|
||||
|
||||
def marco(sesion, definicion=definicion):
|
||||
armado_id = ultimo_armado(sesion, definicion.url, cohortes=tablas_cohorte)
|
||||
return armado_id, None if armado_id is None else leer_marco(sesion, armado_id, definicion,
|
||||
cohortes=tablas_cohorte)
|
||||
|
||||
armado_id, ancho = ctx.repos.gold.cohorts.read(marco)
|
||||
if armado_id is None:
|
||||
continue
|
||||
riesgos = [tuple(r) for r in estimador.estimar(*ancho)]
|
||||
lotes[definicion.url] = ctx.repos.gold.cohorts.save_batch(
|
||||
armado_id, estimador.procedencia().como_dict(), estimador.desenlace, riesgos
|
||||
)
|
||||
return lotes
|
||||
|
||||
|
||||
def _last_load_date(sesion, tablas) -> date | None:
|
||||
"""The day of the latest load: its `fin`, or its `inicio` if it didn't finish. None without loads."""
|
||||
ultima = sesion.exec(select(func.max(func.coalesce(tablas.Carga.fin, tablas.Carga.inicio)))).one()
|
||||
if ultima is None or isinstance(ultima, date):
|
||||
return ultima.date() if isinstance(ultima, datetime) else ultima
|
||||
return date.fromisoformat(str(ultima)[:10])
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Lo que el ciclo necesita saber de las definiciones de un proyecto: sus periodos (dbt) y sus cohortes (el kit)."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from indicadores_kit.oro.cohortes.definicion import RAIZ
|
||||
|
||||
|
||||
def period_types(proyecto: str, manifest: Path) -> list[str]:
|
||||
"""The period types the project's measures publish, from their `meta.tipos_periodo` in dbt's manifest."""
|
||||
metrics = json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values()
|
||||
return sorted({t for m in metrics for t in m["config"].get("meta", {}).get("tipos_periodo", [])
|
||||
if m["config"]["meta"].get("measure_url", "").startswith(f"{proyecto}/")})
|
||||
|
||||
|
||||
def cohort_definitions(proyecto: str) -> list[Path]:
|
||||
"""Los TOML de cohortes que el ciclo arma (`<proyecto>/cohortes/*.toml`): hoy solo CaCu (vigilancia). Las de `cohortes/propuestas/` no (T-21h)."""
|
||||
return sorted((RAIZ / proyecto / "cohortes").glob("*.toml"))
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Los repositorios que recibe un paso (`ctx.repos`), agrupados por capa: bronce, plata y oro.
|
||||
|
||||
Las subclases viven en `persistance/edges/<capa>/` y se
|
||||
instancian en `persistance/<proyecto>/__init__.py` con la fábrica de sesión del
|
||||
dominio. Aquí solo se juntan: la orquestación no nombra ninguna conexión.
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass
|
||||
from importlib import import_module
|
||||
|
||||
from persistance.edges.bronze import StagingRepository
|
||||
from persistance.edges.gold import (
|
||||
CalculationRepository,
|
||||
CohortRepository,
|
||||
PublicationRepository,
|
||||
ReferenceRepository,
|
||||
)
|
||||
from persistance.edges.silver import (
|
||||
LoadRepository,
|
||||
CatalogRepository,
|
||||
ObservationRepository,
|
||||
TimelineRepository,
|
||||
LinksRepository,
|
||||
ViewsRepository,
|
||||
)
|
||||
from persistance.materializer import Materializer
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Bronze:
|
||||
"""Lo que deja la ingesta. Solo se lee."""
|
||||
|
||||
staging: StagingRepository
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Silver:
|
||||
"""Los catálogos, las cargas, `v_persona`, el periodo de observación y la verificación de la plata."""
|
||||
|
||||
catalogs: CatalogRepository
|
||||
loads: LoadRepository
|
||||
views: ViewsRepository
|
||||
observation: ObservationRepository
|
||||
links: LinksRepository
|
||||
timeline: TimelineRepository | None = None # the patients' timeline: dbt's view, as the models and the strata read it
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Gold:
|
||||
"""El registro (parámetros, periodos, definiciones), los reportes y las cohortes."""
|
||||
|
||||
parameters: ReferenceRepository
|
||||
periods: ReferenceRepository
|
||||
calculation: CalculationRepository
|
||||
publication: PublicationRepository # el catálogo de publicación de §6f (T-19b)
|
||||
cohorts: CohortRepository | None # donde hay tablas de cohortes (los tres desde MD-12)
|
||||
dates: ReferenceRepository | None = None # `dim_fecha`, desde `comun.dim_fecha.desde` (I-MD27)
|
||||
age_groups: ReferenceRepository | None = None # `dim_grupo_edad`, de `<proyecto>.grupos_edad` (I-MD27)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Repositories:
|
||||
"""Todo lo que un paso usa para tocar la base de su proyecto, por capa."""
|
||||
|
||||
bronze: Bronze
|
||||
silver: Silver
|
||||
gold: Gold
|
||||
# Una sesión para leer y escribir en el mismo paso (`load`).
|
||||
materializer: Materializer | None = None
|
||||
|
||||
|
||||
def repositories_of(proyecto: str) -> Repositories:
|
||||
dominio = import_module(f"persistance.{proyecto}")
|
||||
return Repositories(
|
||||
bronze=Bronze(staging=dominio.staging_repository),
|
||||
silver=Silver(
|
||||
catalogs=dominio.catalog_repository,
|
||||
loads=dominio.carga_repository,
|
||||
views=dominio.views_repository,
|
||||
observation=dominio.observation_period_repository,
|
||||
links=dominio.links_repository,
|
||||
timeline=dominio.timeline_repository,
|
||||
),
|
||||
materializer=dominio.materializer,
|
||||
gold=Gold(
|
||||
parameters=dominio.def_parametro_repository,
|
||||
periods=dominio.dim_periodo_repository,
|
||||
calculation=dominio.calculation_repository,
|
||||
publication=dominio.publication_repository,
|
||||
cohorts=getattr(dominio, "cohort_repository", None),
|
||||
dates=getattr(dominio, "dim_fecha_repository", None),
|
||||
age_groups=getattr(dominio, "dim_grupo_edad_repository", None),
|
||||
),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Corre los pasos de un proyecto (`cycle.py`) con Hamilton.
|
||||
|
||||
Si un paso falla, los anteriores quedan hechos (cada operación de un
|
||||
repositorio es su propia transacción) y se puede volver a correr: los pasos no
|
||||
duplican. Si el contexto no trae repositorios, se le ponen los de Persistance
|
||||
para el proyecto (`repositories_of`).
|
||||
"""
|
||||
|
||||
import logging
|
||||
import time
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass, replace
|
||||
from typing import Any
|
||||
|
||||
from hamilton import driver
|
||||
from hamilton.execution.graph_functions import topologically_sort_nodes
|
||||
from hamilton.lifecycle import NodeExecutionHook
|
||||
|
||||
from webapi.orchestration import cycle
|
||||
from webapi.orchestration.context import Context
|
||||
from webapi.orchestration.project import cohort_definitions
|
||||
from webapi.orchestration.repositories import repositories_of
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Step:
|
||||
"""Lo que dejó un paso: su resumen y cuánto tardó."""
|
||||
|
||||
name: str
|
||||
summary: Any
|
||||
seconds: float
|
||||
|
||||
|
||||
class _Logbook(NodeExecutionHook):
|
||||
"""Anota cada paso que corre, en el orden en que corre."""
|
||||
|
||||
def __init__(self):
|
||||
self.pasos: list[Step] = []
|
||||
self._inicio = 0.0
|
||||
|
||||
def run_before_node_execution(self, **_):
|
||||
self._inicio = time.monotonic()
|
||||
|
||||
def run_after_node_execution(self, *, node_name: str, result: Any, success: bool, **_):
|
||||
if success:
|
||||
self.pasos.append(Step(node_name, result, time.monotonic() - self._inicio))
|
||||
log.info("%s: %s en %.1f s", node_name, _short(result), self.pasos[-1].seconds)
|
||||
|
||||
|
||||
def _driver(proyecto: str, *adaptadores) -> driver.Driver:
|
||||
return (driver.Builder()
|
||||
.with_modules(cycle)
|
||||
.with_config({"with_cohorts": bool(cohort_definitions(proyecto))})
|
||||
.with_adapters(*adaptadores)
|
||||
.build())
|
||||
|
||||
|
||||
def _in_order(dr: driver.Driver) -> list[str]:
|
||||
return [n.name for n in topologically_sort_nodes(list(dr.graph.get_nodes())) if not n.user_defined]
|
||||
|
||||
|
||||
def steps_of(proyecto: str) -> list[str]:
|
||||
"""Los pasos del proyecto en un orden que respeta sus dependencias (los de cohortes, only donde hay definiciones)."""
|
||||
return _in_order(_driver(proyecto))
|
||||
|
||||
|
||||
def run(ctx: Context, *, only: Sequence[str] | None = None) -> list[Step]:
|
||||
"""Corre el ciclo del proyecto en el orden de sus dependencias. `only`: los pasos a correr; los demás no corren.
|
||||
|
||||
Los pasos que no corren se le dan a Hamilton ya resueltos. Así entre dos pedidos puede no quedar dependencia
|
||||
(`load` y `compute` sin `views`), por eso se le piden en el orden del grafo completo.
|
||||
"""
|
||||
if ctx.repos is None:
|
||||
ctx = replace(ctx, repos=repositories_of(ctx.project))
|
||||
bitacora = _Logbook()
|
||||
dr = _driver(ctx.project, bitacora)
|
||||
todos = _in_order(dr)
|
||||
pedidos = [p for p in todos if only is None or p in only]
|
||||
dr.execute(pedidos, inputs={"ctx": ctx}, overrides={p: None for p in todos if p not in pedidos})
|
||||
return bitacora.pasos
|
||||
|
||||
|
||||
def _short(resumen: Any) -> str:
|
||||
if isinstance(resumen, dict):
|
||||
return f"{len(resumen)} elementos"
|
||||
return str(resumen)
|
||||
@@ -0,0 +1,78 @@
|
||||
"""What the cycle takes from dbt's manifest: the event models to create and the catalog the reports point to.
|
||||
|
||||
The measures are defined in dbt's semantic layer (`webapi.metrics`, `webapi.compositions`). Their event models have
|
||||
to exist in the database for a measure to be asked; `event_views` gives the DDL that creates them from dbt's compiled
|
||||
SQL, as `dbt run` would for a view. The publication catalog (`cat_measure*`, `cat_estrato`) is what the reports'
|
||||
units point to; `catalog_layers` builds it from the same definitions, parents before children.
|
||||
"""
|
||||
|
||||
import json
|
||||
from importlib import import_module
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import text
|
||||
|
||||
from webapi.compositions import composition_definitions
|
||||
from webapi.durations import OBSERVATION, duration_definitions
|
||||
from webapi.kpis import scoring_of
|
||||
from webapi.metrics import measure_definitions
|
||||
|
||||
CONTRACTS = {"proportion": "C1", "composition": "C2", "continuous-variable": "C3r"} # the publication views
|
||||
STRATUM_LABELS = {"grupo_edad": "Grupo de edad"} # unless the stratum's `etiqueta` says otherwise
|
||||
|
||||
|
||||
def event_views(manifest: Path, project: str) -> list:
|
||||
"""`drop view if exists` and `create view … as <compiled SQL>` for every model the project's measures read,
|
||||
parents first.
|
||||
|
||||
Those are the project's models semantic models count over (`models/<project>/…`) and the timelines its strata
|
||||
read (`meta.estratos.*.linea`), with the non-ephemeral models they're built on; an ephemeral one is already inlined
|
||||
in its child's compiled SQL. Another domain's models aren't created: their tables may not exist here.
|
||||
"""
|
||||
m = json.loads(manifest.read_text(encoding="utf-8"))
|
||||
nodes = {n["unique_id"]: n for n in m["nodes"].values()}
|
||||
by_name = {n["name"]: uid for uid, n in nodes.items() if n["resource_type"] == "model"}
|
||||
roots = {uid for uid in (s["depends_on"]["nodes"][0] for s in m["semantic_models"].values())
|
||||
if nodes[uid]["fqn"][1] == project}
|
||||
roots |= {by_name[spec["linea"]] for metric in m["metrics"].values()
|
||||
if metric["config"].get("meta", {}).get("measure_url", "").startswith(f"{project}/")
|
||||
for spec in metric["config"]["meta"].get("estratos", {}).values() if "linea" in spec}
|
||||
ordered: list[str] = []
|
||||
|
||||
def visit(uid: str) -> None:
|
||||
if uid in ordered or uid not in nodes:
|
||||
return
|
||||
for parent in nodes[uid]["depends_on"]["nodes"]:
|
||||
visit(parent)
|
||||
if nodes[uid]["config"]["materialized"] != "ephemeral":
|
||||
ordered.append(uid)
|
||||
|
||||
for uid in sorted(roots):
|
||||
visit(uid)
|
||||
ddl = [text(f"drop view if exists {nodes[uid]['alias']}") for uid in reversed(ordered)]
|
||||
return ddl + [text(f"create view {nodes[uid]['alias']} as {nodes[uid]['compiled_code']}") for uid in ordered]
|
||||
|
||||
|
||||
def catalog_layers(project: str, manifest: Path) -> list[list]:
|
||||
"""The catalog rows of every measure the manifest defines for the project, in layers: parents first."""
|
||||
t = import_module(f"core.{project}.indicadores.models")
|
||||
# The title on screen: `meta.titulo` when the label had to differ (dbt wants labels unique in the project).
|
||||
labels = {n["name"]: n["config"].get("meta", {}).get("titulo") or n["label"]
|
||||
for n in json.loads(manifest.read_text(encoding="utf-8"))["metrics"].values()}
|
||||
definitions = [d for d in (*measure_definitions(manifest).values(), *composition_definitions(manifest).values(),
|
||||
*duration_definitions(manifest).values()) if d.url.startswith(f"{project}/")]
|
||||
labels_of = {s.name: s.spec.get("etiqueta") or STRATUM_LABELS.get(s.name, s.name)
|
||||
for d in definitions for s in d.strata}
|
||||
strata = sorted(labels_of)
|
||||
measures, children = [], []
|
||||
for d in definitions:
|
||||
contract = CONTRACTS[scoring_of(d)]
|
||||
measures.append(t.CatMeasure(measure_id=d.measure_id, url=d.url, version=d.version, titulo=labels[d.metric],
|
||||
contrato=contract, unidad=d.basis))
|
||||
codes = dict.fromkeys((*d.denominator.codes, *d.numerator.codes, *((OBSERVATION,) if contract == "C3r" else ())))
|
||||
children += [t.CatMeasureResultado(resultado_id=f"{d.measure_id}.{c}", measure_id=d.measure_id, poblacion=c,
|
||||
etiqueta=c) for c in codes]
|
||||
children.append(t.CatMeasureGrupo(measure_id=d.measure_id, grupo=d.group, etiqueta=d.group, orden=0))
|
||||
children += [t.CatMeasureEstrato(measure_id=d.measure_id, estrato_id=s.name) for s in d.strata]
|
||||
stratum_rows = [t.CatEstrato(estrato_id=s, etiqueta=labels_of[s], unidad="paciente") for s in strata]
|
||||
return [stratum_rows + measures, children]
|
||||
Reference in New Issue
Block a user