Merge tea/parity into P3.6
This commit is contained in:
@@ -0,0 +1,215 @@
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import zipfile
|
||||
|
||||
import mlflow
|
||||
import pandas as pd
|
||||
import pytest
|
||||
|
||||
from core.domains import Domain, part
|
||||
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# approved\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_guard_runs_on_export_and_on_import(stores, monkeypatch):
|
||||
_register()
|
||||
hook = part(DOMAIN, "bundle")
|
||||
monkeypatch.setattr(hook, "guard", lambda version: [])
|
||||
exported = bundle.export(DOMAIN, versions="latest")
|
||||
_trust(exported.data)
|
||||
monkeypatch.setattr(hook, "guard", lambda version: ["problem"])
|
||||
for operation in (
|
||||
lambda: bundle.export(DOMAIN, versions="latest"),
|
||||
lambda: bundle.import_(DOMAIN, exported.data),
|
||||
):
|
||||
with pytest.raises(bundle.BundleError, match=r"tea\.curve_x v1: problem"):
|
||||
operation()
|
||||
|
||||
|
||||
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)
|
||||
Reference in New Issue
Block a user