execution.map runs a heavy op's items in this process, on local workers or on a Dask scheduler, and reports progress on the run

This commit is contained in:
2026-11-27 17:19:55 -06:00
parent 3546269eaf
commit 9220b8c52c
2 changed files with 784 additions and 0 deletions
+404
View File
@@ -0,0 +1,404 @@
"""The one way a heavy op spreads work over cores or machines: `map(fn, items)` returns the
results in input order whatever the mode (in this process, on local worker processes, on a
remote Dask scheduler). While it runs, a monitor thread reports progress: a JSON run tag the
API reads at once (Dagster shows op metadata only when the op returns, so the tag is the live
channel) and one throttled log line per tenth of the work. Ops never touch Dask themselves.
`with running(context, execution):` makes a Dagster op's context the ambient one, so that
`map` calls inside the block report on that run, share one cluster, and leave a summary in the
op's output metadata."""
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:
"""Seconds left, from an exponentially smoothed rate of items per second."""
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:
"""What `running` shares with the `map` calls in its block."""
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:
"""Close what this module opened; a remote scheduler is only disconnected from."""
for closable in (client, local_cluster):
if closable is not None:
try:
closable.close()
except Exception:
pass
def _counts(dask_scheduler) -> dict:
"""Run on the scheduler: how many tasks are in each state."""
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):
"""A client on the chosen Dask cluster and the local cluster it started, if any."""
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:
"""Samples one `map` every `SAMPLE_S` seconds and reports it."""
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 # a failed sample keeps the previous one
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 = {} # future -> (index, item)
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 - the module's public name, as in `execution.map`
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]:
"""Apply `fn` to every item and return the results in input order.
`fn` is a module-level function of one item returning something picklable, and must give
the same result for the same item: then every mode returns equal lists. `items` may be a
lazy generator; at most `max(4, 2 * threads)` items are loaded and unfinished at once.
`total` is needed only when `items` has no length. `phase` is the lowercase code the
WebApp shows. `workers` overrides the local worker count (a cluster shared inside
`running` keeps the count it started with). A failed item takes `on_error(item, error)`
as its result, or, without it, the error propagates after the rest is cancelled."""
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]:
"""Make `context` and `execution` the ambient ones for the `map` calls in the block; on
exit close the shared cluster and leave the run's figures in the op's output metadata."""
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
+380
View File
@@ -0,0 +1,380 @@
"""`execution.map` returns the same list in every mode, spreads lazy input without loading it
all, fails fast when the cluster is wrong, cleans up after a cancel, and reports progress on
the Dagster run. Remote tests need a scheduler: set `DASK_TEST_SCHEDULER` and
`DASK_EXPECTED_WORKERS` (the compose `test` profile does)."""
import json
import os
import signal
import subprocess
import sys
import textwrap
import threading
import time
from types import SimpleNamespace
import cloudpickle
import dagster as dg
import numpy as np
import psutil
import pytest
from models import execution
from models.execution import Execution, ExecutionError, Progress
from persistance import cluster
cloudpickle.register_pickle_by_value(sys.modules[__name__])
def by_value(fn):
"""Mark a worker function so that Dask ships its code, not its name: the scheduler
unpickles task graphs too, and has no test module (Dask wraps `fn` in a task, which
hides the by-value registration above from it)."""
fn.__module__ = "__main__"
return fn
@by_value
def square(x):
return int(x) ** 2
@by_value
def numeric(x):
rng = np.random.default_rng(x)
return float(np.linalg.norm(rng.normal(size=(20, 20)) @ rng.normal(size=(20, 20))))
@by_value
def slow(x):
time.sleep(0.2)
return x
@by_value
def sleep_forever(x):
time.sleep(60)
@by_value
def fail_on_three(x):
if x == 3:
raise RuntimeError("three")
return x
@pytest.fixture(autouse=True)
def env(monkeypatch):
for name in ("EXECUTION_MODE", "DASK_SCHEDULERS"):
monkeypatch.delenv(name, raising=False)
monkeypatch.setenv("DASK_LOCAL_WORKERS", "2")
def fake_context():
context = SimpleNamespace(run_id="r1", logs=[], tags=[], metadata=[])
context.log = SimpleNamespace(info=context.logs.append)
context.instance = SimpleNamespace(add_run_tags=lambda run, tags: context.tags.append(tags))
context.add_output_metadata = context.metadata.append
return context
def test_resolve_defaults_and_allow_list(monkeypatch):
assert execution.resolve().mode == "local"
monkeypatch.setenv("EXECUTION_MODE", "sync")
assert execution.resolve().mode == "sync"
with pytest.raises(ExecutionError):
execution.resolve(Execution(mode="remote"))
monkeypatch.setenv("DASK_SCHEDULERS", "a:8786,tcp://b:8786")
assert execution.resolve(Execution(mode="remote")).scheduler == "tcp://a:8786"
assert execution.resolve(Execution(mode="remote", scheduler="b:8786")).scheduler == (
"tcp://b:8786"
)
assert execution.options().schedulers == ["tcp://a:8786", "tcp://b:8786"]
def test_resolve_rejects_unlisted_scheduler_and_scheduler_in_local_mode(monkeypatch):
monkeypatch.setenv("DASK_SCHEDULERS", "a:8786")
with pytest.raises(ExecutionError, match="not in DASK_SCHEDULERS"):
execution.resolve(Execution(mode="remote", scheduler="c:8786"))
with pytest.raises(ExecutionError, match="only goes with remote"):
execution.resolve(Execution(mode="local", scheduler="a:8786"))
with pytest.raises(ExecutionError, match="not host:port"):
cluster.normalize("http://a:1")
def test_map_sync_keeps_input_order_and_reports_each_item(monkeypatch):
monkeypatch.setenv("EXECUTION_MODE", "sync")
lines = []
assert execution.map(square, range(5), log=lines.append) == [0, 1, 4, 9, 16]
assert lines[0] == "working: 0/5" and lines[-1] == "working: 5/5"
def test_map_empty_items_starts_nothing(monkeypatch):
import distributed
def boom(*a, **k):
raise AssertionError("a cluster was started")
monkeypatch.setattr(distributed, "LocalCluster", boom)
assert execution.map(square, []) == []
assert execution.map(square, iter([]), total=0) == []
def test_map_local_equals_sync(monkeypatch):
items = list(range(12))
monkeypatch.setenv("EXECUTION_MODE", "sync")
expected = execution.map(numeric, items, log=lambda s: None)
monkeypatch.setenv("EXECUTION_MODE", "local")
assert execution.map(numeric, items, log=lambda s: None) == expected
def test_map_lazy_items_are_not_all_loaded_at_once():
state = {"loaded": 0, "finished": 0, "peak": 0}
lock = threading.Lock()
def generate():
for i in range(30):
with lock:
state["loaded"] += 1
state["peak"] = max(state["peak"], state["loaded"] - state["finished"])
yield i
class Counting:
def __init__(self):
self.n = 0
out = []
real = execution._Monitor.item_done
def item_done(self):
with lock:
state["finished"] += 1
real(self)
execution._Monitor.item_done = item_done
try:
out = execution.map(slow, generate(), total=30, log=lambda s: None)
finally:
execution._Monitor.item_done = real
assert out == list(range(30))
assert state["peak"] <= max(4, 2 * 2)
@pytest.mark.parametrize("mode", ["sync", "local"])
def test_map_on_error_converts_a_failed_item(monkeypatch, mode):
monkeypatch.setenv("EXECUTION_MODE", mode)
out = execution.map(fail_on_three, range(6), on_error=lambda item, e: -item, log=lambda s: None)
assert out == [0, 1, 2, -3, 4, 5]
@pytest.mark.parametrize("mode", ["sync", "local"])
def test_map_raises_without_on_error(monkeypatch, mode):
monkeypatch.setenv("EXECUTION_MODE", mode)
with pytest.raises(RuntimeError, match="three"):
execution.map(fail_on_three, range(6), log=lambda s: None)
def test_eta_smoothing_and_threshold():
eta = execution.Eta(alpha=0.3, min_done=3)
eta.update(0.0, 0)
eta.update(1.0, 2)
assert eta.eta_s(10) is None # fewer than 3 done
eta.update(2.0, 4)
assert eta.eta_s(10) == pytest.approx((10 - 4) / 2.0)
eta.update(3.0, 8) # a faster burst: 4 items/s
assert eta.rate == pytest.approx(0.3 * 4 + 0.7 * 2.0)
assert eta.eta_s(10) == pytest.approx(2 / eta.rate)
def test_progress_tag_and_log_lines_inside_running(monkeypatch):
monkeypatch.setenv("EXECUTION_MODE", "sync")
context = fake_context()
with execution.running(context):
execution.map(square, range(6), phase="analyzing")
first, last = (Progress.model_validate_json(t[execution.PROGRESS_TAG]) for t in
(context.tags[0], context.tags[-1])) # fmt: skip
assert first.done == 0 and last.done == last.total == 6 and last.phase == "analyzing"
assert context.logs[0] == "analyzing: 0/6" and context.logs[-1] == "analyzing: 6/6"
summary = context.metadata[-1]
assert set(summary) == {"mode", "scheduler", "phases", "peak_cpu_pct", "peak_memory_bytes"}
def test_no_tag_outside_running(monkeypatch):
monkeypatch.setenv("EXECUTION_MODE", "sync")
context = fake_context()
execution.map(square, range(3), log=context.logs.append)
assert context.tags == [] and context.logs
def test_version_mismatch_fails_before_any_task(monkeypatch):
import distributed
monkeypatch.setenv("DASK_SCHEDULERS", "x:8786")
submitted = []
class SpyClient:
def __init__(self, *a, **k):
self.closed = False
def submit(self, *a, **k):
submitted.append(a)
def close(self):
self.closed = True
monkeypatch.setattr(distributed, "Client", SpyClient)
monkeypatch.setattr(cluster, "versions_error", lambda client: "numpy 1.0 vs 2.0")
with pytest.raises(execution.ClusterVersionError, match="numpy 1.0 vs 2.0"):
execution.map(square, range(3), execution=Execution(mode="remote"))
assert submitted == []
CANCEL_SCRIPT = textwrap.dedent(
"""
import signal, sys
from models import execution
from models.execution import Execution
def stop(*a):
raise KeyboardInterrupt
def sleep_forever(x):
import time
time.sleep(60)
signal.signal(signal.SIGTERM, stop)
import cloudpickle
cloudpickle.register_pickle_by_value(sys.modules["__main__"])
execution.map(sleep_forever, range({n}), log=lambda s: print(s, flush=True),
execution=Execution(mode="{mode}"))
"""
)
def run_cancelled(mode, n):
"""Start a `map` of sleepers in a subprocess, send SIGTERM after its first line."""
proc = subprocess.Popen(
[sys.executable, "-c", CANCEL_SCRIPT.format(n=n, mode=mode)],
stdout=subprocess.PIPE,
text=True,
env={**os.environ, "DASK_LOCAL_WORKERS": "2"},
)
assert proc.stdout.readline().startswith("working: 0/")
time.sleep(3) # the cluster is up and the tasks are submitted
return proc
def test_local_cancel_leaves_no_worker_processes():
proc = run_cancelled("local", 4)
children = psutil.Process(proc.pid).children(recursive=True)
assert children
proc.send_signal(signal.SIGTERM)
proc.wait(timeout=30)
deadline = time.time() + 20
while time.time() < deadline and any(c.is_running() and c.status() != "zombie"
for c in children): # fmt: skip
time.sleep(0.5)
assert not [c for c in children if c.is_running() and c.status() != "zombie"]
def test_health_sync_and_local(monkeypatch):
sync = execution.health(Execution(mode="sync"))
assert sync.reachable and sync.workers == 1 and sync.threads == 1
local = execution.health(Execution(mode="local"))
assert local.reachable and local.workers == 2 and local.versions_ok is None
def test_health_unreachable_remote(monkeypatch):
monkeypatch.setenv("DASK_SCHEDULERS", "tcp://127.0.0.1:1")
started = time.time()
h = execution.health(Execution(mode="remote"))
assert not h.reachable and h.error and time.time() - started < 15
def test_health_rejects_unlisted_scheduler(monkeypatch):
monkeypatch.setenv("DASK_SCHEDULERS", "tcp://127.0.0.1:1")
with pytest.raises(ExecutionError):
execution.health(Execution(mode="remote", scheduler="tcp://127.0.0.1:2"))
with pytest.raises(ExecutionError):
execution.health(Execution(mode="sync"), reference="../x")
def test_progress_reaches_the_dagster_run():
@dg.op
def analyze(context) -> dg.Nothing:
with execution.running(context, Execution(mode="sync")):
execution.map(square, range(6), phase="analyzing")
@dg.op(ins={"start": dg.In(dg.Nothing)})
def after(context):
pass
@dg.job
def two():
after(analyze())
instance = dg.DagsterInstance.ephemeral()
result = two.execute_in_process(instance=instance)
assert result.success
tags = instance.get_run_by_id(result.run_id).tags
progress = Progress.model_validate_json(tags[execution.PROGRESS_TAG])
assert (progress.done, progress.total, progress.phase) == (6, 6, "analyzing")
event = next(e for e in result.events_for_node("analyze") if e.is_successful_output)
assert "mode" in event.event_specific_data.metadata
@pytest.fixture(scope="module")
def scheduler():
address = os.environ.get("DASK_TEST_SCHEDULER")
if not address:
pytest.skip("DASK_TEST_SCHEDULER is not set")
expected = int(os.environ["DASK_EXPECTED_WORKERS"])
os.environ["DASK_SCHEDULERS"] = address
deadline = time.time() + 60
while time.time() < deadline:
if execution.health(Execution(mode="remote", scheduler=address)).workers == expected:
return cluster.normalize(address)
time.sleep(1)
pytest.fail(f"the scheduler never showed {expected} workers")
def test_map_remote_equals_sync(scheduler, monkeypatch):
monkeypatch.setenv("DASK_SCHEDULERS", scheduler)
items = list(range(12))
expected = execution.map(numeric, items, execution=Execution(mode="sync"), log=print)
remote = execution.map(numeric, items, execution=Execution(mode="remote"), log=print)
assert remote == expected
def test_health_remote(scheduler, monkeypatch):
monkeypatch.setenv("DASK_SCHEDULERS", scheduler)
h = execution.health(Execution(mode="remote"))
assert h.reachable and h.workers == h.expected_workers == 2
assert h.versions_ok and h.latency_ms > 0 and h.dashboard_ok
def test_remote_cancel_cancels_futures(scheduler, monkeypatch):
from distributed import Client
monkeypatch.setenv("DASK_SCHEDULERS", scheduler)
proc = run_cancelled("remote", 8)
proc.send_signal(signal.SIGTERM)
proc.wait(timeout=30)
with Client(scheduler, timeout=10) as client:
deadline = time.time() + 20
processing = None
while time.time() < deadline:
processing = client.run_on_scheduler(execution._counts).get("processing", 0)
if processing == 0:
break
time.sleep(0.5)
assert processing == 0
assert client.scheduler_info()["workers"]
def test_progress_json_is_stable(monkeypatch):
monkeypatch.setenv("EXECUTION_MODE", "sync")
context = fake_context()
with execution.running(context):
execution.map(square, range(2))
assert json.loads(context.tags[-1][execution.PROGRESS_TAG])["mode"] == "sync"