Cohorts built from dbt's rules and exported, an idempotent run command and estimate; io split by responsibility, with stored predictions moved into the registry and the ONNX check into tracking

This commit is contained in:
2026-11-05 16:12:23 -06:00
parent 0fdab3651c
commit 9808701c46
35 changed files with 1710 additions and 719 deletions
@@ -1,11 +1,11 @@
"""What this module covers: the `RiskEstimator` contract in `models.io.contract` and the two records it
"""What this module covers: the `RiskEstimator` contract in `models.io.contracts` and the two records it
returns, `Risk` and `Provenance`.
Fixtures: no pytest fixtures. `ConstantEstimator` is the smallest class that meets the contract: one
fixed probability per member and horizon. `Incomplete` lacks `provenance`.
"""
from models.io.contract import Provenance, Risk, RiskEstimator
from models.io.contracts import Provenance, Risk, RiskEstimator
class ConstantEstimator:
+49
View File
@@ -0,0 +1,49 @@
"""What this module covers: `models.io.lineage`, the vocabulary files, runs and versions record their origin with: the
hashes of files and tables, and the rule that decides an output is already done.
Fixtures: none; each test builds its own small table or file.
"""
import pyarrow as pa
import pytest
from models.io.lineage import file_sha256, matches, registered_name, require_match, table_sha256
def test_a_table_hashes_by_its_rows_not_its_metadata():
"""Pins down: the same rows hash the same whatever metadata the table carries, and another row changes the hash.
Fails if metadata such as `built_at` enters the hash, so every rebuild would look new."""
table = pa.table({"pac_id": [1, 2]})
assert table_sha256(table) == table_sha256(table.replace_schema_metadata({"built_at": "now"}))
assert table_sha256(table) != table_sha256(pa.table({"pac_id": [1, 2, 3]}))
def test_files_hash_in_order(tmp_path):
"""Pins down: several files hash as their bytes in the order given, so a model's code hash covers each file. Fails
if a file is skipped or the order stops mattering."""
a, b = tmp_path / "a", tmp_path / "b"
a.write_bytes(b"one")
b.write_bytes(b"two")
assert file_sha256(a, b) != file_sha256(b, a) != file_sha256(a)
def test_an_output_is_done_when_its_lineage_has_every_expected_value():
"""Pins down: recorded lineage matches when every expected key has its value, compared as text since files and
MLflow store text; extra keys don't matter. Fails if a missing key counts as a match or numbers stop matching text."""
recorded = {"armado_id": "7", "n_members": "2", "built_at": "now"}
assert matches(recorded, {"armado_id": 7, "n_members": 2})
assert not matches(recorded, {"armado_id": 7, "content_sha256": "x"})
def test_a_mismatch_is_refused_with_both_sides():
"""Pins down: `require_match` names what was expected and what was found. Fails if a mismatch passes silently."""
with pytest.raises(ValueError, match="doesn't belong.*armado_id"):
require_match({"armado_id": "1"}, {"armado_id": 2}, "build.parquet")
def test_models_are_registered_as_domain_and_scenario():
"""Pins down: the name runs and versions share. Fails if the convention changes on one side only."""
assert registered_name("cacu", "cin2_logistic") == "cacu-cin2_logistic"
+7 -6
View File
@@ -16,9 +16,10 @@ import pytest
from core.governance.enums import Environment
from mlflow import MlflowClient
from models.io import training
from models.io.registry import MODEL_SHA_TAG, registry
from models.io.training import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, TrainingRun
from models.io import lineage
from models.io.lineage import GIT_COMMIT_ENV, GIT_COMMIT_TAG, GIT_DIRTY_TAG, MODEL_SHA_TAG
from models.io.registry import registry
from models.io.tracking import TrainingRun
class Constant(mlflow.pyfunc.PythonModel):
@@ -37,7 +38,7 @@ def _train(model: Constant | None = None, scenario: str = "tamizaje") -> tuple[T
run = TrainingRun(domain="cacu", scenario=scenario, environment=Environment.DEV)
if model is not None:
run.log_model(model)
return run, run.finish(metrics={"auc": 0.7})
return run, registry.register_run(run.finish(metrics={"auc": 0.7}))
def test_a_logged_model_is_what_the_version_loads(mlflow_tracking):
@@ -129,7 +130,7 @@ def test_an_explicit_version_is_returned_with_its_status(production_ready):
def _git(*args: str) -> str:
return subprocess.run(["git", "-C", str(Path(training.__file__).parent), *args], capture_output=True, text=True,
return subprocess.run(["git", "-C", str(Path(lineage.__file__).parent), *args], capture_output=True, text=True,
check=True).stdout.strip()
@@ -155,7 +156,7 @@ def test_without_a_repository_the_commit_comes_from_the_environment(mlflow_track
def no_git(*args, **kwargs):
raise FileNotFoundError("git")
monkeypatch.setattr(training.subprocess, "run", no_git)
monkeypatch.setattr(lineage.subprocess, "run", no_git)
monkeypatch.setenv(GIT_COMMIT_ENV, "abc123")
tags = MlflowClient().get_run(TrainingRun(domain="cacu", scenario="tamizaje",
environment=Environment.DEV).run_id).data.tags
+1 -1
View File
@@ -56,7 +56,7 @@ def test_retire_and_lineage(production_ready):
def test_invalid_onnx_checkpoint_is_rejected(production_ready):
from models.io.export import inspect_onnx_metadata
from models.io.tracking import inspect_onnx_metadata
with pytest.raises(ValueError, match="ONNX"):
import tempfile
@@ -2,8 +2,7 @@ import json
import pytest
from models.io.prediction import ApplicabilityRejected, Interpretability, PredictionService
from models.io.registry import registry
from models.io.registry import ApplicabilityRejected, Interpretability, PredictionService, registry
class StubModel:
@@ -1,4 +1,4 @@
"""What this module covers: `models.io.cohorts`, reading a cohort build's file; and the rule that a model's folder
"""What this module covers: `models.io.storage`, reading a cohort build's file; and the rule that a model's folder
doesn't import the database layer, since the file is its only input.
Fixtures: `cohort_file`, a small Parquet file of a build with two members.
@@ -13,7 +13,8 @@ import pyarrow.parquet as pq
import pytest
import models
from models.io.cohorts import SCHEMA, CohortFileError, read_cohort
from models.io.contracts import COHORT_SCHEMA as SCHEMA, CohortFileError
from models.io.storage import read_cohort
def _row(pac_id, fecha_indice, valor, fuente_id):
@@ -1,10 +1,10 @@
"""What this module covers: `resolve_repository`, how `models` finds a domain's Persistance repository by name.
"""What this module covers: `models.io.storage.resolve_repository`, how `models` finds a domain's Persistance repository by name.
Fixtures: `cacu_db` (from `conftest.py`), an empty CaCu SQLite database per test.
"""
import pytest
from models.io.repositories import resolve_repository
from models.io.storage import resolve_repository
def test_resolves_the_domain_repository_and_reads_its_rows(cacu_db):
@@ -4,7 +4,8 @@ from core.governance.enums import ArtifactKind, Environment
from models.io.registry import registry
from mlflow import MlflowException
from models.io.training import ReadOnlyRepository, TrainingRun
from models.io.storage import ReadOnlyRepository
from models.io.tracking import TrainingRun
def test_prod_run_requires_a_cohort_build():
@@ -23,7 +24,7 @@ def test_finish_registers_model_version_and_artifacts(mlflow_tracking, tmp_path)
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
run.log_artifact(ArtifactKind.ONNX_CHECKPOINT, checkpoint, metadata={"opset": 17})
version = run.finish(metrics={"auc": 0.81})
version = registry.register_run(run.finish(metrics={"auc": 0.81}))
mv = registry.get("cacu", "tamizaje", version)
assert mv.tags["environment"] == Environment.DEV.value
@@ -61,23 +62,34 @@ def test_experiments_keep_artifacts_under_the_configured_root(mlflow_tracking, t
assert experiment.artifact_location.endswith(str(root / "cama-riesgo"))
def test_finish_only_tolerates_an_existing_registered_model(mlflow_tracking, monkeypatch):
def test_registering_only_tolerates_an_existing_registered_model(mlflow_tracking, monkeypatch):
from mlflow import MlflowClient
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
assert run.finish() == "1"
assert registry.register_run(run.finish()) == "1"
second = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
assert second.finish() == "2"
assert registry.register_run(second.finish()) == "2"
third = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV)
def unreachable(name):
def unreachable(self, name):
raise MlflowException("servidor no disponible")
monkeypatch.setattr(third.client, "create_registered_model", unreachable)
monkeypatch.setattr(MlflowClient, "create_registered_model", unreachable)
with pytest.raises(MlflowException, match="no disponible"):
third.finish()
registry.register_run(third.finish())
def test_unknown_domain_is_rejected():
with pytest.raises(ValueError, match="dominio desconocido"):
TrainingRun(domain="x", scenario="tamizaje", environment=Environment.DEV)
def test_finishing_a_run_registers_nothing(mlflow_tracking):
"""Pins down: closing a run logs its metrics and ends it, and only the registry turns it into a version, so a run
can be kept without becoming a model. Fails if `finish` starts registering again."""
run = TrainingRun(domain="cacu", scenario="tamizaje", environment=Environment.DEV).finish(metrics={"auc": 0.5})
assert registry.client.get_run(run.run_id).info.status == "FINISHED"
assert registry.client.search_model_versions("name='cacu-tamizaje'") == []
@@ -2,7 +2,7 @@ import onnx
import onnx.helper
import pytest
from models.io.export import inspect_onnx_metadata
from models.io.tracking import inspect_onnx_metadata
def _tiny_onnx_bytes() -> bytes: