Files
models/tests/test_tea_job.py
T
alberto d8445fcabf Cleanup of the TEA parity work: no prose in code, no hacks, everything in its place
1. No prose in code
- Remove parity-added comments and docstrings from TEA jobs, analysis and
  scoring helpers, execution, definitions, and tests. Keep base prose and
  Ruff and type-checker directives.

2. No hacks, no glued code
- Delegate both association cohort queries to persistance.eeg. Keep the
  predictor mapping and DataFrame shaping in the job, sharing biomarker
  codes and EEG study IDs with Core. Preserve column names and order, row
  selection, score filtering, and earliest fitting study.
- Use the existing MODELS registry for curve scoring in place of CURVES.
  Keep GOLD because the generic score job reads it.
- Catch lookup, database, and validation failures when loading a preview
  pipeline, preserving the existing warning. Keep execution-boundary
  exception handling for submitted tasks, telemetry and shutdown.
- Name the association test for the missing-champion case. Preserve its
  assertion and the other test assertions.

3. Everything in its place
- Keep SQL in Persistance, cohort shaping in models, and tests in their
  existing testpaths. Keep the association fits together with their
  shared design and result machinery.
2026-11-30 13:41:49 -06:00

222 lines
8.0 KiB
Python

import os
from pathlib import Path
import dagster as dg
import pytest
from pydantic import ValidationError
from sqlalchemy import inspect
from models import definitions, execution
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, destination, eeg
from synthetic import tea
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
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_returns_none_without_a_champion():
assert tea_jobs.relate() is None
@pytest.fixture
def synthetic_tea(platform, tmp_path, monkeypatch):
tea.build(tmp_path / "hospital_tea.db")
fixtures = Path(__file__).parents[2] / "tests" / "fixtures"
drawing = tmp_path / "pipeline.json"
drawing.write_text(
(fixtures / "pipelines" / "hospital_tea.json")
.read_text()
.replace("{hospital}", str(tmp_path))
)
platform.save("concept_maps", "hospital_tea", fixtures / "concept_maps" / "hospital_tea.json")
platform.save("pipelines", "tea", drawing)
platform.ingest("tea")
for name in ("PLATFORM_DATABASE_URL", "DLT_DATA_DIR", "EXECUTION_MODE"):
monkeypatch.setenv(name, platform.env[name])
monkeypatch.setattr(destination, "DATA_DIR", tmp_path)
destination.engine.cache_clear()
try:
yield platform
finally:
destination.engine.cache_clear()
@pytest.mark.parametrize("platform", ["sqlite"], indirect=True)
def test_tea_eeg_first_n_analyses_exactly_n(synthetic_tea):
table = "bronze.eeg_analysis"
with destination.engine().connect() as con:
has_analysis = inspect(con).has_table("eeg_analysis", schema="bronze")
before = synthetic_tea.count(table) if has_analysis else 0
pending = len(eeg.pending())
tea_jobs.analyze(eeg.Scope(mode="first_n", n=3), rebuild_gold=False)
assert synthetic_tea.count(table) == before + 3
assert len(eeg.pending()) == pending - 3
@pytest.mark.skipif(
not os.environ.get("DASK_TEST_SCHEDULER"), reason="DASK_TEST_SCHEDULER is not set"
)
@pytest.mark.parametrize("platform", ["sqlite"], indirect=True)
def test_tea_eeg_remote_mode_gives_the_same_analysis(synthetic_tea):
def snapshot():
analyses = synthetic_tea.query(
"select edf, valid, level, age_months, clean_fraction, bad_channels "
"from bronze.eeg_analysis order by edf"
)
metrics = synthetic_tea.query(
"select edf, code, value from bronze.eeg_metrics order by edf, code"
)
return analyses, metrics
assert tea_jobs.analyze(eeg.Scope(mode="first_n", n=2), rebuild_gold=False) == 2
before, metrics_before = snapshot()
ids = [study["id"] for study in eeg.studies() if study["analysed"]]
assert len(ids) == 2
@dg.op
def remote_analysis(context):
remote = cluster.Execution(mode="remote", scheduler=os.environ["DASK_TEST_SCHEDULER"])
with execution.running(context, remote):
return tea_jobs.analyze(eeg.Scope(mode="ids", ids=ids), rebuild_gold=False)
@dg.job
def reanalyze():
remote_analysis()
result = reanalyze.execute_in_process()
assert result.success
assert result.output_for_node("remote_analysis") == 2
after, metrics_after = snapshot()
def close(value):
return pytest.approx(value, rel=1e-12) if isinstance(value, float) else value
assert [tuple(row) for row in after] == [tuple(map(close, row)) for row in before]
assert [tuple(row) for row in metrics_after] == [
tuple(map(close, row)) for row in metrics_before
]