Files
tea/tests/test_boundaries.py
T
AlbertoPMDM 4956f36d80 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.
2026-11-18 20:24:03 -06:00

115 lines
4.3 KiB
Python

"""
The boundary rule: a module imports only `tea_modulo.contracts`, the standard
library and its approved third-party libraries. It never imports another
`tea_modulo` module, so any module can be replaced without touching the rest.
"""
from __future__ import annotations
import ast
import sys
from pathlib import Path
import pytest
SRC = Path(__file__).resolve().parents[1] / "src" / "tea_modulo"
# Approved third-party libraries (top-level import names).
BASE = {"numpy", "scipy", "pandas", "mne", "sklearn", "antropy", "fooof", "yasa",
"meegkit", "edfio"}
LEGACY = {"numpy", "scipy", "pandas", "sklearn"}
EXTRA = {
"validation": {"fhir"},
"serving": {"mlflow"},
"pipeline": {"dask", "distributed", "s3fs", "fsspec", "psutil"},
"verify": {"dask", "distributed", "s3fs", "fsspec"},
"export": set(),
}
# lazy imports inside the director's figure / HDF5 helpers (never reached by legacy)
DIRECTOR_LAZY = {"matplotlib", "h5py"}
# files allowed to touch MNE / FHIR inside legacy (the contract adapters)
LEGACY_ADAPTERS = {"_adapter.py", "fhir.py", "api.py", "__init__.py"}
def unit_of(path: Path) -> tuple[str, ...]:
"""The replaceable unit a file belongs to, as a path tuple under tea_modulo."""
rel = path.relative_to(SRC).parts
if rel[0] == "legacy":
rest = rel[1:]
if len(rest) >= 2 and rest[0] in ("processes", "biomarkers") and len(rest) > 2:
return ("legacy", rest[0], rest[1])
if len(rest) >= 2:
return ("legacy", rest[0])
return ("legacy",)
if rel[0] in ("processes", "biomarkers") and len(rel) > 2:
return (rel[0], rel[1])
if len(rel) == 1:
return ()
return (rel[0],)
def imports_of(path: Path):
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
pkg = list(path.relative_to(SRC.parent).with_suffix("").parts)
if path.name != "__init__.py":
pkg = pkg[:-1]
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for a in node.names:
yield a.name, node.lineno
elif isinstance(node, ast.ImportFrom):
if node.level:
base = pkg[: len(pkg) - (node.level - 1)]
mod = ".".join(base + ([node.module] if node.module else []))
yield mod, node.lineno
else:
yield node.module or "", node.lineno
def allowed_third_party(unit: tuple[str, ...], fname: str) -> set[str]:
if not unit:
return set()
if unit[0] == "legacy":
extra = {"mne", "fhir", "edfio"} if fname in LEGACY_ADAPTERS else set()
return LEGACY | extra | DIRECTOR_LAZY
if unit[0] == "export":
return {"numpy", "edfio"}
return BASE | EXTRA.get(unit[0], set())
FILES = sorted(p for p in SRC.rglob("*.py"))
@pytest.mark.parametrize("path", FILES, ids=[str(p.relative_to(SRC)) for p in FILES])
def test_imports_respect_boundaries(path):
unit = unit_of(path)
own = "tea_modulo." + ".".join(unit) if unit else "tea_modulo"
bad = []
for mod, line in imports_of(path):
top = mod.split(".")[0]
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:
ok = (mod == "tea_modulo.contracts" or mod.startswith("tea_modulo.contracts.")
or mod == own or mod.startswith(own + "."))
if unit == ("contracts",):
ok = mod.startswith("tea_modulo.contracts")
elif top in sys.stdlib_module_names or top == "__future__":
ok = True
else:
ok = top in allowed_third_party(unit, path.name)
if not ok:
bad.append(f"line {line}: {mod}")
assert not bad, f"{path.relative_to(SRC)} ({'.'.join(unit) or 'root'}) breaks the boundary: " + "; ".join(bad)
def test_legacy_never_imports_dask():
for p in (SRC / "legacy").rglob("*.py") if (SRC / "legacy").exists() else []:
for mod, line in imports_of(p):
assert mod.split(".")[0] not in ("dask", "distributed"), f"{p}:{line} imports {mod}"