serving (MLflow), HK1K verification command and the tea-verify DaskJob
- serving: plans and biomarkers as MLflow "models from code" (standalone wrapper files), code_paths = only the module's package + contracts; plan.json artifact and plan params; biomarker models pin plan_uri and plan_hash. privacy: no study codes / dates / paths, binary artifacts refused, baselines from fewer than 5 children refused. - verify: python -m tea_modulo.verify hk1k lists HK1K in a worker task, runs the pipeline remotely (line 50 Hz), checks the remote run equals a plain sequential run in one task, summarizes the posterior rhythm by age group (groups < 5 suppressed) and writes the summary under processed/usuarios/. Any input prefix but raw/eeg-helsinki/ is refused. - deploy: Dockerfile.verify (dask:1.1 + antropy, fhir.resources, meegkit, pytest; tea-modulo from the local checkout), .dockerignore keeping .venv, eeg/ and any signal or patient file out, dask-verify.yaml (own 2x4-worker cluster, no eeg-data PVC, keys only on workers), verify.sh. Tests: MLflow round trips on sqlite, model loads with only its own code in a fresh interpreter, privacy refusals, verify guards.
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
"""MLflow round trips on a temporary sqlite store, and the privacy guard."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
mlflow = pytest.importorskip("mlflow")
|
||||
|
||||
from tea_modulo.legacy.biomarkers.posterior_rhythm import LegacyPosteriorRhythm # noqa: E402
|
||||
from tea_modulo.preprocessing import DIRECTOR_CLUSTER, PreprocessPlan # noqa: E402
|
||||
from tea_modulo.serving import Forbidden, load_biomarker, load_plan, log_biomarker, log_plan # noqa: E402
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def store(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("MLFLOW_DISABLE_AGENT_HINT", "1")
|
||||
uri = f"sqlite:///{tmp_path / 'mlflow.db'}"
|
||||
mlflow.set_tracking_uri(uri)
|
||||
mlflow.set_registry_uri(uri)
|
||||
monkeypatch.chdir(tmp_path) # artifacts land under tmp_path/mlruns
|
||||
yield uri
|
||||
mlflow.set_tracking_uri(None)
|
||||
|
||||
|
||||
def _table(n=300, seed=0):
|
||||
rng = np.random.default_rng(seed)
|
||||
ages = rng.uniform(12, 48, n)
|
||||
return pd.DataFrame({"posterior_rhythm_hz": 5 + ages / 20 + rng.normal(0, .5, n), "age_months": ages})
|
||||
|
||||
|
||||
def test_plan_round_trip(store):
|
||||
v = log_plan(DIRECTOR_CLUSTER, registered_name="tea-plan-director-cluster")
|
||||
d = load_plan(f"models:/tea-plan-director-cluster/{v.version}")
|
||||
assert d["hash"] == DIRECTOR_CLUSTER.content_hash()
|
||||
assert PreprocessPlan.from_dict(d) == DIRECTOR_CLUSTER
|
||||
run = mlflow.get_run(v.run_id)
|
||||
assert run.data.tags["plan_hash"] == DIRECTOR_CLUSTER.content_hash()
|
||||
art = mlflow.artifacts.download_artifacts(run_id=v.run_id, artifact_path="plan/plan.json")
|
||||
assert json.loads(Path(art).read_text())["name"] == "director-cluster"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("baseline", ["curves", "age_blocks"])
|
||||
def test_biomarker_round_trip_pinned_to_plan(store, baseline):
|
||||
pv = log_plan(DIRECTOR_CLUSTER, registered_name="tea-plan-director-cluster")
|
||||
plan_uri = f"models:/tea-plan-director-cluster/{pv.version}"
|
||||
rhythm = LegacyPosteriorRhythm(baseline=baseline).train(_table())
|
||||
bv = log_biomarker(rhythm, plan_uri=plan_uri, registered_name="tea-bio-posterior-rhythm")
|
||||
uri = f"models:/tea-bio-posterior-rhythm/{bv.version}"
|
||||
x = pd.DataFrame({"posterior_rhythm_hz": [5.0, 6.5, 9.0], "age_months": [30.0] * 3})
|
||||
want = rhythm.predict(x)
|
||||
pd.testing.assert_frame_equal(mlflow.pyfunc.load_model(uri).predict(x), want)
|
||||
pd.testing.assert_frame_equal(load_biomarker(uri).predict(x), want)
|
||||
tags = mlflow.get_run(bv.run_id).data.tags
|
||||
assert tags["plan_uri"] == plan_uri and tags["impl"] == "legacy"
|
||||
assert tags["plan_hash"] == DIRECTOR_CLUSTER.content_hash()
|
||||
|
||||
|
||||
def test_biomarker_model_runs_with_only_its_code(store, tmp_path):
|
||||
rhythm = LegacyPosteriorRhythm(baseline="curves").train(_table())
|
||||
bv = log_biomarker(rhythm, registered_name="tea-bio-iso")
|
||||
code = f"""
|
||||
import sys, json, mlflow, pandas as pd
|
||||
mlflow.set_tracking_uri({store!r}); mlflow.set_registry_uri({store!r})
|
||||
m = mlflow.pyfunc.load_model("models:/tea-bio-iso/{bv.version}")
|
||||
import tea_modulo
|
||||
out = m.predict(pd.DataFrame({{"posterior_rhythm_hz": [5.0], "age_months": [30.0]}}))
|
||||
try:
|
||||
import tea_modulo.pipeline
|
||||
other = "importable"
|
||||
except ImportError:
|
||||
other = "missing"
|
||||
print(json.dumps({{"pkg": tea_modulo.__file__, "pipeline": other, "outside": int(out.outside.iloc[0])}}))
|
||||
"""
|
||||
out = subprocess.run([sys.executable, "-W", "ignore", "-c", code], capture_output=True, text=True,
|
||||
cwd=tmp_path, env={**__import__("os").environ, "MLFLOW_DISABLE_AGENT_HINT": "1"})
|
||||
assert out.returncode == 0, out.stderr[-2000:]
|
||||
r = json.loads(out.stdout.strip().splitlines()[-1])
|
||||
assert "code" in Path(r["pkg"]).parts, r["pkg"] # tea_modulo comes from the model's code
|
||||
assert r["pipeline"] == "missing" # nothing else of the library is there
|
||||
assert r["outside"] == -1
|
||||
|
||||
|
||||
def test_privacy_guard(store):
|
||||
with pytest.raises(Forbidden, match="study code"):
|
||||
log_plan(DIRECTOR_CLUSTER, registered_name="eeg_012-plan")
|
||||
small = LegacyPosteriorRhythm(baseline="age_blocks").train(_table(n=4))
|
||||
with pytest.raises(Forbidden, match="fewer than 5"):
|
||||
log_biomarker(small, registered_name="tea-bio-small")
|
||||
Reference in New Issue
Block a user