d8445fcabf
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.
375 lines
12 KiB
Python
375 lines
12 KiB
Python
import contextvars
|
|
import threading
|
|
import time
|
|
from collections.abc import Callable, Iterable, Iterator
|
|
from contextlib import contextmanager
|
|
from datetime import UTC, datetime
|
|
from itertools import islice
|
|
|
|
import dagster as dg
|
|
import psutil
|
|
|
|
from persistance import cluster
|
|
from persistance.cluster import (
|
|
PROGRESS_TAG,
|
|
ClusterVersionError,
|
|
Execution,
|
|
ExecutionError,
|
|
Health,
|
|
Options,
|
|
Progress,
|
|
Resolved,
|
|
Tasks,
|
|
Worker,
|
|
health,
|
|
options,
|
|
resolve,
|
|
)
|
|
|
|
__all__ = [
|
|
"ClusterVersionError",
|
|
"Execution",
|
|
"ExecutionError",
|
|
"Health",
|
|
"Options",
|
|
"Progress",
|
|
"Resolved",
|
|
"health",
|
|
"map",
|
|
"options",
|
|
"resolve",
|
|
"running",
|
|
]
|
|
|
|
SAMPLE_S = 2.0
|
|
_SINGLE_THREAD = {
|
|
"OMP_NUM_THREADS": "1",
|
|
"OPENBLAS_NUM_THREADS": "1",
|
|
"MKL_NUM_THREADS": "1",
|
|
}
|
|
|
|
|
|
class Eta:
|
|
def __init__(self, alpha: float = 0.3, min_done: int = 3):
|
|
self.alpha, self.min_done = alpha, min_done
|
|
self.rate: float | None = None
|
|
self._last: tuple[float, int] | None = None
|
|
|
|
def update(self, elapsed_s: float, done: int) -> None:
|
|
last, self._last = self._last, (elapsed_s, done)
|
|
if last is None or elapsed_s <= last[0]:
|
|
return
|
|
rate = (done - last[1]) / (elapsed_s - last[0])
|
|
self.rate = rate if self.rate is None else self.alpha * rate + (1 - self.alpha) * self.rate
|
|
|
|
def eta_s(self, total: int) -> float | None:
|
|
done = self._last[1] if self._last else 0
|
|
if done < self.min_done or not self.rate or self.rate <= 0:
|
|
return None
|
|
return max(0, total - done) / self.rate
|
|
|
|
|
|
class _Ambient:
|
|
def __init__(self, context, execution: Execution | None):
|
|
self.context, self.execution = context, execution
|
|
self.client = None
|
|
self.cluster = None
|
|
self.phases: list[dict] = []
|
|
self.peak_cpu_pct = 0.0
|
|
self.peak_memory_bytes = 0
|
|
|
|
def close(self) -> None:
|
|
_close(self.client, self.cluster)
|
|
self.client = self.cluster = None
|
|
|
|
|
|
_ambient: contextvars.ContextVar[_Ambient | None] = contextvars.ContextVar(
|
|
"execution_ambient", default=None
|
|
)
|
|
|
|
|
|
def _close(client, local_cluster) -> None:
|
|
for closable in (client, local_cluster):
|
|
if closable is not None:
|
|
try:
|
|
closable.close()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _counts(dask_scheduler) -> dict:
|
|
counts: dict = {}
|
|
for task in dask_scheduler.tasks.values():
|
|
counts[task.state] = counts.get(task.state, 0) + 1
|
|
return counts
|
|
|
|
|
|
def _connect(resolved: Resolved, workers: int | None):
|
|
from distributed import Client, LocalCluster
|
|
|
|
if resolved.mode == "local":
|
|
local = LocalCluster(
|
|
n_workers=cluster.local_workers(workers),
|
|
threads_per_worker=1,
|
|
processes=True,
|
|
memory_limit=cluster.memory_per_worker(),
|
|
dashboard_address=None,
|
|
env=_SINGLE_THREAD,
|
|
)
|
|
try:
|
|
return Client(local), local
|
|
except BaseException:
|
|
_close(None, local)
|
|
raise
|
|
try:
|
|
client = Client(resolved.scheduler, timeout=10)
|
|
except Exception as e:
|
|
raise ExecutionError(f"cannot reach the Dask scheduler {resolved.scheduler}: {e}") from e
|
|
detail = cluster.versions_error(client)
|
|
if detail is not None:
|
|
_close(client, None)
|
|
raise ClusterVersionError(
|
|
f"Dask workers differ from this server: {detail}. "
|
|
"Rebuild the worker image from the same commit."
|
|
)
|
|
return client, None
|
|
|
|
|
|
class _Monitor:
|
|
def __init__(self, ambient, resolved, phase, total, log, client):
|
|
self.ambient, self.resolved, self.phase = ambient, resolved, phase
|
|
self.total, self.log, self.client = total, log, client
|
|
self.done = 0
|
|
self.started = time.monotonic()
|
|
self.eta = Eta()
|
|
self.tasks: Tasks | None = None
|
|
self.last_tenth = 0
|
|
self.peak_cpu = 0.0
|
|
self.peak_memory = 0
|
|
self._lock = threading.Lock()
|
|
self._stop = threading.Event()
|
|
self._thread = threading.Thread(target=self._loop, daemon=True)
|
|
self._process = psutil.Process()
|
|
|
|
def item_done(self) -> None:
|
|
with self._lock:
|
|
self.done += 1
|
|
|
|
def start(self) -> None:
|
|
self.report(force_log=True)
|
|
self._thread.start()
|
|
|
|
def stop(self, *, final: bool) -> None:
|
|
self._stop.set()
|
|
self._thread.join()
|
|
if final:
|
|
self.report(force_log=True)
|
|
|
|
def _loop(self) -> None:
|
|
while not self._stop.wait(SAMPLE_S):
|
|
self.report()
|
|
|
|
def _cluster_state(self) -> list[Worker]:
|
|
if self.client is None:
|
|
cpu = self._process.cpu_percent()
|
|
self.peak_cpu = max(self.peak_cpu, cpu)
|
|
self.peak_memory = max(self.peak_memory, self._process.memory_info().rss)
|
|
return []
|
|
workers = []
|
|
try:
|
|
info = self.client.scheduler_info()["workers"]
|
|
for w in info.values():
|
|
m = w.get("metrics", {})
|
|
workers.append(
|
|
Worker(
|
|
name=str(w.get("name", "")),
|
|
cpu_pct=float(m.get("cpu", 0.0)),
|
|
memory_bytes=int(m.get("memory", 0)),
|
|
memory_limit=w.get("memory_limit"),
|
|
executing=int(m.get("executing", 0)),
|
|
threads=int(w.get("nthreads", 1)),
|
|
)
|
|
)
|
|
except Exception:
|
|
return []
|
|
try:
|
|
counts = self.client.run_on_scheduler(_counts)
|
|
self.tasks = Tasks(**{k: counts.get(k, 0) for k in Tasks.model_fields})
|
|
except Exception:
|
|
pass
|
|
self.peak_cpu = max(self.peak_cpu, sum(w.cpu_pct for w in workers))
|
|
self.peak_memory = max(self.peak_memory, sum(w.memory_bytes for w in workers))
|
|
return workers
|
|
|
|
def report(self, *, force_log: bool = False) -> None:
|
|
workers = self._cluster_state()
|
|
with self._lock:
|
|
done = self.done
|
|
elapsed = time.monotonic() - self.started
|
|
self.eta.update(elapsed, done)
|
|
progress = Progress(
|
|
phase=self.phase,
|
|
done=done,
|
|
total=self.total,
|
|
elapsed_s=round(elapsed, 1),
|
|
eta_s=self.eta.eta_s(self.total),
|
|
mode=self.resolved.mode,
|
|
scheduler=self.resolved.scheduler,
|
|
workers=workers,
|
|
tasks=self.tasks,
|
|
updated_at=datetime.now(UTC).isoformat(timespec="seconds"),
|
|
)
|
|
tenth = done * 10 // self.total
|
|
if force_log or tenth > self.last_tenth:
|
|
self.last_tenth = tenth
|
|
self.log(f"{self.phase}: {done}/{self.total}")
|
|
context = self.ambient.context if self.ambient else None
|
|
if context is not None:
|
|
context.instance.add_run_tags(
|
|
context.run_id, {PROGRESS_TAG: progress.model_dump_json()}
|
|
)
|
|
|
|
|
|
def _default_log(ambient) -> Callable[[str], None]:
|
|
return ambient.context.log.info if ambient and ambient.context else print
|
|
|
|
|
|
def _run_sync(fn, iterator, monitor, on_error):
|
|
results = []
|
|
for item in iterator:
|
|
try:
|
|
results.append(fn(item))
|
|
except Exception as e:
|
|
if on_error is None:
|
|
raise
|
|
results.append(on_error(item, e))
|
|
monitor.item_done()
|
|
return results
|
|
|
|
|
|
def _run_dask(fn, iterator, client, monitor, on_error):
|
|
from distributed import as_completed
|
|
|
|
threads = sum(w["nthreads"] for w in client.scheduler_info()["workers"].values()) or 1
|
|
limit = max(4, 2 * threads)
|
|
results: dict[int, object] = {}
|
|
pending: dict = {}
|
|
completed = as_completed([])
|
|
numbered = enumerate(iterator)
|
|
try:
|
|
while True:
|
|
for index, item in islice(numbered, max(0, limit - len(pending))):
|
|
future = client.submit(fn, item, pure=False, retries=1)
|
|
pending[future] = (index, item)
|
|
completed.add(future)
|
|
if not pending:
|
|
break
|
|
future = next(completed)
|
|
index, item = pending.pop(future)
|
|
try:
|
|
results[index] = future.result()
|
|
except Exception as e:
|
|
if on_error is None:
|
|
raise
|
|
results[index] = on_error(item, e)
|
|
monitor.item_done()
|
|
except BaseException:
|
|
try:
|
|
client.cancel(list(pending), force=True)
|
|
except Exception:
|
|
pass
|
|
raise
|
|
return [results[i] for i in range(len(results))]
|
|
|
|
|
|
def map[T, R]( # noqa: A001
|
|
fn: Callable[[T], R],
|
|
items: Iterable[T],
|
|
*,
|
|
execution: Execution | None = None,
|
|
log: Callable[[str], None] | None = None,
|
|
phase: str = "working",
|
|
total: int | None = None,
|
|
workers: int | None = None,
|
|
on_error: Callable[[T, Exception], R] | None = None,
|
|
) -> list[R]:
|
|
ambient = _ambient.get()
|
|
if execution is None and ambient is not None:
|
|
execution = ambient.execution
|
|
resolved = resolve(execution)
|
|
log = log or _default_log(ambient)
|
|
if total is None:
|
|
try:
|
|
total = len(items) # type: ignore[arg-type]
|
|
except TypeError:
|
|
raise ValueError("total is needed when items has no length") from None
|
|
iterator = iter(items)
|
|
if total == 0:
|
|
return []
|
|
monitor = None
|
|
client, local = (ambient.client, None) if ambient else (None, None)
|
|
opened_here = False
|
|
ok = False
|
|
try:
|
|
if resolved.mode != "sync" and client is None:
|
|
client, local = _connect(resolved, workers)
|
|
if ambient is not None:
|
|
ambient.client, ambient.cluster = client, local
|
|
else:
|
|
opened_here = True
|
|
monitor = _Monitor(ambient, resolved, phase, total, log, client)
|
|
monitor.start()
|
|
if resolved.mode == "sync":
|
|
results = _run_sync(fn, iterator, monitor, on_error)
|
|
else:
|
|
results = _run_dask(fn, iterator, client, monitor, on_error)
|
|
ok = True
|
|
return results
|
|
finally:
|
|
if monitor is not None:
|
|
monitor.stop(final=ok)
|
|
if ambient is not None:
|
|
ambient.phases.append(
|
|
{
|
|
"phase": phase,
|
|
"done": monitor.done,
|
|
"total": total,
|
|
"elapsed_s": round(time.monotonic() - monitor.started, 1),
|
|
}
|
|
)
|
|
ambient.peak_cpu_pct = max(ambient.peak_cpu_pct, monitor.peak_cpu)
|
|
ambient.peak_memory_bytes = max(ambient.peak_memory_bytes, monitor.peak_memory)
|
|
if opened_here:
|
|
_close(client, local)
|
|
|
|
|
|
@contextmanager
|
|
def running(context: dg.OpExecutionContext, execution: Execution | None = None) -> Iterator[None]:
|
|
ambient = _Ambient(context, execution)
|
|
token = _ambient.set(ambient)
|
|
failed = True
|
|
try:
|
|
yield
|
|
failed = False
|
|
finally:
|
|
_ambient.reset(token)
|
|
ambient.close()
|
|
try:
|
|
resolved = resolve(execution)
|
|
context.add_output_metadata(
|
|
{
|
|
"mode": dg.MetadataValue.text(resolved.mode),
|
|
"scheduler": (
|
|
dg.MetadataValue.text(resolved.scheduler)
|
|
if resolved.scheduler
|
|
else dg.MetadataValue.null()
|
|
),
|
|
"phases": dg.MetadataValue.json(ambient.phases),
|
|
"peak_cpu_pct": dg.MetadataValue.float(ambient.peak_cpu_pct),
|
|
"peak_memory_bytes": dg.MetadataValue.int(ambient.peak_memory_bytes),
|
|
}
|
|
)
|
|
except Exception:
|
|
if not failed:
|
|
raise
|