Merge P3.4: model bundle endpoints
This commit is contained in:
@@ -0,0 +1,129 @@
|
||||
import hashlib
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from models.tea.jobs import Baseline
|
||||
from persistance import bundle, config, registry
|
||||
|
||||
NAME = "tea.curve_x"
|
||||
|
||||
|
||||
def _register(platform, monkeypatch, n_reference=10):
|
||||
with monkeypatch.context() as local:
|
||||
local.setenv("MLFLOW_TRACKING_URI", platform.env["MLFLOW_TRACKING_URI"])
|
||||
local.chdir(platform.env["ISSSTELEON_DATA"])
|
||||
version = registry.register(
|
||||
NAME,
|
||||
Baseline("x", {"value": {}}),
|
||||
{},
|
||||
{"n_reference": n_reference},
|
||||
{"technical_validation": {}, "interpretability": {}},
|
||||
)
|
||||
registry.add_report(NAME, version, "clinical_validation", "review.txt", b"approved")
|
||||
registry.promote(NAME, version)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def exported(api, platform, monkeypatch):
|
||||
_register(platform, monkeypatch)
|
||||
response = api.get("/models/tea/export")
|
||||
assert response.status_code == 200, response.text
|
||||
return response
|
||||
|
||||
|
||||
def _trust(platform, sha, monkeypatch):
|
||||
with monkeypatch.context() as local:
|
||||
local.setattr(config, "DATA_DIR", Path(platform.env["ISSSTELEON_DATA"]))
|
||||
bundle.trusted_file().write_text(f"{sha}\n")
|
||||
|
||||
|
||||
def _post(api, data, sha):
|
||||
return api.post(
|
||||
"/models/tea/import", params={"sha256": sha}, files={"file": ("bundle.zip", data)}
|
||||
)
|
||||
|
||||
|
||||
def _run(api, response):
|
||||
assert response.status_code == 200, response.text
|
||||
run_id = response.json()["run_id"]
|
||||
deadline = time.monotonic() + 120
|
||||
while True:
|
||||
response = api.get(f"/runs/{run_id}")
|
||||
assert response.status_code == 200, response.text
|
||||
run = response.json()
|
||||
if run["state"] in {"succeeded", "failed", "cancelled"}:
|
||||
return run
|
||||
assert time.monotonic() < deadline, run
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def test_export_and_import_through_the_api(exported, fresh_api, fresh_platform, monkeypatch):
|
||||
sha = hashlib.sha256(exported.content).hexdigest()
|
||||
assert exported.headers["content-type"] == "application/zip"
|
||||
assert exported.headers["x-bundle-sha256"] == sha
|
||||
assert exported.headers["x-bundle-versions"] == "tea.curve_x/1"
|
||||
assert (
|
||||
exported.headers["content-disposition"]
|
||||
== f'attachment; filename="tea-models-{sha[:12]}.zip"'
|
||||
)
|
||||
_trust(fresh_platform, sha, monkeypatch)
|
||||
run = _run(fresh_api, _post(fresh_api, exported.content, sha.upper()))
|
||||
assert run["state"] == "succeeded", run
|
||||
response = fresh_api.get("/models/tea/curve_x/versions")
|
||||
assert response.status_code == 200, response.text
|
||||
(version,) = response.json()
|
||||
assert version["version"] == 1
|
||||
assert version["metrics"]["n_reference"] == 10
|
||||
assert version["reports"] == sorted(registry.REPORTS)
|
||||
assert version["aliases"] == []
|
||||
|
||||
|
||||
def test_import_refuses_a_wrong_sha_and_a_non_zip(api, exported):
|
||||
wrong = _post(api, exported.content, "0" * 64)
|
||||
assert wrong.status_code == 422
|
||||
assert wrong.json()["detail"] == (
|
||||
f"the file's SHA-256 is {exported.headers['x-bundle-sha256']}, not the one given"
|
||||
)
|
||||
non_zip = _post(api, b"hello", hashlib.sha256(b"hello").hexdigest())
|
||||
assert non_zip.status_code == 422
|
||||
assert non_zip.json()["detail"] == "not a bundle"
|
||||
|
||||
|
||||
def test_importing_the_same_bundle_again_fails_the_run(
|
||||
exported,
|
||||
fresh_api,
|
||||
fresh_platform,
|
||||
monkeypatch,
|
||||
):
|
||||
sha = exported.headers["x-bundle-sha256"]
|
||||
_trust(fresh_platform, sha, monkeypatch)
|
||||
first = _run(fresh_api, _post(fresh_api, exported.content, sha))
|
||||
assert first["state"] == "succeeded", first
|
||||
second = _run(fresh_api, _post(fresh_api, exported.content, sha))
|
||||
assert second["state"] == "failed", second
|
||||
assert "already registered" in second["error"]
|
||||
|
||||
|
||||
def test_export_guard_failure_is_422(api, platform, monkeypatch):
|
||||
assert api.get("/models/cacu/export").status_code == 409
|
||||
_register(platform, monkeypatch, n_reference=3)
|
||||
response = api.get("/models/tea/export")
|
||||
assert response.status_code == 422
|
||||
assert "reference group of 3 children is under 5" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_an_untrusted_bundle_is_refused(api, platform, exported):
|
||||
sha = exported.headers["x-bundle-sha256"]
|
||||
response = _post(api, exported.content, sha)
|
||||
assert response.status_code == 403
|
||||
directory = Path(platform.env["ISSSTELEON_DATA"]) / "bundles"
|
||||
assert response.json()["detail"] == (
|
||||
f"bundle {sha} is not trusted on this server: "
|
||||
f"the operator adds its SHA-256 to {directory / 'trusted'}"
|
||||
)
|
||||
assert not (directory / f"{sha}.zip").exists()
|
||||
history = api.get("/runs", params={"job": "import_bundle"})
|
||||
assert history.status_code == 200, history.text
|
||||
assert history.json() == []
|
||||
+63
-2
@@ -2,15 +2,17 @@
|
||||
scoring runs (Dagster). The API starts runs and reads the registry; it never trains."""
|
||||
|
||||
import mimetypes
|
||||
import zipfile
|
||||
from datetime import date
|
||||
from typing import Annotated
|
||||
|
||||
from dagster_graphql import DagsterGraphQLClient
|
||||
from fastapi import APIRouter, Depends, HTTPException, UploadFile
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, UploadFile
|
||||
from fastapi.responses import Response
|
||||
from pydantic import BaseModel
|
||||
|
||||
from core.domains import Domain
|
||||
from persistance import registry
|
||||
from persistance import bundle, registry
|
||||
from persistance.cluster import Execution
|
||||
from webapi.runs import dagster, execution_config, submit
|
||||
|
||||
@@ -32,6 +34,65 @@ def models(domain: Domain) -> list[str]:
|
||||
return [n.removeprefix(prefix) for n in registry.names(prefix)]
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{domain}/export",
|
||||
responses={200: {"content": {"application/zip": {}}}},
|
||||
response_class=Response,
|
||||
)
|
||||
def export_models(
|
||||
domain: Domain,
|
||||
names: Annotated[list[str] | None, Query()] = None,
|
||||
versions: bundle.Selection = "champion",
|
||||
) -> Response:
|
||||
try:
|
||||
exported = bundle.export(domain, names, versions)
|
||||
except bundle.Empty as e:
|
||||
raise HTTPException(409, detail=str(e)) from e
|
||||
except bundle.BundleError as e:
|
||||
raise HTTPException(422, detail=str(e)) from e
|
||||
return Response(
|
||||
exported.data,
|
||||
media_type="application/zip",
|
||||
headers={
|
||||
"X-Bundle-Sha256": exported.sha256,
|
||||
"X-Bundle-Versions": ",".join(f"{name}/{v}" for name, v in exported.versions),
|
||||
"Content-Disposition": (
|
||||
f'attachment; filename="{domain}-models-{exported.sha256[:12]}.zip"'
|
||||
),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/{domain}/import")
|
||||
def import_models(
|
||||
domain: Domain,
|
||||
sha256: Annotated[str, Query(pattern=r"^[0-9a-fA-F]{64}$")],
|
||||
file: UploadFile,
|
||||
client: DagsterGraphQLClient = Depends(dagster),
|
||||
) -> dict[str, str]:
|
||||
computed, path = bundle.stage(file.file)
|
||||
if computed != sha256.lower():
|
||||
path.unlink(missing_ok=True)
|
||||
raise HTTPException(422, detail=f"the file's SHA-256 is {computed}, not the one given")
|
||||
if not zipfile.is_zipfile(path):
|
||||
path.unlink(missing_ok=True)
|
||||
raise HTTPException(422, detail="not a bundle")
|
||||
if not bundle.trusted(computed):
|
||||
path.unlink(missing_ok=True)
|
||||
raise HTTPException(
|
||||
403,
|
||||
detail=f"bundle {computed} is not trusted on this server: "
|
||||
f"the operator adds its SHA-256 to {bundle.trusted_file()}",
|
||||
)
|
||||
return submit(
|
||||
client,
|
||||
"import_bundle",
|
||||
"import_bundle_files",
|
||||
{"domain": domain.value, "sha256": computed},
|
||||
domain.value,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{domain}/{name}/versions")
|
||||
def versions(domain: Domain, name: str) -> list[Version]:
|
||||
if not (found := registry.versions(f"{domain.value}.{name}")):
|
||||
|
||||
Reference in New Issue
Block a user