TEA EEG: training and analysis choose the cluster, EEG ids are text, run progress snapshots; tea library pointer
This commit is contained in:
+1
-1
Submodule libs/tea updated: fcf8e6ef03...ed31baf70f
+16
-1
@@ -4,8 +4,10 @@ Each area adds its subcommands to `build_parser`. Heavy imports (MLflow, the kit
|
|||||||
command that needs them, so `--help` stays immediate.
|
command that needs them, so `--help` stays immediate.
|
||||||
"""
|
"""
|
||||||
import argparse
|
import argparse
|
||||||
|
import json
|
||||||
import sys
|
import sys
|
||||||
from collections.abc import Sequence
|
from collections.abc import Sequence
|
||||||
|
from dataclasses import asdict
|
||||||
|
|
||||||
|
|
||||||
def _show_help(parser: argparse.ArgumentParser) -> int:
|
def _show_help(parser: argparse.ArgumentParser) -> int:
|
||||||
@@ -164,10 +166,22 @@ def _serve_notebooks(args: argparse.Namespace) -> int:
|
|||||||
|
|
||||||
def _tea_analyze(args: argparse.Namespace) -> int:
|
def _tea_analyze(args: argparse.Namespace) -> int:
|
||||||
"""The EEG analysis over the pending EEGs (`models.eeg_analysis`)."""
|
"""The EEG analysis over the pending EEGs (`models.eeg_analysis`)."""
|
||||||
|
if args.ids is not None and (args.all or args.limit is not None):
|
||||||
|
print("--ids cannot be combined with --all or --limit", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
ids = [value.strip() for value in args.ids.split(",")] if args.ids is not None else None
|
||||||
|
if ids is not None and not all(ids):
|
||||||
|
print("--ids requires a comma-separated list of EEG ids", file=sys.stderr)
|
||||||
|
return 2
|
||||||
from models.eeg_analysis import analyze_pending
|
from models.eeg_analysis import analyze_pending
|
||||||
|
|
||||||
s = analyze_pending(everything=args.all, limit=args.limit, cluster=args.cluster)
|
try:
|
||||||
|
s = analyze_pending(everything=args.all, limit=args.limit, ids=ids, cluster=args.cluster)
|
||||||
|
except LookupError as error:
|
||||||
|
print(error, file=sys.stderr)
|
||||||
|
return 1
|
||||||
print(f"{s.pending} pending: {s.valid} valid, {s.not_valid} not valid, {s.failed} failed")
|
print(f"{s.pending} pending: {s.valid} valid, {s.not_valid} not valid, {s.failed} failed")
|
||||||
|
print(f"summary: {json.dumps(asdict(s))}")
|
||||||
return 1 if s.failed else 0
|
return 1 if s.failed else 0
|
||||||
|
|
||||||
|
|
||||||
@@ -542,6 +556,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
"analyze", help="run the EEG analysis on each stored EDF not yet analysed with this plan, modules and baselines")
|
"analyze", help="run the EEG analysis on each stored EDF not yet analysed with this plan, modules and baselines")
|
||||||
analyze.add_argument("--all", action="store_true", help="analyse every EEG with an EDF again")
|
analyze.add_argument("--all", action="store_true", help="analyse every EEG with an EDF again")
|
||||||
analyze.add_argument("--limit", type=int, help="at most this many EEGs")
|
analyze.add_argument("--limit", type=int, help="at most this many EEGs")
|
||||||
|
analyze.add_argument("--ids", help="comma-separated EEG IDs to analyse again")
|
||||||
analyze.add_argument("--cluster", choices=["auto", "local", "remote", "sync"], default="auto",
|
analyze.add_argument("--cluster", choices=["auto", "local", "remote", "sync"], default="auto",
|
||||||
help="where the batch runs: DASK_SCHEDULER_ADDRESS or a local cluster (auto), or this process")
|
help="where the batch runs: DASK_SCHEDULER_ADDRESS or a local cluster (auto), or this process")
|
||||||
analyze.set_defaults(run=_tea_analyze)
|
analyze.set_defaults(run=_tea_analyze)
|
||||||
|
|||||||
+33
-9
@@ -13,10 +13,12 @@ its governance `ExtractionRun` (VAR-07/08) as soon as it arrives, so an interrup
|
|||||||
`DASK_SCHEDULER_ADDRESS` if set and locally otherwise.
|
`DASK_SCHEDULER_ADDRESS` if set and locally otherwise.
|
||||||
"""
|
"""
|
||||||
import uuid
|
import uuid
|
||||||
from collections.abc import Callable, Mapping
|
from collections.abc import Callable, Mapping, Sequence
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from datetime import datetime, timedelta, timezone
|
from datetime import datetime, timedelta, timezone
|
||||||
|
from itertools import batched
|
||||||
|
|
||||||
|
from sqlalchemy import case
|
||||||
from sqlmodel import Session, col, delete, select
|
from sqlmodel import Session, col, delete, select
|
||||||
|
|
||||||
from core.tea.enums import MetricaEeg
|
from core.tea.enums import MetricaEeg
|
||||||
@@ -38,10 +40,26 @@ def checked_settings() -> Settings:
|
|||||||
return s
|
return s
|
||||||
|
|
||||||
|
|
||||||
|
def selected_ids(session: Session, ids: Sequence[int | str]) -> list[str]:
|
||||||
|
"""Resolve requested IDs and return the ones with stored EDFs."""
|
||||||
|
requested = {str(eeg_id) for eeg_id in ids}
|
||||||
|
has_edf = case((Eeg.eeg_estudio.is_not(None), 1), else_=0)
|
||||||
|
found = {}
|
||||||
|
for group in batched(requested, 500):
|
||||||
|
query = select(Eeg.eeg_id, has_edf).where(col(Eeg.eeg_id).in_(group))
|
||||||
|
found.update(session.exec(query).all())
|
||||||
|
missing = sorted(requested - found.keys())
|
||||||
|
if missing:
|
||||||
|
raise LookupError(f"No se encontraron los EEG: {', '.join(missing)}")
|
||||||
|
return sorted(eeg_id for eeg_id, stored in found.items() if stored)
|
||||||
|
|
||||||
|
|
||||||
def pending_ids(session: Session, *, plan_hash: str, versions: str, models: Callable[[], Mapping[str, str | None]],
|
def pending_ids(session: Session, *, plan_hash: str, versions: str, models: Callable[[], Mapping[str, str | None]],
|
||||||
everything: bool = False, limit: int | None = None) -> list[str]:
|
everything: bool = False, limit: int | None = None, ids: Sequence[int | str] | None = None) -> list[str]:
|
||||||
"""`models` gives the `met_modelo` each metric code would get now; it is only asked when a valid EEG analysed
|
"""`models` gives the `met_modelo` each metric code would get now; it is only asked when a valid EEG analysed
|
||||||
with the current plan and versions has to be compared, so a cycle with nothing to compare never reads MLflow."""
|
with the current plan and versions has to be compared, so a cycle with nothing to compare never reads MLflow."""
|
||||||
|
if ids is not None:
|
||||||
|
return selected_ids(session, ids)
|
||||||
query = select(Eeg.eeg_id, Eeg.eeg_valido, Eeg.eeg_plan_hash, Eeg.eeg_versiones, Eeg.eeg_error).where(
|
query = select(Eeg.eeg_id, Eeg.eeg_valido, Eeg.eeg_plan_hash, Eeg.eeg_versiones, Eeg.eeg_error).where(
|
||||||
Eeg.eeg_estudio.is_not(None)).order_by(Eeg.eeg_id)
|
Eeg.eeg_estudio.is_not(None)).order_by(Eeg.eeg_id)
|
||||||
out, expected = [], None
|
out, expected = [], None
|
||||||
@@ -203,27 +221,33 @@ def _now() -> datetime:
|
|||||||
return datetime.now(timezone.utc).replace(tzinfo=None)
|
return datetime.now(timezone.utc).replace(tzinfo=None)
|
||||||
|
|
||||||
|
|
||||||
def analyze_pending(*, everything: bool = False, limit: int | None = None, cluster: str = "auto", batch: int = 16,
|
def analyze_pending(*, everything: bool = False, limit: int | None = None, ids: Sequence[int | str] | None = None,
|
||||||
|
cluster: str = "auto", batch: int = 16,
|
||||||
settings: Settings | None = None, baselines: Baselines | None = None,
|
settings: Settings | None = None, baselines: Baselines | None = None,
|
||||||
measure_fn: Callable[..., Measurement] = measure, log_runs: bool = True) -> Summary:
|
measure_fn: Callable[..., Measurement] = measure, log_runs: bool = True) -> Summary:
|
||||||
from tea.pipeline.dask_runner import run as run_batch
|
from tea.pipeline.dask_runner import run as run_batch
|
||||||
|
from tea.pipeline.run_monitor import monitor_from_env
|
||||||
|
|
||||||
from persistance.tea import eeg_repository
|
from persistance.tea import eeg_repository
|
||||||
|
|
||||||
|
with monitor_from_env() as monitor:
|
||||||
s = settings or checked_settings()
|
s = settings or checked_settings()
|
||||||
b = baselines or Baselines(s.domain)
|
b = baselines or Baselines(s.domain)
|
||||||
pipe = pipeline(s)
|
pipe = pipeline(s)
|
||||||
plan_hash, current = plan(s).get("hash", ""), versions(pipe, s)
|
plan_hash, current = plan(s).get("hash", ""), versions(pipe, s)
|
||||||
with eeg_repository.open_session() as session:
|
with eeg_repository.open_session() as session:
|
||||||
ids = pending_ids(session, plan_hash=plan_hash, versions=current, models=lambda: expected_models(s, b),
|
selected = pending_ids(session, plan_hash=plan_hash, versions=current, models=lambda: expected_models(s, b),
|
||||||
everything=everything, limit=limit)
|
everything=everything, limit=limit, ids=ids)
|
||||||
summary = Summary(pending=len(ids))
|
summary = Summary(pending=len(selected))
|
||||||
|
monitor.total(summary.pending)
|
||||||
|
monitor.phase("analizando")
|
||||||
|
|
||||||
def write(m: Measurement) -> None:
|
def write(m: Measurement) -> None:
|
||||||
ended = _now()
|
ended = _now()
|
||||||
with eeg_repository.open_session() as session:
|
with eeg_repository.open_session() as session:
|
||||||
save(session, m.key, rows(m, s, b, at=ended))
|
save(session, m.key, rows(m, s, b, at=ended))
|
||||||
session.commit()
|
session.commit()
|
||||||
|
monitor.advance()
|
||||||
if log_runs:
|
if log_runs:
|
||||||
from persistance.governance import extraction_run_repository
|
from persistance.governance import extraction_run_repository
|
||||||
|
|
||||||
@@ -239,11 +263,11 @@ def analyze_pending(*, everything: bool = False, limit: int | None = None, clust
|
|||||||
return Measurement(key=args[0], age_months=args[2], plan_hash=plan_hash, versions=current,
|
return Measurement(key=args[0], age_months=args[2], plan_hash=plan_hash, versions=current,
|
||||||
error=f"{type(exc).__name__}: the batch lost this study")
|
error=f"{type(exc).__name__}: the batch lost this study")
|
||||||
|
|
||||||
for start in range(0, len(ids), batch):
|
for start in range(0, len(selected), batch):
|
||||||
argsets = []
|
argsets = []
|
||||||
with eeg_repository.open_session() as session:
|
with eeg_repository.open_session() as session:
|
||||||
for eeg_id in ids[start:start + batch]:
|
for eeg_id in selected[start:start + batch]:
|
||||||
edf, age = inputs(session, eeg_id, s.days_per_month)
|
edf, age = inputs(session, eeg_id, s.days_per_month)
|
||||||
argsets.append((eeg_id, edf, age, s))
|
argsets.append((eeg_id, edf, age, s))
|
||||||
run_batch(measure_fn, argsets, cluster=cluster, on_result=write, on_error=lost)
|
run_batch(measure_fn, argsets, cluster=cluster, on_result=write, on_error=lost, track_progress=False)
|
||||||
return summary
|
return summary
|
||||||
|
|||||||
@@ -6,11 +6,19 @@ then promoting each through the registry's checks. `--reference-dir` trains on a
|
|||||||
instead of the cohort of `model.toml` (`reference.py`), to export the result as a bundle (`bundle.py`).
|
instead of the cohort of `model.toml` (`reference.py`), to export the result as a bundle (`bundle.py`).
|
||||||
"""
|
"""
|
||||||
import argparse
|
import argparse
|
||||||
|
import os
|
||||||
import sys
|
import sys
|
||||||
|
|
||||||
from models.tea.eeg.settings import settings
|
from models.tea.eeg.settings import settings
|
||||||
|
|
||||||
SETTINGS = settings()
|
SETTINGS = settings()
|
||||||
|
CLUSTERS = ("auto", "local", "remote", "sync")
|
||||||
|
|
||||||
|
|
||||||
|
def _cluster() -> str:
|
||||||
|
"""Where training measures the studies: `EEG_ANALYSIS_CLUSTER` when it names a runner, else `auto`."""
|
||||||
|
chosen = os.environ.get("EEG_ANALYSIS_CLUSTER", "auto")
|
||||||
|
return chosen if chosen in CLUSTERS else "auto"
|
||||||
|
|
||||||
|
|
||||||
def run_steps(args: argparse.Namespace) -> int:
|
def run_steps(args: argparse.Namespace) -> int:
|
||||||
@@ -32,7 +40,7 @@ def run_steps(args: argparse.Namespace) -> int:
|
|||||||
return 2
|
return 2
|
||||||
versions: dict[str, str] = {}
|
versions: dict[str, str] = {}
|
||||||
if args.train:
|
if args.train:
|
||||||
for scenario, (version, new) in train.train_all(s, environment).items():
|
for scenario, (version, new) in train.train_all(s, environment, cluster=_cluster()).items():
|
||||||
print(f"{scenario}: {'trained' if new else 'already trained'}, version {version}")
|
print(f"{scenario}: {'trained' if new else 'already trained'}, version {version}")
|
||||||
versions[scenario] = version
|
versions[scenario] = version
|
||||||
if not args.promote:
|
if not args.promote:
|
||||||
|
|||||||
+12
-2
@@ -19,6 +19,7 @@ from dataclasses import dataclass
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
from tea.pipeline.run_monitor import active_monitor, monitor_from_env
|
||||||
|
|
||||||
from models.io.lineage import (
|
from models.io.lineage import (
|
||||||
COHORT_BUILD_TAG,
|
COHORT_BUILD_TAG,
|
||||||
@@ -78,7 +79,7 @@ def list_reference(s: Settings) -> list[tuple[str, float]]:
|
|||||||
def listing(s: Settings, cluster: str = "auto") -> Listing:
|
def listing(s: Settings, cluster: str = "auto") -> Listing:
|
||||||
from tea.pipeline.dask_runner import run as run_batch
|
from tea.pipeline.dask_runner import run as run_batch
|
||||||
|
|
||||||
(found,) = run_batch(list_reference, [(s,)], cluster=cluster)
|
(found,) = run_batch(list_reference, [(s,)], cluster=cluster, track_progress=False)
|
||||||
return Listing.of(s.reference.name, found)
|
return Listing.of(s.reference.name, found)
|
||||||
|
|
||||||
|
|
||||||
@@ -146,9 +147,14 @@ def train_scenario(scenario: str, studies: list[ReferenceStudy], found: Listing,
|
|||||||
biomarker, phase = s.scenarios[scenario]
|
biomarker, phase = s.scenarios[scenario]
|
||||||
data = table(studies, biomarker, phase)
|
data = table(studies, biomarker, phase)
|
||||||
module = type(pipeline(s).module(biomarker))(baseline=s.baseline)
|
module = type(pipeline(s).module(biomarker))(baseline=s.baseline)
|
||||||
|
monitor = active_monitor()
|
||||||
|
if monitor is not None:
|
||||||
|
monitor.phase("ajustando")
|
||||||
module.train(data)
|
module.train(data)
|
||||||
sha, state = _module_state(module)
|
sha, state = _module_state(module)
|
||||||
name = registered_name(DOMAIN, scenario)
|
name = registered_name(DOMAIN, scenario)
|
||||||
|
if monitor is not None:
|
||||||
|
monitor.phase("registrando")
|
||||||
# Created here first so it lives under MLFLOW_ARTIFACT_ROOT; `log_biomarker` alone would put it in ./mlruns.
|
# Created here first so it lives under MLFLOW_ARTIFACT_ROOT; `log_biomarker` alone would put it in ./mlruns.
|
||||||
experiment_id(MlflowClient(), name)
|
experiment_id(MlflowClient(), name)
|
||||||
mv = log_biomarker(module, plan=plan(s), registered_name=name, run_name=scenario, n_reference=len(data),
|
mv = log_biomarker(module, plan=plan(s), registered_name=name, run_name=scenario, n_reference=len(data),
|
||||||
@@ -210,6 +216,7 @@ def train_all(s: Settings, environment: str, *, cluster: str = "auto", found: Li
|
|||||||
"""Every scenario's version, by scenario: (version, whether it's new). A scenario already trained on the same
|
"""Every scenario's version, by scenario: (version, whether it's new). A scenario already trained on the same
|
||||||
listing, plan, module version and baseline keeps its version; the reference cohort is measured only if some
|
listing, plan, module version and baseline keeps its version; the reference cohort is measured only if some
|
||||||
scenario needs it."""
|
scenario needs it."""
|
||||||
|
with monitor_from_env() as monitor:
|
||||||
found = found or listing(s, cluster)
|
found = found or listing(s, cluster)
|
||||||
out, pending = {}, []
|
out, pending = {}, []
|
||||||
for scenario in s.scenarios:
|
for scenario in s.scenarios:
|
||||||
@@ -219,7 +226,10 @@ def train_all(s: Settings, environment: str, *, cluster: str = "auto", found: Li
|
|||||||
else:
|
else:
|
||||||
pending.append(scenario)
|
pending.append(scenario)
|
||||||
if pending:
|
if pending:
|
||||||
studies = studies if studies is not None else measure(found, s, cluster)
|
if studies is None:
|
||||||
|
monitor.total(len(found.studies))
|
||||||
|
monitor.phase("midiendo")
|
||||||
|
studies = measure(found, s, cluster)
|
||||||
for scenario in pending:
|
for scenario in pending:
|
||||||
out[scenario] = (train_scenario(scenario, studies, found, s, environment), True)
|
out[scenario] = (train_scenario(scenario, studies, found, s, environment), True)
|
||||||
return out
|
return out
|
||||||
|
|||||||
@@ -0,0 +1,196 @@
|
|||||||
|
"""Cover cluster probes using clean_environment, loopback_port and monkeypatch.
|
||||||
|
|
||||||
|
Fails if mode resolution, connection handling or independent probe results regress.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import socket
|
||||||
|
from contextlib import nullcontext
|
||||||
|
from time import perf_counter
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import Mock
|
||||||
|
|
||||||
|
import distributed
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from tea.pipeline import cluster_status
|
||||||
|
from tea.pipeline.cluster_status import ClusterStatus
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def clean_environment(monkeypatch):
|
||||||
|
"""Clear cluster configuration so machine settings cannot change probe targets or results."""
|
||||||
|
for variable in (
|
||||||
|
"DASK_SCHEDULER_ADDRESS",
|
||||||
|
"TEA_DASK_EXPECTED_WORKERS",
|
||||||
|
"TEA_DASK_DASHBOARD_URL",
|
||||||
|
"TEA_DASK_DASHBOARD_PORT",
|
||||||
|
):
|
||||||
|
monkeypatch.delenv(variable, raising=False)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def loopback_port():
|
||||||
|
"""Reserve a loopback port so live probes cannot connect to another service."""
|
||||||
|
try:
|
||||||
|
port = socket.socket()
|
||||||
|
except PermissionError as exc:
|
||||||
|
pytest.skip(f"TCP sockets are unavailable: {exc}")
|
||||||
|
with port:
|
||||||
|
try:
|
||||||
|
port.bind(("127.0.0.1", 0))
|
||||||
|
except PermissionError as exc:
|
||||||
|
pytest.skip(f"Loopback binding is unavailable: {exc}")
|
||||||
|
yield port.getsockname()[1]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("mode", ["auto", "local", "sync"])
|
||||||
|
def test_non_remote_mode_does_not_connect(monkeypatch, mode):
|
||||||
|
"""Pin the full non-remote response. Fail if a client starts or a probe reports a value."""
|
||||||
|
client = Mock()
|
||||||
|
monkeypatch.setattr(distributed, "Client", client)
|
||||||
|
if mode != "auto":
|
||||||
|
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", "tcp://scheduler:8786")
|
||||||
|
|
||||||
|
assert ClusterStatus().check(mode) == {
|
||||||
|
"mode": "local" if mode == "auto" else mode,
|
||||||
|
"scheduler": None,
|
||||||
|
"reachable": True,
|
||||||
|
"workers": None,
|
||||||
|
"expected_workers": None,
|
||||||
|
"versions_ok": None,
|
||||||
|
"version_error": None,
|
||||||
|
"dashboard_ok": None,
|
||||||
|
"dashboard_url": None,
|
||||||
|
"reference": None,
|
||||||
|
"latency_ms": None,
|
||||||
|
"error": None,
|
||||||
|
}
|
||||||
|
client.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
|
def test_unreachable_scheduler_is_bounded(monkeypatch, loopback_port):
|
||||||
|
"""Pin failure on a closed TCP port. Fail if it raises or ignores the connection timeout."""
|
||||||
|
monkeypatch.setenv("TEA_DASK_DASHBOARD_PORT", str(loopback_port))
|
||||||
|
start = perf_counter()
|
||||||
|
status = ClusterStatus().check(scheduler=f"tcp://127.0.0.1:{loopback_port}")
|
||||||
|
|
||||||
|
assert perf_counter() - start < 9
|
||||||
|
assert status["mode"] == "remote"
|
||||||
|
assert status["reachable"] is False
|
||||||
|
assert status["error"]
|
||||||
|
assert status["workers"] is None
|
||||||
|
assert status["versions_ok"] is None
|
||||||
|
assert status["dashboard_ok"] is False
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.usefixtures("loopback_port")
|
||||||
|
def test_reachable_scheduler_reports_one_worker(monkeypatch):
|
||||||
|
"""Pin health on a real Dask worker. Fail if the client miscounts it or skips version checks."""
|
||||||
|
with distributed.LocalCluster(
|
||||||
|
n_workers=1, threads_per_worker=1, processes=False, dashboard_address=":0"
|
||||||
|
) as cluster:
|
||||||
|
monkeypatch.setenv("DASK_SCHEDULER_ADDRESS", cluster.scheduler_address)
|
||||||
|
monkeypatch.setenv("TEA_DASK_EXPECTED_WORKERS", "2")
|
||||||
|
port = cluster.scheduler.services["dashboard"].port
|
||||||
|
monkeypatch.setenv("TEA_DASK_DASHBOARD_URL", f"http://127.0.0.1:{port}/status")
|
||||||
|
monkeypatch.setenv("no_proxy", "127.0.0.1")
|
||||||
|
|
||||||
|
status = ClusterStatus().check()
|
||||||
|
|
||||||
|
assert status["scheduler"] == cluster.scheduler_address
|
||||||
|
assert status["reachable"] is True
|
||||||
|
assert status["workers"] == 1
|
||||||
|
assert status["expected_workers"] == 2
|
||||||
|
assert status["versions_ok"] is True
|
||||||
|
assert status["dashboard_ok"] is True
|
||||||
|
assert status["latency_ms"] >= 0
|
||||||
|
assert status["error"] is None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("dashboard_healthy", [True, False])
|
||||||
|
def test_version_mismatch_and_dashboard_are_independent(monkeypatch, dashboard_healthy):
|
||||||
|
"""Pin zero-worker and mismatch responses. Fail if either prevents an independent dashboard probe."""
|
||||||
|
client = Mock()
|
||||||
|
client.scheduler_info.return_value = {"workers": {}}
|
||||||
|
client.get_versions.side_effect = ValueError("version mismatch")
|
||||||
|
connect = Mock(return_value=client)
|
||||||
|
monkeypatch.setattr(distributed, "Client", connect)
|
||||||
|
if dashboard_healthy:
|
||||||
|
dashboard_url = "https://dashboard.example/status?view=all"
|
||||||
|
health_url = "https://dashboard.example/health"
|
||||||
|
monkeypatch.setenv("TEA_DASK_DASHBOARD_URL", dashboard_url)
|
||||||
|
open_health = Mock(return_value=nullcontext(SimpleNamespace(status=200)))
|
||||||
|
else:
|
||||||
|
dashboard_url = "http://scheduler:8787/status"
|
||||||
|
health_url = "http://scheduler:8787/health"
|
||||||
|
open_health = Mock(side_effect=TimeoutError)
|
||||||
|
monkeypatch.setattr(cluster_status, "urlopen", open_health)
|
||||||
|
|
||||||
|
status = ClusterStatus().check("remote", "tcp://scheduler:8786", "cohort")
|
||||||
|
|
||||||
|
assert status["reachable"] is True
|
||||||
|
assert status["error"] is None
|
||||||
|
assert status["workers"] == 0
|
||||||
|
assert status["versions_ok"] is False
|
||||||
|
assert status["version_error"] == "version mismatch"
|
||||||
|
assert status["dashboard_ok"] is dashboard_healthy
|
||||||
|
assert status["dashboard_url"] == dashboard_url
|
||||||
|
assert status["reference"] is None
|
||||||
|
connect.assert_called_once_with("tcp://scheduler:8786", timeout=5)
|
||||||
|
client.get_versions.assert_called_once_with(check=True)
|
||||||
|
client.submit.assert_not_called()
|
||||||
|
client.close.assert_called_once_with()
|
||||||
|
open_health.assert_called_once_with(health_url, timeout=3)
|
||||||
|
|
||||||
|
|
||||||
|
def test_warning_only_version_mismatch_is_reported(monkeypatch):
|
||||||
|
"""Pin mismatches returned by Dask without an exception. Fail if they count as compatible."""
|
||||||
|
client = Mock()
|
||||||
|
client.scheduler_info.return_value = {"workers": {"worker": {}}}
|
||||||
|
matching = {"packages": {"distributed": "2026.8.0"}}
|
||||||
|
client.get_versions.return_value = {
|
||||||
|
"scheduler": matching,
|
||||||
|
"client": matching,
|
||||||
|
"workers": {"worker": {"packages": {"distributed": "2026.9.0"}}},
|
||||||
|
}
|
||||||
|
monkeypatch.setattr(distributed, "Client", Mock(return_value=client))
|
||||||
|
monkeypatch.setattr(cluster_status, "urlopen", Mock(side_effect=TimeoutError))
|
||||||
|
|
||||||
|
status = ClusterStatus().check(scheduler="tcp://scheduler:8786")
|
||||||
|
|
||||||
|
assert status["versions_ok"] is False
|
||||||
|
assert "Mismatched versions found" in status["version_error"]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("name", ["cohort-1", "../escape", ".."])
|
||||||
|
def test_reference_submission_requires_safe_name(monkeypatch, name):
|
||||||
|
"""Pin worker-side reference lookup. Fail if an unsafe name is submitted or a valid count is lost."""
|
||||||
|
client = Mock()
|
||||||
|
client.scheduler_info.return_value = {"workers": {"worker": {}}}
|
||||||
|
client.submit.return_value.result.return_value = 3
|
||||||
|
monkeypatch.setattr(distributed, "Client", Mock(return_value=client))
|
||||||
|
monkeypatch.setattr(cluster_status, "urlopen", Mock(side_effect=TimeoutError))
|
||||||
|
|
||||||
|
status = ClusterStatus().check(scheduler="tcp://scheduler:8786", reference_name=name)
|
||||||
|
|
||||||
|
if name == "cohort-1":
|
||||||
|
client.submit.assert_called_once_with(cluster_status._count_edfs, name, pure=False)
|
||||||
|
assert status["reference"] == {"name": name, "edfs": 3}
|
||||||
|
else:
|
||||||
|
client.submit.assert_not_called()
|
||||||
|
assert status["reference"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_local_workers_can_be_capped_by_the_environment(monkeypatch):
|
||||||
|
"""Pins down: `TEA_LOCAL_WORKERS` fixes the size of a local cluster, an explicit count still wins, and a value
|
||||||
|
below one means one worker.
|
||||||
|
|
||||||
|
Fails if a local run on a shared machine can no longer be limited from the environment.
|
||||||
|
"""
|
||||||
|
from tea.pipeline.dask_runner import local_workers
|
||||||
|
|
||||||
|
monkeypatch.setenv("TEA_LOCAL_WORKERS", "1")
|
||||||
|
assert local_workers() == 1
|
||||||
|
monkeypatch.setenv("TEA_LOCAL_WORKERS", "0")
|
||||||
|
assert local_workers() == 1
|
||||||
|
assert local_workers(n_workers=3) == 3
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
"""What this module covers: the EEG analysis's settings and its unit of work, `measure`, run on the real `tea`
|
"""What this module covers: the EEG analysis's settings and its unit of work, `measure`, run on the real `tea`
|
||||||
library.
|
library, plus EEG selection and the CLI summary. Fails if explicit selection skips current studies or the CLI
|
||||||
|
stops reporting its final counts.
|
||||||
|
|
||||||
Fixtures: `measured`, three synthetic studies measured once for the module (see `synth_edf.py`): a clean four-minute
|
Fixtures: `measured`, three synthetic studies measured once for the module (see `synth_edf.py`): a clean four-minute
|
||||||
study, half awake with a 7 Hz posterior rhythm and half asleep with spindles; the same with eight central and
|
study, half awake with a 7 Hz posterior rhythm and half asleep with spindles; the same with eight central and
|
||||||
posterior channels flat; and bytes that are not an EDF.
|
posterior channels flat; and bytes that are not an EDF. `selection_session` holds three EEG rows in SQLite.
|
||||||
"""
|
"""
|
||||||
import pytest
|
import pytest
|
||||||
from synth_edf import edf_bytes
|
from synth_edf import edf_bytes
|
||||||
@@ -18,7 +19,7 @@ FLAT = ["C3", "C4", "Cz", "P3", "P4", "Pz", "O1", "O2"]
|
|||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
def measured():
|
def measured():
|
||||||
"""The three studies' measurements, keyed `clean`, `flat` and `broken`; the clean child is 27.5 months old."""
|
"""Measure clean, flat, and broken studies to expose changes in triage and metrics."""
|
||||||
s = settings()
|
s = settings()
|
||||||
return {
|
return {
|
||||||
"clean": measure("clean", edf_bytes(minutes=4), 27.5, s),
|
"clean": measure("clean", edf_bytes(minutes=4), 27.5, s),
|
||||||
@@ -115,3 +116,77 @@ def test_channel_codes_lose_their_numbers():
|
|||||||
assert criterion_code("intermittent-contact-by", "intermittent contact by bursts (30% of blocks)", "F3") == \
|
assert criterion_code("intermittent-contact-by", "intermittent contact by bursts (30% of blocks)", "F3") == \
|
||||||
"intermittent-bursts"
|
"intermittent-bursts"
|
||||||
assert criterion_code("clean-windows", "clean 4 s windows", None) == "clean-windows"
|
assert criterion_code("clean-windows", "clean 4 s windows", None) == "clean-windows"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def selection_session():
|
||||||
|
"""Store current, pending, and EDF-less EEGs to expose scope regressions."""
|
||||||
|
from sqlmodel import Session, create_engine
|
||||||
|
|
||||||
|
from core.tea.models import Eeg
|
||||||
|
|
||||||
|
engine = create_engine("sqlite://")
|
||||||
|
Eeg.__table__.create(engine)
|
||||||
|
with Session(engine) as session:
|
||||||
|
session.add_all([
|
||||||
|
Eeg(eeg_id="1", eeg_estudio=b"edf", eeg_plan_hash="current", eeg_versiones="current", eeg_valido=0),
|
||||||
|
Eeg(eeg_id="2"),
|
||||||
|
Eeg(eeg_id="3", eeg_estudio=b"edf"),
|
||||||
|
])
|
||||||
|
session.commit()
|
||||||
|
yield session
|
||||||
|
engine.dispose()
|
||||||
|
|
||||||
|
|
||||||
|
def test_explicit_ids_select_current_edfs(selection_session):
|
||||||
|
"""Pin explicit reanalysis. Fail if current EEGs are skipped or EDF-less and unrequested rows are selected."""
|
||||||
|
from models.eeg_analysis import pending_ids
|
||||||
|
|
||||||
|
options = {"plan_hash": "current", "versions": "current", "models": dict}
|
||||||
|
assert pending_ids(selection_session, **options) == ["3"]
|
||||||
|
assert pending_ids(selection_session, ids=[2, 1, 1], **options) == ["1"]
|
||||||
|
with pytest.raises(LookupError, match=r"8, 9"):
|
||||||
|
pending_ids(selection_session, ids=[1, 9, 8], **options)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("failed", [0, 1])
|
||||||
|
def test_analyze_cli_emits_summary_and_passes_ids(monkeypatch, capsys, failed):
|
||||||
|
"""Pin the final JSON line and failure status. Fail if explicit IDs or the failed count are ignored."""
|
||||||
|
import json
|
||||||
|
|
||||||
|
from models import eeg_analysis
|
||||||
|
from models.__main__ import main
|
||||||
|
|
||||||
|
def analyze(**options):
|
||||||
|
assert options == {"everything": False, "limit": None, "ids": ["1", "2"], "cluster": "sync"}
|
||||||
|
return eeg_analysis.Summary(pending=2, valid=1, not_valid=1 - failed, failed=failed)
|
||||||
|
|
||||||
|
monkeypatch.setattr(eeg_analysis, "analyze_pending", analyze)
|
||||||
|
assert main(["tea", "analyze", "--ids", "1,2", "--cluster", "sync"]) == failed
|
||||||
|
line = capsys.readouterr().out.splitlines()[-1]
|
||||||
|
assert line.startswith("summary: ")
|
||||||
|
assert json.loads(line.removeprefix("summary: ")) == {
|
||||||
|
"pending": 2, "valid": 1, "not_valid": 1 - failed, "failed": failed,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def test_explicit_ids_may_be_uuids(selection_session):
|
||||||
|
"""Pin that ids are matched as strings, so the UUID ids real EEGs carry select their rows. Fail if ids go back
|
||||||
|
to being parsed as integers."""
|
||||||
|
from core.tea.models import Eeg
|
||||||
|
from models.eeg_analysis import selected_ids
|
||||||
|
|
||||||
|
uuid = "ed257fbd-61d5-4c9c-bb72-00c4ec550961"
|
||||||
|
selection_session.add(Eeg(eeg_id=uuid, eeg_estudio=b"EDF"))
|
||||||
|
selection_session.commit()
|
||||||
|
assert selected_ids(selection_session, [uuid]) == [uuid]
|
||||||
|
with pytest.raises(LookupError, match="no-such-id"):
|
||||||
|
selected_ids(selection_session, [uuid, "no-such-id"])
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("other", [["--all"], ["--limit", "2"]])
|
||||||
|
def test_analyze_cli_rejects_conflicting_scope(other):
|
||||||
|
"""Pin exit 2 for ambiguous scopes. Fail if an explicit ID request can start with another scope."""
|
||||||
|
from models.__main__ import main
|
||||||
|
|
||||||
|
assert main(["tea", "analyze", "--ids", "1", *other]) == 2
|
||||||
|
|||||||
@@ -184,3 +184,20 @@ def test_a_reference_study_is_measured_from_its_path(tmp_path):
|
|||||||
assert (st.valid, st.error) == (1, None)
|
assert (st.valid, st.error) == (1, None)
|
||||||
assert set(st.features) == set(settings().scenarios.values())
|
assert set(st.features) == set(settings().scenarios.values())
|
||||||
assert set(st.features["spindles", "N2"]) == set(pipeline(settings()).module("spindles").features)
|
assert set(st.features["spindles", "N2"]) == set(pipeline(settings()).module("spindles").features)
|
||||||
|
|
||||||
|
|
||||||
|
def test_training_reads_the_cluster_choice_from_the_environment(monkeypatch):
|
||||||
|
"""Pins down: training measures its studies on the runner `EEG_ANALYSIS_CLUSTER` names, and falls back to `auto`
|
||||||
|
for an unset or unknown value (including `off`, which only the analysis understands).
|
||||||
|
|
||||||
|
Fails if `run_steps` stops passing the choice to `train_all`, or lets an unknown value reach the runner.
|
||||||
|
"""
|
||||||
|
from models.tea.eeg import model
|
||||||
|
|
||||||
|
monkeypatch.delenv("EEG_ANALYSIS_CLUSTER", raising=False)
|
||||||
|
assert model._cluster() == "auto"
|
||||||
|
for chosen in ("auto", "local", "remote", "sync"):
|
||||||
|
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", chosen)
|
||||||
|
assert model._cluster() == chosen
|
||||||
|
monkeypatch.setenv("EEG_ANALYSIS_CLUSTER", "off")
|
||||||
|
assert model._cluster() == "auto"
|
||||||
|
|||||||
@@ -0,0 +1,163 @@
|
|||||||
|
"""Cover optional, atomic progress reporting and ETA with temporary files and a fake clock.
|
||||||
|
|
||||||
|
Fails if monitoring changes unconfigured runs, publishes incomplete samples, or miscalculates throughput.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from distributed import Client, LocalCluster
|
||||||
|
|
||||||
|
from tea.pipeline import run_monitor
|
||||||
|
|
||||||
|
|
||||||
|
def test_monitor_without_directory(monkeypatch):
|
||||||
|
"""Pin the no-op monitor. Fail if an unconfigured run activates sampling."""
|
||||||
|
monkeypatch.delenv("RUN_PROGRESS_DIR", raising=False)
|
||||||
|
with run_monitor.monitor_from_env() as monitor:
|
||||||
|
monitor.start()
|
||||||
|
monitor.phase("analizando")
|
||||||
|
monitor.total(12)
|
||||||
|
monitor.advance()
|
||||||
|
assert run_monitor.active_monitor() is None
|
||||||
|
monitor.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_local_cluster_progress(tmp_path, monkeypatch):
|
||||||
|
"""Pin live Dask telemetry and atomic snapshots. Fail if progress stalls, grows unbounded, or tears."""
|
||||||
|
path = tmp_path / "progress.json"
|
||||||
|
replace = run_monitor.os.replace
|
||||||
|
replacements = []
|
||||||
|
|
||||||
|
def verify_replace(source, target):
|
||||||
|
if target == path:
|
||||||
|
assert json.loads(source.read_text())["history"]
|
||||||
|
if path.exists():
|
||||||
|
assert json.loads(path.read_text())["history"]
|
||||||
|
replacements.append(source)
|
||||||
|
replace(source, target)
|
||||||
|
|
||||||
|
def read_until(predicate):
|
||||||
|
deadline = time.monotonic() + 10
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
if path.exists():
|
||||||
|
progress = json.loads(path.read_text())
|
||||||
|
if predicate(progress):
|
||||||
|
return progress
|
||||||
|
time.sleep(0.01)
|
||||||
|
pytest.fail("Timed out waiting for progress")
|
||||||
|
|
||||||
|
monkeypatch.setattr(run_monitor.os, "replace", verify_replace)
|
||||||
|
with LocalCluster(n_workers=1, threads_per_worker=1, processes=False, dashboard_address=":0") as cluster:
|
||||||
|
with Client(cluster) as client, run_monitor.RunMonitor(tmp_path, interval=0.1, history=4) as monitor:
|
||||||
|
monitor.start(client, ("local", None))
|
||||||
|
monitor.total(10)
|
||||||
|
monitor.phase("midiendo")
|
||||||
|
initial = read_until(lambda p: p["phase"] == "midiendo" and p["tasks"] and p["cluster"]["workers"])
|
||||||
|
assert initial["done"] == 0 and initial["eta_s"] is None
|
||||||
|
assert set(initial["tasks"]) == {"processing", "waiting", "memory", "erred"}
|
||||||
|
assert initial["cluster"]["workers"][0]["threads"] == 1
|
||||||
|
monitor.advance(3)
|
||||||
|
measured = read_until(lambda p: p["done"] == 3 and len(p["history"]) == 4)
|
||||||
|
assert measured["eta_s"] > 0
|
||||||
|
monitor.advance(2)
|
||||||
|
monitor.phase("ajustando")
|
||||||
|
monitor.stop()
|
||||||
|
|
||||||
|
final = json.loads(path.read_text())
|
||||||
|
assert final["done"] == 5 and final["eta_s"] is None
|
||||||
|
assert final["phase"] == "ajustando"
|
||||||
|
assert len(final["history"]) == 4
|
||||||
|
assert final["history"][-1]["done"] == 5
|
||||||
|
assert len(replacements) >= 5
|
||||||
|
assert list(tmp_path.iterdir()) == [path]
|
||||||
|
|
||||||
|
|
||||||
|
def test_eta_smoothed_rate(tmp_path, monkeypatch):
|
||||||
|
"""Pin ETA arithmetic and its threshold. Fail if cumulative or instantaneous rate replaces smoothing."""
|
||||||
|
now = 100.0
|
||||||
|
monkeypatch.setattr(run_monitor, "monotonic", lambda: now)
|
||||||
|
monkeypatch.setattr(run_monitor.Thread, "start", lambda self: None)
|
||||||
|
monkeypatch.setenv("RUN_PROGRESS_DIR", str(tmp_path))
|
||||||
|
path = tmp_path / "progress.json"
|
||||||
|
with run_monitor.monitor_from_env() as monitor:
|
||||||
|
assert run_monitor.active_monitor() is monitor
|
||||||
|
monitor.phase("analizando")
|
||||||
|
monitor.total(20)
|
||||||
|
monitor.advance(2)
|
||||||
|
now += 2
|
||||||
|
monitor._write_sample()
|
||||||
|
first = json.loads(path.read_text())
|
||||||
|
assert first["eta_s"] is None
|
||||||
|
assert first["tasks"] is None and first["cluster"] is None
|
||||||
|
monitor.advance(4)
|
||||||
|
now += 2
|
||||||
|
monitor._write_sample()
|
||||||
|
assert json.loads(path.read_text())["eta_s"] == pytest.approx(14 / (0.3 * 2 + 0.7))
|
||||||
|
|
||||||
|
|
||||||
|
class _FakeClient:
|
||||||
|
"""A stand-in for a Dask client with one busy worker, whose status the test can flip."""
|
||||||
|
|
||||||
|
status = "running"
|
||||||
|
|
||||||
|
def scheduler_info(self):
|
||||||
|
return {"workers": {"tcp://w:1": {"name": "w", "nthreads": 1, "memory_limit": 1000,
|
||||||
|
"metrics": {"cpu": 90.0, "memory": 500, "executing": 1}}}}
|
||||||
|
|
||||||
|
|
||||||
|
def _wait_for(path, condition, seconds=5.0):
|
||||||
|
"""The last snapshot at `path` once `condition(snapshot)` holds, or fail after `seconds`."""
|
||||||
|
deadline = time.monotonic() + seconds
|
||||||
|
while time.monotonic() < deadline:
|
||||||
|
if path.exists():
|
||||||
|
snapshot = json.loads(path.read_text())
|
||||||
|
if condition(snapshot):
|
||||||
|
return snapshot
|
||||||
|
time.sleep(0.02)
|
||||||
|
raise AssertionError(f"no snapshot matched: {path.read_text() if path.exists() else 'no file'}")
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_cluster_figures_clear_when_the_client_is_released(tmp_path):
|
||||||
|
"""Pin that `release` drops the cluster and task figures from every later snapshot, including the final one.
|
||||||
|
Fail if a finished run keeps reporting its last CPU, RAM and task counts as if the cluster were still busy."""
|
||||||
|
path = tmp_path / "progress.json"
|
||||||
|
monitor = run_monitor.RunMonitor(tmp_path, interval=0.02)
|
||||||
|
monitor.start(_FakeClient(), ("local", None))
|
||||||
|
busy = _wait_for(path, lambda s: s["cluster"] and s["cluster"]["cpu_pct"] == 90.0)
|
||||||
|
assert busy["cluster"]["workers"][0]["name"] == "w"
|
||||||
|
monitor.release()
|
||||||
|
cleared = _wait_for(path, lambda s: s["cluster"] is None)
|
||||||
|
assert cleared["tasks"] is None
|
||||||
|
monitor.stop()
|
||||||
|
final = json.loads(path.read_text())
|
||||||
|
assert final["cluster"] is None and final["tasks"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_cluster_figures_clear_when_the_sampler_sees_a_closed_client(tmp_path):
|
||||||
|
"""Pin that a client closed without a `release` call still stops being reported on the next sample.
|
||||||
|
Fail if the sampler goes on writing the last figures of a client whose status is closed."""
|
||||||
|
path = tmp_path / "progress.json"
|
||||||
|
client = _FakeClient()
|
||||||
|
monitor = run_monitor.RunMonitor(tmp_path, interval=0.02)
|
||||||
|
monitor.start(client, ("remote", "tcp://s:1"))
|
||||||
|
_wait_for(path, lambda s: s["cluster"] and s["cluster"]["scheduler"] == "tcp://s:1")
|
||||||
|
client.status = "closed"
|
||||||
|
_wait_for(path, lambda s: s["cluster"] is None and s["tasks"] is None)
|
||||||
|
monitor.stop()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_client_attached_later_is_reported_again(tmp_path):
|
||||||
|
"""Pin that releasing one client does not stop the next one (a run opens a cluster per phase) from reporting.
|
||||||
|
Fail if `release` leaves the monitor unable to take a new client."""
|
||||||
|
path = tmp_path / "progress.json"
|
||||||
|
monitor = run_monitor.RunMonitor(tmp_path, interval=0.02)
|
||||||
|
first = _FakeClient()
|
||||||
|
monitor.start(first, ("local", None))
|
||||||
|
_wait_for(path, lambda s: s["cluster"] is not None)
|
||||||
|
monitor.release(first)
|
||||||
|
_wait_for(path, lambda s: s["cluster"] is None)
|
||||||
|
monitor.start(_FakeClient(), ("local", None))
|
||||||
|
_wait_for(path, lambda s: s["cluster"] is not None and s["cluster"]["cpu_pct"] == 90.0)
|
||||||
|
monitor.stop()
|
||||||
Reference in New Issue
Block a user