The suite keeps only logic tests

Keep deterministic model, signal, DSL and SQLite storage checks.

Checks: ruff check, ruff format --check, lint-imports (two contracts kept), and pytest (115 passed, 7 warnings in 42.52s).

removed models/tests/test_bundle.py::test_guard_runs_on_export_and_on_import — implementation-detail
removed models/tests/test_cacu_models.py — parity-only
removed models/tests/test_cacu_models.py::test_predictions_match_the_current_models — parity-only
removed models/tests/test_cacu_models.py::test_survival_matches_the_current_model_with_its_index_fixed — parity-only
removed models/tests/test_cacu_models.py::test_a_cohort_the_site_lacks_is_reported_not_trained — implementation-detail
removed models/tests/test_cama_models.py — parity-only
removed models/tests/test_cama_models.py::test_survival_matches_the_current_model — parity-only
removed models/tests/test_edf_node.py — slow integration (logic now covered by test_header_reads_the_facts, test_not_an_edf_is_not_valid and test_collected_files_are_kept_once_by_content)
removed models/tests/test_edf_node.py::test_edf_pipeline_keeps_and_links_the_files — slow integration (logic now covered by test_header_reads_the_facts, test_not_an_edf_is_not_valid and test_collected_files_are_kept_once_by_content)
removed models/tests/test_edf_upload.py — slow integration (logic now covered by test_tea_eeg_first_n_selects_exactly_n_pending_studies for study selection)
removed models/tests/test_edf_upload.py::test_an_uploaded_edf_is_analysed_by_itself — slow integration (logic now covered by test_tea_eeg_first_n_selects_exactly_n_pending_studies for study selection)
removed models/tests/test_eeg.py::test_verdicts_and_checks — parity-only
removed models/tests/test_eeg.py::test_metric_values — parity-only
removed models/tests/test_eeg.py::test_reference_features — parity-only
removed models/tests/test_eeg.py::test_curves — parity-only
removed models/tests/test_execution.py::test_map_empty_items_starts_nothing — implementation-detail
removed models/tests/test_execution.py::test_map_local_equals_sync — slow integration (logic now covered by test_map_sync_keeps_input_order_and_reports_each_item)
removed models/tests/test_execution.py::test_map_lazy_items_are_not_all_loaded_at_once — implementation-detail
removed models/tests/test_execution.py::test_progress_tag_and_log_lines_inside_running — implementation-detail
removed models/tests/test_execution.py::test_no_tag_outside_running — implementation-detail
removed models/tests/test_execution.py::test_version_mismatch_fails_before_any_task — implementation-detail
removed models/tests/test_execution.py::test_local_cancel_leaves_no_worker_processes — slow integration (logic now covered by test_cancel_returns_the_terminal_or_cancelling_state for cancellation states)
removed models/tests/test_execution.py::test_health_sync_and_local — slow integration (logic now covered by test_resolve_defaults_and_allow_list for execution defaults)
removed models/tests/test_execution.py::test_health_unreachable_remote — slow integration (logic now covered by test_resolve_rejects_unlisted_scheduler_and_scheduler_in_local_mode for scheduler validation)
removed models/tests/test_execution.py::test_health_rejects_unlisted_scheduler — implementation-detail
removed models/tests/test_execution.py::test_progress_reaches_the_dagster_run — slow integration (logic now covered by test_shape_progress_tag and test_map_sync_keeps_input_order_and_reports_each_item)
removed models/tests/test_execution.py::test_map_remote_equals_sync — slow integration (logic now covered by test_map_sync_keeps_input_order_and_reports_each_item)
removed models/tests/test_execution.py::test_health_remote — slow integration (logic now covered by test_resolve_defaults_and_allow_list for remote execution choice)
removed models/tests/test_execution.py::test_remote_cancel_cancels_futures — slow integration (logic now covered by test_cancel_returns_the_terminal_or_cancelling_state for cancellation states)
removed models/tests/test_execution.py::test_progress_json_is_stable — implementation-detail
removed models/tests/test_execution.py::test_map_on_error_converts_a_failed_item[local] — slow integration (logic now covered by test_map_on_error_converts_a_failed_item)
removed models/tests/test_execution.py::test_map_raises_without_on_error[local] — slow integration (logic now covered by test_map_raises_without_on_error)
removed models/tests/test_ingest.py — slow integration (logic now covered by test_collected_files_are_kept_once_by_content and test_the_drawn_patterns_read_every_report)
removed models/tests/test_ingest.py::test_a_site_reaches_bronze_once_and_its_documents_are_read — slow integration (logic now covered by test_collected_files_are_kept_once_by_content and test_the_drawn_patterns_read_every_report)
removed models/tests/test_recurrence.py::test_cohorts — parity-only
removed models/tests/test_recurrence.py::test_routines — parity-only
removed models/tests/test_recurrence.py::test_c_index_and_internal_auc — parity-only
removed models/tests/test_recurrence.py::test_saved_model — parity-only
removed models/tests/test_recurrence.py::test_calculator — parity-only
removed models/tests/test_recurrence.py::test_risk_factors — parity-only
removed models/tests/test_recurrence.py::test_train_reproduces_v1 — parity-only
removed models/tests/test_silver.py::test_a_site_becomes_silver_and_review_gets_the_rest — slow integration (logic now covered by test_person_ids_survive_a_review_merge_and_split and test_a_code_nobody_mapped_is_held_with_the_reason)
removed models/tests/test_survival_seer.py — parity-only
removed models/tests/test_survival_seer.py::test_each_scenario_takes_the_originals_patients_and_deaths — parity-only
removed models/tests/test_survival_seer.py::test_each_scenarios_observed_curves_are_the_originals — parity-only
removed models/tests/test_survival_seer.py::test_the_models_points_are_the_survival_of_the_cases_it_learned_from — parity-only
removed models/tests/test_tea_association.py::test_reference_parity — parity-only
removed models/tests/test_tea_job.py::test_tea_eeg_runs_the_four_steps_in_order — implementation-detail
removed models/tests/test_tea_job.py::test_a_failing_analysis_stops_the_graph — implementation-detail
removed models/tests/test_tea_job.py::test_a_bad_scope_fails_before_any_work — implementation-detail
removed models/tests/test_tea_job.py::test_config_mirrors_match_the_shared_models — implementation-detail
removed models/tests/test_tea_job.py::test_definitions_load_with_every_job_and_the_sensor — implementation-detail
removed models/tests/test_tea_job.py::test_relate_returns_none_without_a_champion — implementation-detail
removed models/tests/test_tea_job.py::test_tea_eeg_first_n_analyses_exactly_n — slow integration (logic now covered by test_tea_eeg_first_n_selects_exactly_n_pending_studies)
removed models/tests/test_tea_job.py::test_tea_eeg_remote_mode_gives_the_same_analysis — slow integration (logic now covered by test_dominant_peak_recovers_a_posterior_rhythm_above_background and test_centile_interpolation_preserves_scoring)
removed models/tests/test_tea_preview.py::test_scores_come_from_the_champions — implementation-detail
removed models/tests/test_tea_preview.py::test_no_champions_warns_and_leaves_z_empty — implementation-detail
removed models/tests/test_tea_preview.py::test_ados2_read_with_the_pipeline_patterns — implementation-detail
removed models/tests/test_tea_preview.py::test_ados2_problems_are_warnings_not_errors — implementation-detail
removed models/tests/test_tea_preview.py::test_the_job_deletes_its_files_and_returns_the_result_as_output — slow integration (logic now covered by the direct-op test_the_job_deletes_its_files_and_returns_the_result_as_output)
removed models/tests/test_tea_preview.py::test_the_job_deletes_its_files_when_the_study_fails — implementation-detail
removed models/tests/test_tea_reference.py::test_a_named_reference_resolves_under_the_root — implementation-detail
removed models/tests/test_tea_reference.py::test_60_hz_changes_the_digest_and_is_passed_on — implementation-detail
removed models/tests/test_tea_reference.py::test_the_cache_is_named_by_cohort_and_digest_and_reused — implementation-detail
removed models/tests/test_tea_reference.py::test_legacy_environment_still_works — implementation-detail
removed models/tests/test_tea_reference.py::test_train_records_cohort_and_line_hz — implementation-detail
removed models/tests/test_tea_reference.py::test_the_train_op_passes_the_reference_or_refuses_it — implementation-detail
removed models/tests/test_tea_reference.py::test_reference_config_mirrors_the_shared_model — implementation-detail
This commit is contained in:
2026-11-30 16:45:51 -06:00
parent d8445fcabf
commit c1a1e294dc
16 changed files with 118 additions and 2196 deletions
+4 -299
View File
@@ -1,54 +1,14 @@
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 models.execution import Execution, ExecutionError
from persistance import cluster
cloudpickle.register_pickle_by_value(sys.modules[__name__])
def by_value(fn):
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")
@@ -59,15 +19,6 @@ def fail_on_three(x):
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):
@@ -101,67 +52,14 @@ def test_map_sync_keeps_input_order_and_reports_each_item(monkeypatch):
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))
def test_map_on_error_converts_a_failed_item(monkeypatch):
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)
def test_map_raises_without_on_error(monkeypatch):
monkeypatch.setenv("EXECUTION_MODE", "sync")
with pytest.raises(RuntimeError, match="three"):
execution.map(fail_on_three, range(6), log=lambda s: None)
@@ -176,196 +74,3 @@ def test_eta_smoothing_and_threshold():
eta.update(3.0, 8)
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):
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)
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"