Governance: each version stores the drawing of its dataflow as files of its own

Training stores the scenario's Hamilton graph as `diagramas/pipeline.dot` and, when Graphviz's `dot` is installed,
`diagramas/pipeline.svg`, listed next to the version's other files. Without the `graphviz` package there is no
drawing and training goes on.
This commit is contained in:
2026-11-22 07:38:07 -06:00
parent e8c264e571
commit d090bb0f9f
4 changed files with 55 additions and 2 deletions
+20 -1
View File
@@ -8,7 +8,7 @@ scikit-learn estimator that takes the long frame) and `metrics`, with no I/O.
Where the rows come from is the caller's choice (`models.io.storage`: the database or a file); the graph is the same. Where the rows come from is the caller's choice (`models.io.storage`: the database or a file); the graph is the same.
`train` opens the `TrainingRun` before the driver runs, since the run's cohort link is fixed before any node, and marks `train` opens the `TrainingRun` before the driver runs, since the run's cohort link is fixed before any node, and marks
it failed if the graph fails. `find_trained` answers before anything is built whether this source, the installed it failed if the graph fails. Before running, it stores the graph's drawing as `diagramas/pipeline.svg` (and its `.dot`). `find_trained` answers before anything is built whether this source, the installed
`models` version, the config and the environment already have a version. A failing node's inputs, which may hold `models` version, the config and the environment already have a version. A failing node's inputs, which may hold
members' rows, are kept out of Hamilton's error log; the exception still says which node failed. members' rows, are kept out of Hamilton's error log; the exception still says which node failed.
""" """
@@ -108,6 +108,23 @@ def find_trained(scenario: Scenario, source: CohortSource, environment: str = "D
return None return None
def pipeline_drawing(dr: driver.Driver) -> tuple[str, str | None] | None:
"""The scenario's Hamilton graph as Graphviz source and SVG: every node of its modules and the external inputs,
left to right. The SVG is None when Graphviz's `dot` program is missing; the whole drawing is None when the
`graphviz` package is (the `notebooks` extra)."""
try:
graph = dr.display_all_functions(None, orient="LR", show_schema=False)
except ImportError:
return None
if graph is None: # Hamilton logs the missing `graphviz` and gives nothing
return None
try:
svg = graph.pipe(format="svg", encoding="utf-8")
except Exception: # graphviz.ExecutableNotFound or a failed render: the source still goes
svg = None
return graph.source, svg
def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") -> str: def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") -> str:
"""Trains on the source's build and returns the registered version. The run keeps the source's reference, never its """Trains on the source's build and returns the registered version. The run keeps the source's reference, never its
rows.""" rows."""
@@ -117,6 +134,8 @@ def train(scenario: Scenario, source: CohortSource, environment: str = "DEV") ->
try: try:
plain = dataflow(*scenario.modules, config=scenario.config) plain = dataflow(*scenario.modules, config=scenario.config)
required, _ = external_inputs(plain) required, _ = external_inputs(plain)
if drawing := pipeline_drawing(plain):
run.log_diagram("pipeline", *drawing)
loaders = [loader(target=target, source=source) for target, loader in loaders = [loader(target=target, source=source) for target, loader in
(("cohort", from_.cohort_source), ("source_cohort", from_.cohort_source), (("cohort", from_.cohort_source), ("source_cohort", from_.cohort_source),
("cohort_lineage", from_.cohort_source_lineage)) ("cohort_lineage", from_.cohort_source_lineage))
+8
View File
@@ -52,6 +52,7 @@ MODEL_PATH = "model"
ROUTINES_PATH = "rutinas" ROUTINES_PATH = "rutinas"
ANALYSIS_PATH = "analisis" ANALYSIS_PATH = "analisis"
REPORTS_PATH = "reportes" REPORTS_PATH = "reportes"
DIAGRAMS_PATH = "diagramas"
# The routines §5 of the requirements names; a version is promoted only when its run recorded each one. # The routines §5 of the requirements names; a version is promoted only when its run recorded each one.
ROUTINE_KINDS = (ArtifactKind.MUESTREO, ArtifactKind.DATOS_FALTANTES, ArtifactKind.METODO_ANALITICO, ROUTINE_KINDS = (ArtifactKind.MUESTREO, ArtifactKind.DATOS_FALTANTES, ArtifactKind.METODO_ANALITICO,
ArtifactKind.BALANCE_CLASES, ArtifactKind.CONFIANZA_SALIDA) ArtifactKind.BALANCE_CLASES, ArtifactKind.CONFIANZA_SALIDA)
@@ -203,6 +204,13 @@ class TrainingRun:
version keeps for whoever reviews it. Like `log_analysis`, aggregates only.""" version keeps for whoever reviews it. Like `log_analysis`, aggregates only."""
self.client.log_text(self.run_id, page, f"{REPORTS_PATH}/{name}.html") self.client.log_text(self.run_id, page, f"{REPORTS_PATH}/{name}.html")
def log_diagram(self, name: str, dot: str, svg: str | None = None) -> None:
"""A drawing of the run's dataflow, `diagramas/<name>.dot` (Graphviz source) and, when Graphviz's `dot` could
draw it, `diagramas/<name>.svg`: each one more file of the version, listed and downloaded on its own."""
self.client.log_text(self.run_id, dot, f"{DIAGRAMS_PATH}/{name}.dot")
if svg is not None:
self.client.log_text(self.run_id, svg, f"{DIAGRAMS_PATH}/{name}.svg")
def log_model(self, model, *, signature=None, requirements: list[str] | None = None) -> str: def log_model(self, model, *, signature=None, requirements: list[str] | None = None) -> str:
"""Saves `model` under the run's `model` folder, tags the run with its `modelo_sha` and returns it. """Saves `model` under the run's `model` folder, tags the run with its `modelo_sha` and returns it.
Once per run. `signature` describes columns and types only: no input example, so no patient data Once per run. `signature` describes columns and types only: no input example, so no patient data
+2 -1
View File
@@ -216,7 +216,8 @@ def test_training_registers_a_version_and_estimating_dates_each_risk_by_the_mode
assert wrote and resolved.version == version assert wrote and resolved.version == version
files = [f["path"] for f in registry.artifacts("cacu", "survival", version)] files = [f["path"] for f in registry.artifacts("cacu", "survival", version)]
assert {"analisis/curvas.json", "analisis/subgrupos.json", "reportes/subgrupos.html"} <= set(files) assert {"analisis/curvas.json", "analisis/subgrupos.json", "reportes/subgrupos.html", "diagramas/pipeline.dot",
"diagramas/pipeline.svg"} <= set(files)
risks = pq.read_table(output).to_pandas() risks = pq.read_table(output).to_pandas()
assert set(risks["horizonte_anios"]) == {1.0, 3.0, 5.0} and set(risks["pac_id"]) == set(range(1, N + 1)) assert set(risks["horizonte_anios"]) == {1.0, 3.0, 5.0} and set(risks["pac_id"]) == set(range(1, N + 1))
frame = read_cohort(cohort_file) frame = read_cohort(cohort_file)
+25
View File
@@ -139,6 +139,21 @@ def test_training_registers_a_version_from_the_fitted_model_and_the_metrics(scen
assert training.find_trained(scenario, CohortFile(cohort_file)) == version assert training.find_trained(scenario, CohortFile(cohort_file)) == version
def test_training_stores_the_drawing_of_its_dataflow_as_files_of_the_version(scenario, cohort_file, mlflow_tracking):
"""Pins down: the version lists `diagramas/pipeline.dot` and, with Graphviz's `dot`, `diagramas/pipeline.svg`, one
file each (no archive), and the drawing names the scenario's nodes. Fails if training stops drawing its graph or
stores it as anything but separate files."""
pytest.importorskip("graphviz")
version = training.train(scenario, CohortFile(cohort_file))
files = {f["path"] for f in registry.artifacts("cacu", "fake_scenario", version)}
name, dot = registry.artifact("cacu", "fake_scenario", version, "diagramas/pipeline.dot")
assert name == "pipeline.dot" and b"fitted_model" in dot and b"metrics" in dot
assert "diagramas/pipeline.svg" in files or not training.pipeline_drawing(
training.dataflow(*scenario.modules, config=scenario.config))[1]
assert not any(path.endswith(".zip") for path in files)
def test_the_registered_model_runs_without_this_repository(scenario, cohort_file, mlflow_tracking, def test_the_registered_model_runs_without_this_repository(scenario, cohort_file, mlflow_tracking,
predict_without_repository): predict_without_repository):
"""Pins down: the model's own package is pickled by value, so a Python that can't import `models`, Hamilton or the """Pins down: the model's own package is pickled by value, so a Python that can't import `models`, Hamilton or the
@@ -196,3 +211,13 @@ def test_the_registered_model_needs_only_its_listed_requirements(scenario, cohor
assert f"scikit-learn=={installed('scikit-learn')}" in lines and f"numpy=={installed('numpy')}" in lines assert f"scikit-learn=={installed('scikit-learn')}" in lines and f"numpy=={installed('numpy')}" in lines
assert not [line for line in lines if line.startswith("-e") or "/" in line] assert not [line for line in lines if line.startswith("-e") or "/" in line]
def test_without_graphviz_training_has_no_drawing_and_still_registers():
"""Pins down: when Hamilton can't draw (no `graphviz` package, it gives None instead of raising), the drawing
is skipped rather than stopping the training. Fails if `pipeline_drawing` reads a missing graph."""
from types import SimpleNamespace
from models.dags.training import pipeline_drawing
assert pipeline_drawing(SimpleNamespace(display_all_functions=lambda *a, **k: None)) is None