Files
models/tests/tea/test_run_monitor.py

164 lines
6.9 KiB
Python

"""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()