7d06f9db9d
The `cohorts` and `estimate` steps take the project's cohorts from dbt's manifest (`cohort_urls`) and build each one with models' `build_of` over dbt's queries, instead of the Python-frame TOMLs in models/cohorts, which are gone; without a manifest a project has no cohort steps. The recruitment window and cut-off are dbt's vars. The live estimator reads cin2_logistic through `Scenario` and `KitBuild`, and governance imports `models.reports.experiment`, where models now keeps it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
90 lines
3.2 KiB
Python
90 lines
3.2 KiB
Python
"""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.context import dbt_manifest_path
|
|
from webapi.orchestration.project import cohort_urls
|
|
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, manifest, *adaptadores) -> driver.Driver:
|
|
return (driver.Builder()
|
|
.with_modules(cycle)
|
|
.with_config({"with_cohorts": bool(cohort_urls(proyecto, manifest))})
|
|
.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, manifest=None) -> 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, manifest or dbt_manifest_path()))
|
|
|
|
|
|
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, ctx.dbt_manifest, 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)
|