diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..3fcd549 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,17 @@ +.git +**/.git +.venv/ +eeg/ +**/__pycache__/ +**/.pytest_cache/ +**/mlruns/ +**/datos/ +**/salidas/ +**/*.edf +**/*.EDF +**/*.npz +**/*.parquet +**/*.erd +**/*.eeg +**/*_metadata.json +biomarcadores-tea/experimentos/**/salidas/ diff --git a/deploy/Dockerfile.verify b/deploy/Dockerfile.verify new file mode 100644 index 0000000..3eee7df --- /dev/null +++ b/deploy/Dockerfile.verify @@ -0,0 +1,16 @@ +# tea-verify: the team's dask image plus what the tea_modulo verification needs. +# Built from the local checkout (submodules included) by deploy/verify.sh. +FROM 192.168.20.18:5000/dask:1.1 + +# missing from dask:1.1; versions as checked locally +RUN pip install --no-cache-dir "antropy==0.2.3" "fhir.resources==8.3.0" "meegkit==0.2.0" pytest + +# tea-modulo from the local checkout (biomarcadores-tea @ 7dfc641, codigo @ c7a4736: +# the legacy = submodule tests need them). .dockerignore keeps .venv, eeg/ and any +# signal or patient file out of the build context. +COPY . /opt/tea-modulo +ARG TEA_COMMIT=unknown +ENV TEA_COMMIT=$TEA_COMMIT +LABEL tea_modulo.commit=$TEA_COMMIT +RUN pip install --no-cache-dir --no-deps -e /opt/tea-modulo +WORKDIR /opt/tea-modulo diff --git a/deploy/dask-verify.yaml b/deploy/dask-verify.yaml new file mode 100644 index 0000000..4c5055a --- /dev/null +++ b/deploy/dask-verify.yaml @@ -0,0 +1,68 @@ +# tea-verify: test suite + HK1K check, in its own small Dask cluster. +# Applied by deploy/verify.sh (it substitutes COMMIT). HK1K (public) only; +# the eeg-data PVC (patient data) is NOT mounted. +apiVersion: kubernetes.dask.org/v1 +kind: DaskJob +metadata: + name: tea-verify +spec: + job: + spec: + restartPolicy: Never + containers: + - name: job + image: 192.168.20.18:5000/tea-verify:COMMIT + workingDir: /opt/tea-modulo + command: [sh, -c] + args: + - | + set -e + export DASK_SCHEDULER="$DASK_SCHEDULER_ADDRESS" + export MLFLOW_DISABLE_AGENT_HINT=1 + python -m pytest -q -p no:cacheprovider -m "not cluster" + python -m pytest -q -p no:cacheprovider -m cluster + python -m tea_modulo.verify hk1k --out processed/usuarios/alberto/tea-verify/ + env: + - {name: OMP_NUM_THREADS, value: "1"} + - {name: OPENBLAS_NUM_THREADS, value: "1"} + - {name: MKL_NUM_THREADS, value: "1"} + resources: + requests: {memory: 6Gi, cpu: "2"} + limits: {memory: 6Gi} + cluster: + spec: + worker: + replicas: 2 + spec: + containers: + - name: worker + image: 192.168.20.18:5000/tea-verify:COMMIT + args: [dask-worker, --name, $(DASK_WORKER_NAME), --nworkers, "4", --nthreads, "1", --memory-limit, 4.25GiB] + resources: + requests: {memory: 19Gi, cpu: "4"} + limits: {memory: 19Gi} + env: + - {name: AWS_ENDPOINT_URL, value: "http://seaweedfs-s3.seaweedfs:8333"} + - {name: OMP_NUM_THREADS, value: "1"} + - {name: OPENBLAS_NUM_THREADS, value: "1"} + - {name: MKL_NUM_THREADS, value: "1"} + - {name: MLFLOW_DISABLE_AGENT_HINT, value: "1"} + envFrom: + - secretRef: {name: seaweed-s3} + scheduler: + spec: + containers: + - name: scheduler + image: 192.168.20.18:5000/tea-verify:COMMIT + args: [dask-scheduler] + ports: + - {name: tcp-comm, containerPort: 8786} + - {name: http-dashboard, containerPort: 8787} + service: + type: ClusterIP + selector: + dask.org/cluster-name: tea-verify + dask.org/component: scheduler + ports: + - {name: tcp-comm, port: 8786, targetPort: tcp-comm} + - {name: http-dashboard, port: 8787, targetPort: http-dashboard} diff --git a/deploy/verify.sh b/deploy/verify.sh new file mode 100755 index 0000000..1e6c257 --- /dev/null +++ b/deploy/verify.sh @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +# Build, push and run the tea-verify DaskJob for the current commit. +# deploy/verify.sh build + push + apply +# deploy/verify.sh --logs follow the job pod's log +# deploy/verify.sh --delete remove the DaskJob +set -euo pipefail +cd "$(dirname "$0")/.." +REG=192.168.20.18:5000 +case "${1:-}" in + --logs) pod=$(kubectl get pods -l dask.org/cluster-name=tea-verify,dask.org/component=job -o name | head -1) + exec kubectl logs -f "${pod:-job/tea-verify}" ;; + --delete) exec kubectl delete daskjob tea-verify --ignore-not-found ;; +esac +if [ -n "$(git status --porcelain --ignore-submodules=none)" ]; then + echo "uncommitted changes: commit first, so the image tag is a real commit" >&2; exit 1 +fi +C=$(git rev-parse --short HEAD) +docker build -f deploy/Dockerfile.verify --build-arg TEA_COMMIT="$C" -t "$REG/tea-verify:$C" . +docker push "$REG/tea-verify:$C" +kubectl delete daskjob tea-verify --ignore-not-found +sed "s/tea-verify:COMMIT/tea-verify:$C/g" deploy/dask-verify.yaml | kubectl apply -f - +echo "applied tea-verify:$C — follow with: deploy/verify.sh --logs" diff --git a/src/tea_modulo/serving/__init__.py b/src/tea_modulo/serving/__init__.py new file mode 100644 index 0000000..6bc730e --- /dev/null +++ b/src/tea_modulo/serving/__init__.py @@ -0,0 +1,15 @@ +""" +Plans and biomarkers as MLflow models, behind a privacy guard. + + from tea_modulo.serving import log_plan, log_biomarker, load_plan, load_biomarker +""" + +from tea_modulo.serving.models import ( + load_biomarker, + load_plan, + log_biomarker, + log_plan, +) +from tea_modulo.serving.privacy import Forbidden + +__all__ = ["log_plan", "log_biomarker", "load_plan", "load_biomarker", "Forbidden"] diff --git a/src/tea_modulo/serving/model_code/biomarker_model.py b/src/tea_modulo/serving/model_code/biomarker_model.py new file mode 100644 index 0000000..a658e46 --- /dev/null +++ b/src/tea_modulo/serving/model_code/biomarker_model.py @@ -0,0 +1,30 @@ +""" +MLflow "model from code" for a trained tea_modulo biomarker. Standalone on +purpose: it imports nothing from tea_modulo at module level, so a logged model +needs only its own module's code (shipped in code_paths) and `contracts`. + +predict(df with the feature columns + age_months) -> deviation table +(feature, value, age_months, outside, z, baseline). +""" + +import importlib +import json +from pathlib import Path + +import mlflow +import pandas as pd + + +class BiomarkerModel(mlflow.pyfunc.PythonModel): + def load_context(self, context): + folder = Path(context.artifacts["module"]) + cfg = json.loads((folder / "module.json").read_text()) + mod, _, attr = cfg["class"].partition(":") + self.module = getattr(importlib.import_module(mod), attr).load(folder) + self.config = cfg + + def predict(self, context, model_input, params=None): + return self.module.predict(pd.DataFrame(model_input)) + + +mlflow.models.set_model(BiomarkerModel()) diff --git a/src/tea_modulo/serving/model_code/plan_model.py b/src/tea_modulo/serving/model_code/plan_model.py new file mode 100644 index 0000000..1404675 --- /dev/null +++ b/src/tea_modulo/serving/model_code/plan_model.py @@ -0,0 +1,22 @@ +""" +MLflow "model from code" for a preprocessing plan. Standalone: the plan +(plan.json) is the artifact; predict() returns it, one row per input row. +""" + +import json +from pathlib import Path + +import mlflow +import pandas as pd + + +class PlanModel(mlflow.pyfunc.PythonModel): + def load_context(self, context): + self.plan = json.loads(Path(context.artifacts["plan"]).read_text(encoding="utf-8")) + + def predict(self, context, model_input, params=None): + n = max(1, len(model_input)) + return pd.DataFrame({"plan": [json.dumps(self.plan)] * n, "hash": [self.plan.get("hash", "")] * n}) + + +mlflow.models.set_model(PlanModel()) diff --git a/src/tea_modulo/serving/models.py b/src/tea_modulo/serving/models.py new file mode 100644 index 0000000..95fe550 --- /dev/null +++ b/src/tea_modulo/serving/models.py @@ -0,0 +1,138 @@ +""" +Plans and biomarkers as MLflow pyfunc models. + + pv = log_plan(plan, registered_name="tea-plan-director-cluster") + bv = log_biomarker(rhythm, plan_uri=f"models:/tea-plan-director-cluster/{pv.version}", + registered_name="tea-bio-posterior-rhythm") + plan_dict = load_plan("models:/tea-plan-director-cluster/1") + rhythm = load_biomarker("models:/tea-bio-posterior-rhythm/3") + mlflow.pyfunc.load_model(uri).predict(df) # df: features + age_months + +A biomarker model carries only its own module's code plus `contracts` +(code_paths), its saved state (baseline.json, params.json) and a copy of the +plan it was trained with. Tags: plan_uri, plan_hash, module version, impl, +CONTRACT_VERSION. Nothing is logged before the privacy checks pass. +""" + +from __future__ import annotations + +import json +import shutil +import tempfile +from pathlib import Path + +import mlflow +import pandas as pd + +from tea_modulo.contracts import CONTRACT_VERSION + +from . import privacy + +PKG_ROOT = Path(__file__).resolve().parents[1] # .../tea_modulo + + +MODEL_CODE = Path(__file__).with_name("model_code") + + +def _stage_code(module_pkg: str, dest: Path) -> Path: + """A copy of tea_modulo with only `contracts` and the module's package (+ parent __init__s).""" + root = dest / "tea_modulo" + (root).mkdir(parents=True) + shutil.copy(PKG_ROOT / "__init__.py", root / "__init__.py") + shutil.copytree(PKG_ROOT / "contracts", root / "contracts", + ignore=shutil.ignore_patterns("__pycache__")) + parts = module_pkg.split(".")[1:] # drop "tea_modulo" + cur_src, cur_dst = PKG_ROOT, root + for p in parts[:-1]: + cur_src, cur_dst = cur_src / p, cur_dst / p + cur_dst.mkdir(exist_ok=True) + shutil.copy(cur_src / "__init__.py", cur_dst / "__init__.py") + shutil.copytree(PKG_ROOT.joinpath(*parts), root.joinpath(*parts), + ignore=shutil.ignore_patterns("__pycache__"), dirs_exist_ok=True) + return root + + +def _package_of(module) -> str: + """'tea_modulo.legacy.biomarkers.posterior_rhythm' for a module object.""" + name = type(module).__module__ + return name.rsplit(".", 1)[0] if name.endswith(".api") else name + + +def log_plan(plan, *, registered_name: str | None = None, run_name: str | None = None, + experiment: str = "tea-modulo-plans"): + d = plan.to_dict() if hasattr(plan, "to_dict") else dict(plan) + d.pop("bads", None) + d.pop("reasons", None) + privacy.check_text(json.dumps(d), registered_name or "", run_name or "") + mlflow.set_experiment(experiment) + with tempfile.TemporaryDirectory() as tmp, mlflow.start_run(run_name=run_name or d.get("name")): + mlflow.log_dict(d, "plan/plan.json") + mlflow.log_params({"plan.name": d.get("name"), "plan.hash": d.get("hash"), + "plan.line_hz": d.get("line_hz"), + **{f"step.{s['kind']}.{k}": v for s in d.get("steps", []) + for k, v in s.get("params", {}).items()}, + "variants": ",".join(v["name"] for v in d.get("variants", []))}) + mlflow.set_tags({"kind": "plan", "plan_hash": d.get("hash", ""), + "contract_version": CONTRACT_VERSION}) + f = Path(tmp) / "plan.json" + f.write_text(json.dumps(d, indent=1), encoding="utf-8") + info = mlflow.pyfunc.log_model(name="plan", python_model=str(MODEL_CODE / "plan_model.py"), + artifacts={"plan": str(f)}, + code_paths=[str(_stage_code("tea_modulo.contracts", Path(tmp) / "code"))], + input_example=pd.DataFrame({"edf_path": ["study.edf"]}), + registered_model_name=registered_name) + return _version(info, registered_name) + + +def log_biomarker(module, *, plan_uri: str = "", plan: dict | None = None, + registered_name: str | None = None, run_name: str | None = None, + n_reference: int | None = None, experiment: str = "tea-modulo-biomarkers", + input_example: pd.DataFrame | None = None): + privacy.check_text(registered_name or "", run_name or "", plan_uri) + if plan is None and plan_uri: + plan = load_plan(plan_uri) + pkg = _package_of(module) + mlflow.set_experiment(experiment) + with tempfile.TemporaryDirectory() as tmp: + state = Path(tmp) / "module" + state.mkdir() + module.save(state) + (state / "module.json").write_text(json.dumps( + {"class": f"{type(module).__module__}:{type(module).__name__}", "name": module.name, + "version": module.version, "impl": getattr(module, "impl", "modern")})) + if plan is not None: + (state / "plan.json").write_text(json.dumps(plan, indent=1)) + privacy.check_files(state) + privacy.check_group(state, n_reference) + if input_example is None: + input_example = pd.DataFrame({**{f: [1.0] for f in module.features}, "age_months": [24.0]}) + code = _stage_code(pkg, Path(tmp) / "code") + with mlflow.start_run(run_name=run_name or module.name): + mlflow.set_tags({"kind": "biomarker", "module": module.name, "module_version": module.version, + "impl": getattr(module, "impl", "modern"), "plan_uri": plan_uri, + "plan_hash": (plan or {}).get("hash", ""), + "contract_version": CONTRACT_VERSION}) + info = mlflow.pyfunc.log_model(name="biomarker", python_model=str(MODEL_CODE / "biomarker_model.py"), + artifacts={"module": str(state)}, code_paths=[str(code)], + input_example=input_example, + registered_model_name=registered_name) + return _version(info, registered_name) + + +def load_plan(uri: str) -> dict: + """The plan dict of a plan model (models:/name/version or runs:/...).""" + m = mlflow.pyfunc.load_model(uri) + return m.unwrap_python_model().plan + + +def load_biomarker(uri: str): + """The trained biomarker module object of a biomarker model.""" + return mlflow.pyfunc.load_model(uri).unwrap_python_model().module + + +def _version(info, registered_name): + if registered_name: + client = mlflow.MlflowClient() + vs = client.search_model_versions(f"name='{registered_name}'") + return max(vs, key=lambda v: int(v.version)) + return info diff --git a/src/tea_modulo/serving/privacy.py b/src/tea_modulo/serving/privacy.py new file mode 100644 index 0000000..2e90fef --- /dev/null +++ b/src/tea_modulo/serving/privacy.py @@ -0,0 +1,67 @@ +""" +What may leave the computer for MLflow (rule carried over from +biomarcadores-tea/biomarcadores/registro.py, user decision 8 Oct 2026): +plans, group-level baseline parameters, code versions. Never per-child +values, study codes (eeg_###), dates or local paths, and never a group +smaller than MIN_GROUP children. +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path + +# registro._PROHIBIDO, plus POSIX home paths +FORBIDDEN = re.compile(r"eeg_\d+|\d{4}-\d{2}-\d{2}|[A-Za-z]:\\|/Users/|/home/|Escritorio", re.I) +MIN_GROUP = 5 + + +class Forbidden(ValueError): + """Something that must not leave the computer was about to be logged.""" + + +def check_text(*texts): + for t in texts: + m = FORBIDDEN.search(str(t)) + if m: + raise Forbidden(f"text with a study code, date or path ({m.group(0)[:12]!r}…) " + f"cannot go to MLflow") + + +def check_files(folder: Path): + """Every text file a module saved, before it is logged as an artifact.""" + for p in Path(folder).rglob("*"): + if p.is_file(): + try: + check_text(p.read_text(encoding="utf-8")) + except UnicodeDecodeError: + raise Forbidden(f"{p.name}: binary artifacts are not allowed (only JSON / text)") from None + + +def group_size(baseline: dict | None) -> float | None: + """Reference group size of a baseline dict, if its format is known.""" + if not baseline: + return None + st = baseline.get("state") + if isinstance(st, dict) and "n" in st: + return float(st["n"]) + curva = baseline.get("curva") + if isinstance(curva, dict) and curva.get("n_efectivo"): + vals = [v for v in curva["n_efectivo"] if v is not None] + return max(vals) if vals else 0.0 # Kish n_eff <= n + return None + + +def check_group(folder: Path, n_reference: int | None = None): + """Refuse a trained baseline from fewer than MIN_GROUP children.""" + n = n_reference + if n is None: + f = Path(folder) / "baseline.json" + if f.exists(): + n = group_size(json.loads(f.read_text(encoding="utf-8"))) + if n is None: + raise Forbidden("cannot tell the reference group size: pass n_reference") + if n < MIN_GROUP: + raise Forbidden(f"baseline from {n:g} children: fewer than {MIN_GROUP} would almost " + f"show each child's values") diff --git a/src/tea_modulo/verify/__init__.py b/src/tea_modulo/verify/__init__.py new file mode 100644 index 0000000..a1a3a93 --- /dev/null +++ b/src/tea_modulo/verify/__init__.py @@ -0,0 +1 @@ +"""Verification commands run on the team's cluster (HK1K only).""" diff --git a/src/tea_modulo/verify/__main__.py b/src/tea_modulo/verify/__main__.py new file mode 100644 index 0000000..2012071 --- /dev/null +++ b/src/tea_modulo/verify/__main__.py @@ -0,0 +1,17 @@ +"""python -m tea_modulo.verify hk1k --out processed/usuarios//tea-verify/""" + +import sys + +from tea_modulo.verify import hk1k + + +def main(argv=None) -> int: + argv = list(sys.argv[1:] if argv is None else argv) + if not argv or argv[0] != "hk1k": + print(__doc__, file=sys.stderr) + return 2 + return hk1k.main(argv[1:]) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/tea_modulo/verify/hk1k.py b/src/tea_modulo/verify/hk1k.py new file mode 100644 index 0000000..2975ea4 --- /dev/null +++ b/src/tea_modulo/verify/hk1k.py @@ -0,0 +1,186 @@ +""" +HK1K verification on the team's cluster (public data only). + + python -m tea_modulo.verify hk1k --out processed/usuarios/alberto/tea-verify/ [--limit 40] + +1. Lists the HK1K EDFs and ages (anon_codex_age_sex.csv) in a worker task. +2. Runs the pipeline (legacy, and modern when registered) on every study with + age in --ages (default 16-36 months) through the remote Dask scheduler, + mains line 50 Hz (Helsinki). +3. Checks that the remote run equals a sequential run of the same first + studies inside one task (same code path, one worker, plain loop). +4. Compares the posterior rhythm by HK1K age group with the reference table + (normas/referencia_hk1k.csv, ritmo_posterior / vigilia), when present. +5. Prints a JSON summary and writes it to S3 under --out (worker task). + +Only group numbers leave the tasks: counts, medians, percentiles; groups with +fewer than 5 children are suppressed. Input paths other than raw/eeg-helsinki/ +are refused. +""" + +from __future__ import annotations + +import json +import math +import os +import sys +from pathlib import Path + +HK1K = "raw/eeg-helsinki/" +MIN_GROUP = 5 +REF = Path(__file__).resolve().parents[3] / "biomarcadores-tea" / "normas" / "referencia_hk1k.csv" + + +def guard(path: str) -> str: + p = str(path) + p = p[len("s3://"):] if p.startswith("s3://") else p + if not p.startswith(HK1K) or ".." in p: + raise PermissionError(f"verification reads only {HK1K}; refused another prefix") + return p + + +def list_hk1k(base: str = HK1K) -> list[tuple[str, float]]: + """In a task: (s3 path, age in months) of each HK1K EDF with an age.""" + import pandas as pd + + from tea_modulo.pipeline.storage import s3 + fs = s3() + paths = fs.find(guard(base)) + tables = [r for r in paths if r.endswith("anon_codex_age_sex.csv")] + if not tables: + raise FileNotFoundError("anon_codex_age_sex.csv not found under the HK1K prefix") + with fs.open(tables[0], "rb") as f: + codex = pd.read_csv(f) + codex.columns = ["archivo", "edad_anos", "sexo"] + edfs = {Path(r).name: r for r in paths if r.endswith(".edf")} + return [("s3://" + guard(edfs[r.archivo]), round(float(r.edad_anos) * 12, 1)) + for r in codex.itertuples() if r.archivo in edfs] + + +def write_summary(text: str, out_prefix: str, name: str) -> str: + """In a task: write the summary JSON under processed/usuarios/... (never raw/ or eeg-edf).""" + from tea_modulo.pipeline.storage import s3 + if not out_prefix.startswith("processed/usuarios/"): + raise PermissionError("summaries go only under processed/usuarios//") + key = out_prefix.rstrip("/") + "/" + name + with s3().open(key, "w") as f: + f.write(text) + return key + + +def sequential(fn, argsets): + """A plain loop inside one task (the reference for the remote run).""" + return [fn(*a) for a in argsets] + + +def group_stats(values) -> dict | None: + import numpy as np + v = np.asarray([x for x in values if x is not None and math.isfinite(x)], float) + if len(v) < MIN_GROUP: + return {"n": int(len(v)), "suppressed": True} + return {"n": int(len(v)), "p5": round(float(np.percentile(v, 5)), 3), + "median": round(float(np.median(v)), 3), "p95": round(float(np.percentile(v, 95)), 3)} + + +def _versions(client) -> dict: + v = client.get_versions(check=False) + return {k: v["scheduler"]["packages"].get(k) for k in ("python", "dask", "distributed")} + + +def main(argv=None) -> int: + import argparse + + import pandas as pd + from distributed import Client + + from tea_modulo.pipeline import Pipeline, run_study + from tea_modulo.pipeline.dask_runner import scheduler_address + from tea_modulo.preprocessing import DIRECTOR_CLUSTER + + ap = argparse.ArgumentParser(prog="python -m tea_modulo.verify hk1k") + ap.add_argument("--out", required=True) + ap.add_argument("--ages", nargs=2, type=float, default=(16.0, 36.0)) + ap.add_argument("--limit", type=int, default=None) + ap.add_argument("--check-n", type=int, default=4, help="studies re-run sequentially for the equality check") + ap.add_argument("--impl", nargs="+", default=["legacy", "modern"]) + args = ap.parse_args(argv) + + addr = scheduler_address() + if not addr: + print("no DASK_SCHEDULER / DASK_SCHEDULER_ADDRESS: run this inside the tea-verify DaskJob", + file=sys.stderr) + return 2 + plan = {**DIRECTOR_CLUSTER.to_dict(), "line_hz": 50.0} + summary = {"plan_hash": plan["hash"], "line_hz": 50.0, "ages": list(args.ages), "impl": {}, + "commit": os.environ.get("TEA_COMMIT", "")} + + with Client(addr, direct_to_workers=False) as client: + summary["scheduler"] = _versions(client) + items = client.submit(list_hk1k, pure=False, priority=-10).result() + items = [(p, a) for p, a in items if args.ages[0] <= a <= args.ages[1]] + items.sort() + if args.limit: + items = items[: args.limit] + summary["n_listed"] = len(items) + for impl in args.impl: + try: + pipe = Pipeline.default(impl=impl) + except Exception as e: # noqa: BLE001 + summary["impl"][impl] = {"skipped": f"{type(e).__name__}: {e}"[:200]} + continue + if "posterior_rhythm" not in pipe.modules: + summary["impl"][impl] = {"skipped": "posterior_rhythm not registered"} + continue + paths, ages = [p for p, _ in items], [a for _, a in items] + remote = Pipeline(pipe.modules, impl="modern").map( + paths, plan=plan, ages_months=ages, biomarkers=("posterior_rhythm",), + cluster="remote", line_hz=50.0) + # equality: the first studies again, sequentially, in one task + from tea_modulo.pipeline.run_study import order_for + mods = {n: pipe.modules[n] for n in ("validation", "preprocessing", + *order_for(["posterior_rhythm"], pipe.modules), + "posterior_rhythm")} + order = tuple(order_for(["posterior_rhythm"], pipe.modules)) + k = min(args.check_n, len(paths)) + argsets = [(i, paths[i], ages[i], plan, mods, order, ("posterior_rhythm",), 50.0) + for i in range(k)] + seq = pd.DataFrame(client.submit(sequential, run_study, argsets, pure=False, + priority=-10).result()) + cols = [c for c in seq.columns if c not in ("seconds",)] + a = remote[remote.key < k][cols].reset_index(drop=True) + b = seq[cols].reset_index(drop=True) + equal = bool(a.equals(b) or a.fillna(-999).astype(str).equals(b.fillna(-999).astype(str))) + ok = remote[(remote.valid == 1) & (remote.error == "")] + info = {"n": int(len(remote)), "valid": int((remote.valid == 1).sum()), + "not_valid": int((remote.valid == 0).sum()), + "errors": int((remote.error != "").sum()), + "error_types": remote.loc[remote.error != "", "error"].str.split(":").str[0] + .value_counts().to_dict(), + "remote_equals_sequential": equal, "checked": k, + "seconds_median": float(remote.seconds.median()) if len(remote) else None, + "posterior_rhythm_hz": group_stats(ok.get("posterior_rhythm_hz", [])), + "by_age_group": {}} + for lo, hi in ((12, 24), (24, 36)): + g = ok[(ok.age_months >= lo) & (ok.age_months < hi)] + info["by_age_group"][f"{lo}-{hi}"] = group_stats(g.get("posterior_rhythm_hz", [])) + summary["impl"][impl] = info + summary["reference"] = _reference() + text = json.dumps(summary, indent=1, default=str) + print(text) + key = client.submit(write_summary, text, args.out, + f"summary_{summary['commit'] or 'local'}.json", pure=False).result() + print(f"summary written to s3://{key}", file=sys.stderr) + bad = [i for i, v in summary["impl"].items() if isinstance(v, dict) + and v.get("remote_equals_sequential") is False] + return 1 if bad else 0 + + +def _reference() -> dict: + """HK1K reference rhythm (E15) for the age groups the run covers, if the table is here.""" + if not REF.exists(): + return {"available": False} + import pandas as pd + r = pd.read_csv(REF, encoding="utf-8-sig") + r = r[(r.biomarcador == "ritmo_posterior") & (r.estado == "vigilia")] + return {"available": True, "ritmo_posterior_vigilia": r[["grupo_edad_anos", "n", "p5", "mediana", "p95"]] + .to_dict("records")} diff --git a/tests/test_boundaries.py b/tests/test_boundaries.py index 4b07514..77a3014 100644 --- a/tests/test_boundaries.py +++ b/tests/test_boundaries.py @@ -90,6 +90,8 @@ def test_imports_respect_boundaries(path): if top == "tea_modulo": if unit and unit[0] == "export": ok = mod == own or mod.startswith(own + ".") + elif unit == ("verify",): + ok = True # an application: it wires everything, like tests do elif not unit: ok = mod in ("tea_modulo", "tea_modulo.contracts") or mod.startswith("tea_modulo.contracts.") else: diff --git a/tests/test_serving.py b/tests/test_serving.py new file mode 100644 index 0000000..0701d77 --- /dev/null +++ b/tests/test_serving.py @@ -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") diff --git a/tests/test_verify.py b/tests/test_verify.py new file mode 100644 index 0000000..dd730e4 --- /dev/null +++ b/tests/test_verify.py @@ -0,0 +1,27 @@ +"""The HK1K verification command refuses everything but the public HK1K prefix.""" + +import pytest + +from tea_modulo.verify import hk1k + + +@pytest.mark.parametrize("p", ["raw/eeg-data/eeg_001/x.edf", "processed/eeg-edf/eeg_001/eeg_001.edf", + "raw/2021-204/a.edf", "raw/eeg-helsinki/../eeg-data/x.edf"]) +def test_guard_refuses_other_prefixes(p): + with pytest.raises(PermissionError): + hk1k.guard(p) + + +def test_guard_accepts_hk1k(): + assert hk1k.guard("s3://raw/eeg-helsinki/sub-1/x.edf") == "raw/eeg-helsinki/sub-1/x.edf" + + +def test_group_stats_suppresses_small_groups(): + assert hk1k.group_stats([1.0, 2.0, 3.0]) == {"n": 3, "suppressed": True} + s = hk1k.group_stats([6.0, 6.5, 7.0, 7.5, 8.0]) + assert s["n"] == 5 and s["median"] == 7.0 + + +def test_summary_writes_only_to_user_area(): + with pytest.raises(PermissionError): + hk1k.write_summary("{}", "processed/eeg-edf/", "x.json")