Files
edgar 0880181219 Merge dev into feature/cohorts-dbt-canonical: TEA EEG analysis and baselines
Conflicts: the README keeps this branch's rows and adds TEA's; `__main__` keeps the Scenario-based commands and adds
`_own_steps`; pyproject keeps the reports/ paths and adds the `eeg-reference` extra. `GIT_COMMIT_TAG` comes back in
`models.io.lineage` as the name of MLflow's own tag, which `models.tea.eeg.bundle` reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HmQxVJVNR5FYkPAregGEQ7
2026-11-20 20:05:13 -06:00

202 lines
8.1 KiB
Python

import mlflow.pyfunc
import pytest
def _wire(monkeypatch, tmp_path, domain: str, base_module: str, base_class: str):
import importlib
from persistance import db as persistance_db
from persistance import settings as persistance_settings
monkeypatch.setattr(persistance_settings.settings, f"{domain}_database_url", f"sqlite:///{tmp_path / f'{domain}.db'}")
engine = getattr(persistance_db, f"get_{domain}_engine")
engine.cache_clear()
importlib.import_module(f"core.{domain}.models")
if domain != "governance":
importlib.import_module(f"core.{domain}.indicadores.models")
base = getattr(importlib.import_module(base_module), base_class)
base.metadata.create_all(engine())
return engine
@pytest.fixture
def governance_db(tmp_path, monkeypatch):
engine = _wire(monkeypatch, tmp_path, "governance", "core.governance.base", "GovernanceModel")
yield
engine.cache_clear()
@pytest.fixture
def cacu_db(tmp_path, monkeypatch):
engine = _wire(monkeypatch, tmp_path, "cacu", "core.cacu.base", "CaCuModel")
yield
engine.cache_clear()
@pytest.fixture
def tea_db(tmp_path, monkeypatch):
engine = _wire(monkeypatch, tmp_path, "tea", "core.tea.base", "TeaModel")
yield
engine.cache_clear()
@pytest.fixture
def mlflow_tracking(tmp_path, monkeypatch):
"""A SQLite-backed MLflow per test; `chdir` keeps the default `./mlruns` in `tmp_path`."""
import mlflow
uri = f"sqlite:///{tmp_path / 'mlflow.db'}"
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
mlflow.set_tracking_uri(uri)
monkeypatch.chdir(tmp_path)
yield
class Echo(mlflow.pyfunc.PythonModel):
"""A model whose class lives in a module, as a PROD run requires: it returns its input."""
def predict(self, context, model_input, params=None):
return model_input
def trained_run(domain: str, scenario: str, armado_id: int | None, metrics: dict, *, routines=None, model: bool = True):
"""A finished PROD run as training leaves it: each routine's record (all of them unless `routines` names some)
and, with `model`, a saved model."""
from core.governance.enums import Environment
from models.io.tracking import ROUTINE_KINDS, TrainingRun
run = TrainingRun(domain=domain, scenario=scenario, environment=Environment.PROD, cohorte_armado_id=armado_id)
for kind in ROUTINE_KINDS if routines is None else routines:
run.log_routine(kind, {"method": "prueba", "n": 8})
if model:
run.log_model(Echo())
return run.finish(metrics=metrics)
@pytest.fixture
def production_ready(governance_db, cacu_db, mlflow_tracking):
"""Factory: registers a PROD version whose run recorded every routine and its model, with the three reports,
so it passes every promotion check; returns (domain, scenario, version)."""
from models.io.registry import registry
def make(tag: str, *, domain: str = "cacu", scenario: str = "tamizaje", metrics: dict | None = None):
run = trained_run(domain, scenario, armado(f"huella-{tag}"), metrics or {"auc": 0.8})
version = registry.register_run(
run, technical_validation_report_uri="docs/tecnica.pdf", clinical_validation_report_uri="docs/clinica.pdf",
interpretability_report_uri="docs/interpretabilidad.html",
)
return domain, scenario, version
return make
def armado(huella: str) -> int:
"""A CaCu cohort build with two attrition steps; returns its `armado_id`."""
from datetime import date, datetime, timezone
from core.cacu.indicadores.models import CohorteArmado, CohorteExclusion
from persistance.db import get_cacu_session
with get_cacu_session() as session:
fila = CohorteArmado(
url="cacu/cohorte_vigilancia", version="1.0", definicion_sha="d", reglas_sha="r", parametros="{}",
datos_as_of=date(2025, 12, 31), huella=huella, marco_sha="m", n_miembros=8,
armado_en=datetime(2026, 1, 1, tzinfo=timezone.utc))
session.add(fila)
session.flush()
session.add_all([CohorteExclusion(armado_id=fila.armado_id, orden=1, paso="candidatas", n=10),
CohorteExclusion(armado_id=fila.armado_id, orden=2, paso="sin evento previo", n=8)])
session.commit()
return fila.armado_id
LOAD_WITHOUT_REPOSITORY = """
import sys
import pandas as pd
sys.modules["models"] = None # importing anything from this repository now fails
sys.modules["hamilton"] = None # nor Hamilton: the artifact runs where the dataflow isn't installed
import mlflow.pyfunc
model = mlflow.pyfunc.load_model(sys.argv[1])
output = pd.DataFrame(model.predict(pd.read_parquet(sys.argv[2])))
output.columns = [str(column) for column in output.columns]
output.to_parquet(sys.argv[3])
"""
@pytest.fixture
def predict_without_repository(tmp_path):
"""Runs a registered version in a separate Python where neither `models` nor `hamilton` can be imported, on a
frame, and returns its output, columns named `"0"`, `"1"`…: what an environment with MLflow and the model's
libraries would get."""
import os
import subprocess
import sys
import pandas as pd
def run(model_uri: str, frame: pd.DataFrame) -> pd.DataFrame:
source, output = tmp_path / "input.parquet", tmp_path / "output.parquet"
frame.to_parquet(source)
env = {**os.environ, "MLFLOW_DISABLE_AGENT_HINT": "1", "PYTHONPATH": ""}
subprocess.run([sys.executable, "-c", LOAD_WITHOUT_REPOSITORY, model_uri, str(source), str(output)],
check=True, env=env, cwd=tmp_path, capture_output=True)
return pd.read_parquet(output)
return run
@pytest.fixture
def kit_stand_ins():
"""Factory: stand-ins of a domain's `cohort_repository` and `timeline_repository` holding one kit build made of a
long frame's members and events, with dates as text as the database returns them. The timeline records each read's
patients and cut-offs."""
from datetime import datetime, timezone
from types import SimpleNamespace
from persistance.edges.gold import CohortBuild, CohortMember
def make(frame, build_id, cutoff, url="cacu/cohorte_vigilancia"):
index_dates = frame.groupby("pac_id")["fecha_indice"].first()
build = CohortBuild(build_id, url, "1", "huella", "marco", cutoff, None, len(index_dates),
datetime(2027, 1, 1, tzinfo=timezone.utc))
cohorts = SimpleNamespace(
latest_build=lambda asked: build_id if asked == url else None,
build=lambda asked: build if asked == build_id else None,
members=lambda asked: [CohortMember(int(p), d, "t", str(p)) for p, d in index_dates.items()])
rows = [{key: value.isoformat() if hasattr(value, "isoformat") else value
for key, value in row.items() if key != "fecha_indice"} for row in frame.to_dict("records")]
class Timeline:
reads = []
def read(self, *, patients=None, until=None, known_until=None):
self.reads.append({"patients": patients, "until": until, "known_until": known_until})
return [row for row in rows if patients is None or row["pac_id"] in set(patients)]
return cohorts, Timeline()
return make
@pytest.fixture
def mlflow_store_leaks():
"""Factory: which of these texts and integers appear, as text or as 8-byte integers, in any file under `root`
outside `skip` (the inputs themselves). Used with values only the training data holds, to show they never reached
MLflow's database or artifacts."""
from pathlib import Path
def scan(root, texts=(), integers=(), skip=()):
needles = {str(t): str(t).encode() for t in texts}
for number in integers:
needles[f"{number} (text)"] = str(number).encode()
needles[f"{number} (int64)"] = int(number).to_bytes(8, "little", signed=True)
found = set()
for path in Path(root).rglob("*"):
if not path.is_file() or any(part in skip for part in path.relative_to(root).parts):
continue
content = path.read_bytes()
found |= {name for name, needle in needles.items() if needle in content}
return sorted(found)
return scan