Files
models/tests/test_tea_job.py
T
alberto cc95054a96 The tea_eeg job: analyse, score the age curves, relate ADOS-2, rebuild gold; a sensor starts it after an ingest
Analysis and the reference cohort's measuring run on execution.map; relate is the
Phase 2 seam. A LocalCluster starts inside a multiprocess Dagster step (checked on a
real run), so the ops keep the default executor.
2026-11-27 18:02:28 -06:00

140 lines
5.1 KiB
Python

"""The tea_eeg job's graph, its sensor and the config classes, in process (no EEG data)."""
import dagster as dg
import pytest
from pydantic import ValidationError
from models import definitions
from models.definitions import (
ExecutionConfig,
ScopeConfig,
after_ingest,
defs,
tea_eeg,
tea_eeg_after_ingest,
)
from models.tea import jobs as tea_jobs
from persistance import cluster, eeg
def _config(scope: dict) -> dict:
return {"ops": {"tea_analyze_studies": {"config": {
"scope": scope, "execution": {"mode": "sync"}}}}} # fmt: skip
@pytest.fixture
def calls(monkeypatch):
log = []
def analyze(scope=None, *, rebuild_gold=True):
log.append(("analyze", scope, rebuild_gold))
return 2
monkeypatch.setattr(tea_jobs, "analyze", analyze)
monkeypatch.setattr(tea_jobs, "score_curves", lambda: log.append(("score",)) or {"c": 3})
monkeypatch.setattr(tea_jobs, "relate", lambda: log.append(("relate",)))
monkeypatch.setattr(definitions.silver, "build", lambda sel: log.append(("build", sel)))
return log
def test_tea_eeg_runs_the_four_steps_in_order(calls):
result = tea_eeg.execute_in_process(
instance=dg.DagsterInstance.ephemeral(), run_config=_config({"mode": "first_n", "n": 2})
)
assert result.success
assert [c[0] for c in calls] == ["analyze", "score", "relate", "build"]
assert calls[0][1].n == 2 and calls[0][2] is False
assert calls[3][1] == tea_jobs.GOLD_SELECT
assert result.output_for_node("tea_analyze_studies") == {"analysed": 2}
assert result.output_for_node("tea_score_curves") == {"scored": {"c": 3}}
assert result.output_for_node("tea_relate_ados2") == {"ados2_association": None}
assert result.output_for_node("tea_build_gold") == {"built": tea_jobs.GOLD_SELECT}
def test_a_failing_analysis_stops_the_graph(calls, monkeypatch):
def boom(scope=None, *, rebuild_gold=True):
raise RuntimeError("no signal")
monkeypatch.setattr(tea_jobs, "analyze", boom)
result = tea_eeg.execute_in_process(
instance=dg.DagsterInstance.ephemeral(),
run_config=_config({"mode": "pending"}),
raise_on_error=False,
)
assert not result.success
assert calls == []
def test_a_bad_scope_fails_before_any_work(calls):
result = tea_eeg.execute_in_process(
instance=dg.DagsterInstance.ephemeral(),
run_config=_config({"mode": "first_n"}),
raise_on_error=False,
)
assert not result.success
assert calls == []
failure = next(e for e in result.all_events if e.is_step_failure)
assert "first_n needs n" in str(failure.event_specific_data.error)
def test_scope_validation():
assert eeg.Scope().mode == "pending"
assert eeg.Scope(mode="first_n", n=3).n == 3
good = "p1|2024-05-06"
assert eeg.Scope(mode="ids", ids=[good]).ids == [good]
bad = [
{"mode": "first_n"},
{"mode": "first_n", "n": 0},
{"mode": "first_n", "n": 2, "ids": [good]},
{"mode": "ids"},
{"mode": "ids", "ids": [good], "n": 1},
{"mode": "ids", "ids": ["nobar"]},
{"mode": "ids", "ids": ["p|2024-5-6"]},
{"mode": "ids", "ids": ["|2024-05-06"]},
{"mode": "ids", "ids": [f"p{i}|2024-05-06" for i in range(501)]},
{"mode": "pending", "n": 1},
{"mode": "pending", "ids": [good]},
{"mode": "other"},
{"extra": 1},
]
for kwargs in bad:
with pytest.raises(ValidationError):
eeg.Scope(**kwargs)
assert len(eeg.Scope(mode="ids", ids=[f"p{i}|2024-05-06" for i in range(500)]).ids) == 500
with pytest.raises(ValidationError, match="first_n needs n"):
ScopeConfig(mode="first_n").model()
def test_config_mirrors_match_the_shared_models():
for config, shared in ((ScopeConfig, eeg.Scope), (ExecutionConfig, cluster.Execution)):
assert list(config.model_fields) == list(shared.model_fields)
for name, field in shared.model_fields.items():
assert config.model_fields[name].default == field.default, name
# a wrong value still reaches the shared model's validation
with pytest.raises(ValidationError):
ExecutionConfig(mode="cloud").model()
with pytest.raises(ValidationError):
ScopeConfig(mode="all").model()
def test_after_ingest_requests_a_run_only_with_pending_eegs():
skip = after_ingest("r1", lambda: False)
assert isinstance(skip, dg.SkipReason)
request = after_ingest("r1", lambda: True)
assert isinstance(request, dg.RunRequest)
assert request.run_key == "after-ingest-r1"
scope = request.run_config["ops"]["tea_analyze_studies"]["config"]["scope"]
assert scope == {"mode": "pending"}
assert request.tags["domain"] == "tea" and request.tags["triggered_by"] == "r1"
def test_definitions_load_with_every_job_and_the_sensor():
dg.Definitions.validate_loadable(defs)
names = {j.name for j in defs.jobs}
assert names >= {"ingest", "train", "score", "analyze", "tea_eeg"}
assert tea_eeg_after_ingest.default_status == dg.DefaultSensorStatus.RUNNING
def test_relate_is_a_no_op_until_phase_2():
assert tea_jobs.relate() is None