Files
tea/tests/test_pipeline.py
T
AlbertoPMDM 038836a701 pipeline: module registry, run_study, Dask runner and legacy serial executor
- Modules are looked up by name through entry points (tea_modulo.modules,
  tea_modulo.legacy_modules) and checked against their protocol.
- run_study: one EDF to one small row (key, verdict, features, plan hash,
  module versions; failures become error rows with paths removed).
- Modern batches are Dask-native: a dask.delayed graph under
  annotate(priority=-10, retries=1), run on cluster='remote'|'local'|'sync'|
  'auto'. Remote: Client(direct_to_workers=False), get_versions(check=True),
  only close(). Local: processes, 1 thread, BLAS threads 1, closed by us.
- Legacy batches: tea_modulo.legacy.executor.run_serial, a plain loop.
- storage.local_copy fetches s3:// objects to a temp file inside the task.

Tests: legacy loop, Dask sync and a 2-worker LocalCluster give the same
table; error rows; positive priority refused; remote never shut down.
2026-11-18 20:18:07 -06:00

124 lines
4.6 KiB
Python

"""Pipeline: module lookup, dependency order, executors and cluster rules."""
from __future__ import annotations
import os
from pathlib import Path
import pandas as pd
import pytest
from synth_edf import SCALP, make_edf
from tea_modulo.pipeline import NotValid, Pipeline, order_for
from tea_modulo.pipeline import dask_runner
from tea_modulo.preprocessing import DIRECTOR_CLUSTER
BIOS = ("posterior_rhythm",)
@pytest.fixture(scope="module")
def edfs(tmp_path_factory):
d = tmp_path_factory.mktemp("pipe")
good = [make_edf(d / f"s{i}.edf", minutes=3, seed=i, rhythm_hz=6.5 + 0.5 * i) for i in range(2)]
bad = make_edf(d / "bad.edf", minutes=3, bad={"flat": SCALP[:9]}) # 10 usable < 12
broken = d / "broken.edf"
broken.write_bytes(b"not an edf at all")
return good, bad, broken
def _cmp(a: pd.DataFrame, b: pd.DataFrame):
cols = [c for c in a.columns if c != "seconds"]
pd.testing.assert_frame_equal(a[cols].reset_index(drop=True), b[cols].reset_index(drop=True))
def test_order_is_topological():
class M:
def __init__(self, *req):
self.requires = req
mods = {"a": M(), "b": M("a"), "c": M("b", "a"), "bio": M("c")}
assert order_for(["bio"], mods) == ["a", "b", "c"]
mods["a"] = M("c")
with pytest.raises(ValueError, match="cycle"):
order_for(["bio"], mods)
def test_legacy_pipeline_is_registered():
pipe = Pipeline.default(impl="legacy")
assert {"validation", "preprocessing", "annotation_mask", "sleep_state", "posterior_rhythm"} <= set(pipe.modules)
assert pipe.biomarker_names() == ["posterior_rhythm"]
def test_legacy_loop_rows_and_errors(edfs):
good, bad, broken = edfs
pipe = Pipeline.default(impl="legacy")
t = pipe.map([*good, bad, broken], plan=DIRECTOR_CLUSTER, ages_months=[24, 30, 26, 28],
biomarkers=BIOS)
assert list(t.key) == [0, 1, 2, 3]
assert t.valid.tolist()[:3] == [1, 1, 0]
assert t.posterior_rhythm_hz.iloc[0] == pytest.approx(6.5, abs=0.3)
assert t.posterior_rhythm_hz.iloc[1] == pytest.approx(7.0, abs=0.3)
assert "electrodos de cuero" in t.reasons.iloc[2]
assert t.error.iloc[3] and "/" not in t.error.iloc[3] # no path in errors
for c in ("path", "file", "name"):
assert c not in t.columns
def test_dask_sync_and_local_equal_legacy_loop(edfs):
good, bad, _ = edfs
paths, ages = [*good, bad], [24, 30, 26]
legacy = Pipeline.default(impl="legacy")
ref = legacy.map(paths, plan=DIRECTOR_CLUSTER, ages_months=ages, biomarkers=BIOS)
modern = Pipeline(legacy.modules, impl="modern") # same modules, Dask runner
_cmp(modern.map(paths, plan=DIRECTOR_CLUSTER, ages_months=ages, biomarkers=BIOS, cluster="sync"), ref)
_cmp(modern.map(paths, plan=DIRECTOR_CLUSTER, ages_months=ages, biomarkers=BIOS,
cluster="local", n_workers=2, memory_per_worker="2GiB"), ref)
def test_positive_priority_refused():
with pytest.raises(ValueError, match="positive priorities"):
dask_runner.run(lambda: 1, [()], cluster="sync", priority=1)
def test_remote_client_is_closed_never_shut_down(monkeypatch):
calls = []
class FakeClient:
def __init__(self, addr, direct_to_workers=None):
calls.append(("init", addr, direct_to_workers))
def get_versions(self, check=False):
calls.append(("versions", check))
def close(self):
calls.append(("close",))
def shutdown(self):
calls.append(("shutdown",))
def restart(self):
calls.append(("restart",))
import distributed
monkeypatch.setattr(distributed, "Client", FakeClient)
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://scheduler:8786")
monkeypatch.delenv("DASK_SCHEDULER", raising=False)
with dask_runner.client_for("auto"):
pass
assert calls == [("init", "tcp://scheduler:8786", False), ("versions", True), ("close",)]
def test_study_raises_not_valid(edfs):
_, bad, _ = edfs
with pytest.raises(NotValid, match="electrodos de cuero"):
Pipeline.default(impl="legacy").study(bad, plan=DIRECTOR_CLUSTER, age_months=26)
@pytest.mark.cluster
@pytest.mark.skipif(not dask_runner.scheduler_address(), reason="no DASK_SCHEDULER")
def test_remote_equals_sync(edfs):
"""On the cluster job: the synthetic files are local to the job pod, so they are
read by the driver-side sync run only; the remote run uses the HK1K check instead
(tea_modulo.verify). Here we only check the remote scheduler answers a trivial graph."""
out = dask_runner.run(lambda x: x * 2, [(1,), (2,)], cluster="remote")
assert out == [2, 4]