c1a1e294dc
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
221 lines
8.0 KiB
Python
221 lines
8.0 KiB
Python
import hashlib
|
|
import io
|
|
import json
|
|
import zipfile
|
|
|
|
import mlflow
|
|
import pandas as pd
|
|
import pytest
|
|
|
|
from core.domains import Domain
|
|
from persistance import bundle, config, registry
|
|
|
|
DOMAIN = Domain.TEA
|
|
NAME = "tea.curve_x"
|
|
|
|
|
|
class Model(mlflow.pyfunc.PythonModel):
|
|
def __init__(self, value):
|
|
self.value = value
|
|
|
|
def predict(self, context, model_input: pd.DataFrame, params=None):
|
|
return model_input.assign(score=self.value)
|
|
|
|
|
|
@pytest.fixture
|
|
def stores(tmp_path, monkeypatch):
|
|
monkeypatch.setattr(config, "DATA_DIR", tmp_path)
|
|
|
|
def use(name):
|
|
path = tmp_path / name
|
|
path.mkdir(exist_ok=True)
|
|
monkeypatch.setenv("MLFLOW_TRACKING_URI", f"sqlite:///{path}/a.db")
|
|
monkeypatch.chdir(path)
|
|
|
|
use("a")
|
|
return use
|
|
|
|
|
|
def _register(value=1, clinical=True):
|
|
version = registry.register(
|
|
NAME,
|
|
Model(value),
|
|
{"scenario": "curve"},
|
|
{"n_reference": 10},
|
|
{"technical_validation": {"a": 1}, "interpretability": {"b": 2}},
|
|
tags={"source": "test", "bundle.source_version": "stale"},
|
|
)
|
|
if clinical:
|
|
registry.add_report(NAME, version, "clinical_validation", "review.txt", b"approved")
|
|
return version
|
|
|
|
|
|
def _trust(data):
|
|
sha = hashlib.sha256(data).hexdigest()
|
|
with bundle.trusted_file().open("a") as file:
|
|
file.write(f"\n {sha.upper()} \n")
|
|
return sha
|
|
|
|
|
|
def _entries(data):
|
|
with zipfile.ZipFile(io.BytesIO(data)) as archive:
|
|
return {name: archive.read(name) for name in archive.namelist()}
|
|
|
|
|
|
def _zip(entries):
|
|
stream = io.BytesIO()
|
|
with zipfile.ZipFile(stream, "w") as archive:
|
|
for name, data in entries.items():
|
|
archive.writestr(name, data)
|
|
return stream.getvalue()
|
|
|
|
|
|
def test_export_is_deterministic(stores):
|
|
registry.promote(NAME, _register())
|
|
first, second = bundle.export(DOMAIN), bundle.export(DOMAIN)
|
|
assert first.data == second.data
|
|
assert first.sha256 == second.sha256 == hashlib.sha256(first.data).hexdigest()
|
|
with zipfile.ZipFile(io.BytesIO(first.data)) as archive:
|
|
assert archive.namelist() == sorted(archive.namelist())
|
|
for info in archive.infolist():
|
|
assert info.date_time == bundle.EPOCH
|
|
assert info.compress_type == zipfile.ZIP_DEFLATED
|
|
assert info.external_attr == 0o644 << 16
|
|
assert info.create_system == 3
|
|
|
|
|
|
def test_layout_and_manifest_hold_every_file_hash(stores):
|
|
_register()
|
|
entries = _entries(bundle.export(DOMAIN, versions="latest").data)
|
|
manifest = json.loads(entries.pop("manifest.json"))
|
|
assert (manifest["format"], manifest["domain"]) == (1, "tea")
|
|
(item,) = manifest["versions"]
|
|
assert (item["name"], item["version"]) == (NAME, 1)
|
|
prefix = "models/tea.curve_x/v1/"
|
|
assert prefix + "meta.json" in entries
|
|
assert prefix + "model/MLmodel" in entries
|
|
assert prefix + "reports/clinical_validation.txt" in entries
|
|
assert item["files"] == {key: hashlib.sha256(data).hexdigest() for key, data in entries.items()}
|
|
meta = json.loads(entries.pop(prefix + "meta.json"))
|
|
content = {key.removeprefix(prefix): data for key, data in entries.items()}
|
|
assert meta["content_sha256"] == item["content_sha256"] == bundle.content_sha256(content)
|
|
|
|
|
|
def test_selection_champion_latest_all(stores):
|
|
for value in (1, 2, 3):
|
|
_register(value)
|
|
with pytest.raises(bundle.Empty, match="nothing to export"):
|
|
bundle.export(DOMAIN)
|
|
registry.promote(NAME, 2)
|
|
assert bundle.export(DOMAIN).versions == [(NAME, 2)]
|
|
assert bundle.export(DOMAIN, ["curve_x"], "latest").versions == [(NAME, 3)]
|
|
assert bundle.export(DOMAIN, versions="all").versions == [(NAME, 1), (NAME, 2), (NAME, 3)]
|
|
with pytest.raises(bundle.BundleError, match="no tea model missing"):
|
|
bundle.export(DOMAIN, ["missing"])
|
|
|
|
|
|
@pytest.mark.parametrize("clinical", [True, False])
|
|
def test_roundtrip_registers_candidates_with_lineage(stores, clinical):
|
|
_register()
|
|
source_version = _register(2, clinical=clinical)
|
|
source = registry.snapshot(NAME, source_version)
|
|
inputs = pd.DataFrame({"value": [0]})
|
|
prediction = mlflow.pyfunc.load_model(f"models:/{NAME}/{source_version}").predict(inputs)
|
|
exported = bundle.export(DOMAIN, versions="latest")
|
|
stores("b")
|
|
_trust(exported.data)
|
|
assert bundle.import_(DOMAIN, exported.data) == bundle.Imported(
|
|
exported.sha256, [(NAME, 1)], []
|
|
)
|
|
target = registry.snapshot(NAME, 1)
|
|
pd.testing.assert_frame_equal(
|
|
mlflow.pyfunc.load_model(f"models:/{NAME}/1").predict(inputs),
|
|
prediction,
|
|
)
|
|
assert target.params == source.params
|
|
assert target.metrics == source.metrics
|
|
assert target.reports == source.reports
|
|
assert target.tags == {
|
|
"source": "test",
|
|
"bundle.sha256": exported.sha256,
|
|
"bundle.source_name": NAME,
|
|
"bundle.source_version": "2",
|
|
"bundle.content_sha256": json.loads(_entries(exported.data)["manifest.json"])["versions"][
|
|
0
|
|
]["content_sha256"],
|
|
}
|
|
assert registry.champion_version(NAME) is None
|
|
if clinical:
|
|
registry.promote(NAME, 1)
|
|
assert registry.champion_version(NAME) == 1
|
|
else:
|
|
with pytest.raises(registry.MissingReports, match="clinical_validation"):
|
|
registry.promote(NAME, 1)
|
|
|
|
|
|
def test_importing_twice_is_a_conflict_and_partial_imports_skip(stores):
|
|
_register()
|
|
single = bundle.export(DOMAIN, versions="latest")
|
|
_register(2)
|
|
both = bundle.export(DOMAIN, versions="all")
|
|
stores("b")
|
|
_trust(single.data)
|
|
_trust(both.data)
|
|
assert bundle.import_(DOMAIN, single.data).imported == [(NAME, 1)]
|
|
with pytest.raises(bundle.Conflict, match="every version is already registered"):
|
|
bundle.import_(DOMAIN, single.data)
|
|
result = bundle.import_(DOMAIN, both.data)
|
|
assert result.imported == [(NAME, 2)]
|
|
assert result.skipped == [(NAME, 1)]
|
|
|
|
|
|
def test_tampered_bundles_are_refused(stores):
|
|
_register()
|
|
entries = _entries(bundle.export(DOMAIN, versions="latest").data)
|
|
path = "models/tea.curve_x/v1/model/MLmodel"
|
|
manifest = json.loads(entries["manifest.json"])
|
|
|
|
def with_manifest(**fields):
|
|
return entries | {"manifest.json": json.dumps(manifest | fields).encode()}
|
|
|
|
cases = [
|
|
(_zip(entries | {path: entries[path][:-1] + b"!"}), "content does not match the manifest"),
|
|
(_zip(entries | {"extra": b""}), "files in the bundle do not match the manifest"),
|
|
(_zip({k: v for k, v in entries.items() if k != path}), "files in the bundle do not match"),
|
|
(_zip(entries | {"../x": b""}), r"unsafe bundle path: \.\./x"),
|
|
(_zip(with_manifest(format=2)), "bundle format 2, this platform reads 1"),
|
|
(_zip(with_manifest(domain="cacu")), "bundle is for cacu, not tea"),
|
|
(b"hello", "not a bundle"),
|
|
]
|
|
for data, message in cases:
|
|
_trust(data)
|
|
with pytest.raises(bundle.BundleError, match=message):
|
|
bundle.import_(DOMAIN, data)
|
|
|
|
|
|
def test_import_refuses_an_untrusted_digest(stores):
|
|
_register()
|
|
exported = bundle.export(DOMAIN, versions="latest")
|
|
with pytest.raises(bundle.BundleError, match=f"bundle {exported.sha256} is not trusted"):
|
|
bundle.import_(DOMAIN, exported.data)
|
|
|
|
|
|
def test_version_lifecycle(stores):
|
|
first = _register(clinical=False)
|
|
second = _register(clinical=True)
|
|
assert registry.status(NAME, first) == "candidate"
|
|
with pytest.raises(registry.MissingReports, match="clinical_validation"):
|
|
registry.promote(NAME, first)
|
|
registry.add_report(NAME, first, "clinical_validation", "review.txt", b"approved")
|
|
registry.promote(NAME, first)
|
|
assert registry.status(NAME, first) == "champion"
|
|
with pytest.raises(ValueError, match="the champion cannot be retired"):
|
|
registry.retire(NAME, first)
|
|
registry.promote(NAME, second)
|
|
assert registry.status(NAME, first) == "candidate"
|
|
registry.retire(NAME, first)
|
|
assert registry.status(NAME, first) == "retired"
|
|
with pytest.raises(ValueError, match="is retired"):
|
|
registry.promote(NAME, first)
|
|
assert registry.champion_version(NAME) == second
|