Generic model bundles: export and import

Export (GET /models/{domain}/export) writes a deterministic zip of chosen versions with a manifest of SHA-256s, after the domain guard (TEA: n_reference >= 5, no study codes, dates or paths). Import (POST /models/{domain}/import, Dagster job import_bundle) stages the upload, checks its SHA-256 and that the operator listed it in $DATA_DIR/bundles/trusted (403 otherwise), verifies every file against the manifest and registers new candidate versions with lineage tags; duplicates are skipped.

Checks: ruff, import-linter, openapi diff; compose: 43 passed (test_bundles, test_runs, test_bundle, test_core_bundle_guard); ng build clean.
This commit is contained in:
2026-11-28 09:24:40 -06:00
parent be77587f8f
commit fdce3a5f49
7 changed files with 522 additions and 4 deletions
+20
View File
@@ -0,0 +1,20 @@
"""Privacy checks on the metadata and generated reports of a TEA bundle."""
import re
MIN_GROUP = 5
FORBIDDEN = re.compile(r"eeg_\d+|\d{4}-\d{2}-\d{2}|[A-Za-z]:\\|/Users/|/home/", re.IGNORECASE)
def guard(version: dict) -> list[str]:
problems = []
n = version["metrics"].get("n_reference")
if n is None:
problems.append("cannot tell the reference group size (no n_reference metric)")
elif n < MIN_GROUP:
problems.append(f"reference group of {n:g} children is under {MIN_GROUP}")
for field, label in (("params", "param"), ("tags", "tag"), ("reports", "report")):
for key, value in version[field].items():
if match := FORBIDDEN.search(value):
problems.append(f"{label} {key} holds a study code, date or path ({match[0]!r})")
return problems
+352
View File
@@ -0,0 +1,352 @@
"""Deterministic model bundles and the operator-approved import queue."""
import hashlib
import io
import json
import re
import tempfile
import zipfile
from dataclasses import dataclass
from pathlib import Path
from typing import BinaryIO, Literal
from core import domains
from core.domains import Domain
from persistance import config, registry
FORMAT = 1
MANIFEST = "manifest.json"
EPOCH = (1980, 1, 1, 0, 0, 0)
MAX_BYTES = 2 * 1024**3
Selection = Literal["champion", "latest", "all"]
class BundleError(ValueError):
pass
class Empty(BundleError):
pass
class Conflict(BundleError):
pass
@dataclass(frozen=True)
class Exported:
data: bytes
sha256: str
versions: list[tuple[str, int]]
@dataclass(frozen=True)
class Imported:
sha256: str
imported: list[tuple[str, int]]
skipped: list[tuple[str, int]]
def _sha256(content: bytes) -> str:
return hashlib.sha256(content).hexdigest()
def content_sha256(files: dict[str, bytes]) -> str:
return _sha256("".join(f"{path}\0{_sha256(files[path])}\n" for path in sorted(files)).encode())
def guard(domain: Domain, snapshot: registry.Snapshot) -> list[str]:
hook = getattr(domains.part(domain, "bundle"), "guard", None)
if hook is None:
return []
reports = {}
for key in ("technical_validation", "interpretability"):
if key in snapshot.reports:
try:
reports[key] = snapshot.reports[key][1].decode("utf-8")
except UnicodeDecodeError:
continue
return hook(
{
"name": snapshot.name,
"version": snapshot.version,
"params": snapshot.params,
"metrics": snapshot.metrics,
"tags": snapshot.tags,
"reports": reports,
}
)
def _check_guard(domain: Domain, snapshots: list[registry.Snapshot]) -> None:
problems = [
f"{snapshot.name} v{snapshot.version}: {problem}"
for snapshot in snapshots
for problem in guard(domain, snapshot)
]
if problems:
raise BundleError("; ".join(problems))
def _prefix(name: str, version: int) -> str:
return f"models/{name}/v{version}/"
def export(
domain: Domain, names: list[str] | None = None, versions: Selection = "champion"
) -> Exported:
prefix = f"{domain.value}."
available = registry.names(prefix)
selected = available
if names is not None:
selected = []
for short in names:
name = prefix + short
if name not in available:
raise BundleError(f"no {domain.value} model {short}")
selected.append(name)
pairs = []
for name in sorted(set(selected)):
if versions == "all":
pairs.extend((name, item["version"]) for item in registry.versions(name))
else:
lookup = (
registry.champion_version if versions == "champion" else registry.latest_version
)
if (version := lookup(name)) is not None:
pairs.append((name, version))
if not pairs:
raise Empty("nothing to export: no version selected")
snapshots = [registry.snapshot(name, version) for name, version in pairs]
_check_guard(domain, snapshots)
entries = {}
manifest_versions = []
for snapshot in snapshots:
files = {f"model/{path}": data for path, data in snapshot.model.items()}
files.update({f"reports/{filename}": data for filename, data in snapshot.reports.values()})
identity = {
"name": snapshot.name,
"version": snapshot.version,
"content_sha256": content_sha256(files),
}
meta = {
**identity,
"created": snapshot.created,
"params": snapshot.params,
"metrics": snapshot.metrics,
"tags": snapshot.tags,
"reports": {key: filename for key, (filename, _) in snapshot.reports.items()},
}
files["meta.json"] = json.dumps(meta, sort_keys=True, indent=1, ensure_ascii=False).encode()
folder = _prefix(snapshot.name, snapshot.version)
entries.update({folder + path: data for path, data in files.items()})
manifest_versions.append(
{**identity, "files": {folder + path: _sha256(data) for path, data in files.items()}}
)
manifest = {"format": FORMAT, "domain": domain.value, "versions": manifest_versions}
entries[MANIFEST] = json.dumps(manifest, sort_keys=True, indent=1).encode()
output = io.BytesIO()
with zipfile.ZipFile(output, "w") as archive:
for path, data in sorted(entries.items()):
info = zipfile.ZipInfo(path, EPOCH)
info.compress_type = zipfile.ZIP_DEFLATED
info.external_attr = 0o644 << 16
info.create_system = 3
archive.writestr(info, data, compresslevel=6)
data = output.getvalue()
return Exported(data, _sha256(data), pairs)
def _safe_path(path: str) -> bool:
return not any(part in ("", ".", "..") for part in path.split("/")) and not (
"\\" in path or "\0" in path
)
def _read(domain: Domain, archive: zipfile.ZipFile) -> list[tuple[registry.Snapshot, str]]:
paths = set()
for entry in archive.infolist():
path = entry.orig_filename
if not _safe_path(path):
raise BundleError(f"unsafe bundle path: {path}")
if path in paths:
raise BundleError(f"duplicate bundle path: {path}")
paths.add(path)
if sum(entry.file_size for entry in archive.infolist()) > MAX_BYTES:
raise BundleError("bundle exceeds the uncompressed size limit")
if MANIFEST not in paths:
raise BundleError("bundle has no manifest.json")
manifest = json.loads(archive.read(MANIFEST))
if (format_ := manifest.get("format")) != FORMAT:
raise BundleError(f"bundle format {format_}, this platform reads 1")
if (source := manifest.get("domain")) != domain.value:
raise BundleError(f"bundle is for {source}, not {domain.value}")
versions = manifest["versions"]
expected = {path for item in versions for path in item["files"]}
if MANIFEST in expected or paths != expected | {MANIFEST}:
raise BundleError("the files in the bundle do not match the manifest")
files = {path: archive.read(path) for path in expected}
for item in versions:
for path, digest in item["files"].items():
if _sha256(files[path]) != digest:
raise BundleError(f"{path}: content does not match the manifest")
snapshots = [_snapshot(domain, item, files) for item in versions]
if len({(snapshot.name, snapshot.version) for snapshot, _ in snapshots}) != len(snapshots):
raise BundleError("duplicate model version in the manifest")
return snapshots
def _snapshot(domain: Domain, item: dict, files: dict[str, bytes]) -> tuple[registry.Snapshot, str]:
name, version, digest = item["name"], item["version"], item["content_sha256"]
if (
not name.startswith(f"{domain.value}.")
or "/" in name
or type(version) is not int
or version < 1
):
raise BundleError("invalid model name or version in the manifest")
prefix = _prefix(name, version)
if any(not path.startswith(prefix) for path in item["files"]):
raise BundleError(f"{name} v{version}: file outside version folder")
relative = {path.removeprefix(prefix): files[path] for path in item["files"]}
meta = json.loads(relative.pop("meta.json"))
if any(meta[key] != item[key] for key in ("name", "version", "content_sha256")):
raise BundleError(f"{name} v{version}: meta.json does not match the manifest")
if content_sha256(relative) != digest:
raise BundleError(f"{name} v{version}: content SHA-256 does not match")
reports = {}
for key, filename in meta["reports"].items():
if key not in registry.REPORTS or "/" in filename:
raise BundleError(f"{name} v{version}: invalid report {key}")
reports[key] = (filename, relative.pop(f"reports/{filename}"))
if any(not path.startswith("model/") for path in relative):
raise BundleError(f"{name} v{version}: unexpected file in version folder")
model = {path.removeprefix("model/"): data for path, data in relative.items()}
return registry.Snapshot(
name,
version,
meta["created"],
meta["params"],
meta["metrics"],
meta["tags"],
reports,
model,
), digest
def import_(domain: Domain, data: bytes) -> Imported:
sha256 = _sha256(data)
if not trusted(sha256):
raise BundleError(
f"bundle {sha256} is not trusted on this server: "
f"the operator adds its SHA-256 to {trusted_file()}"
)
try:
archive = zipfile.ZipFile(io.BytesIO(data))
except zipfile.BadZipFile:
raise BundleError("not a bundle") from None
try:
with archive:
versions = _read(domain, archive)
versions.sort(key=lambda item: (item[0].name, item[0].version))
_check_guard(domain, [snapshot for snapshot, _ in versions])
except BundleError:
raise
except (
ValueError,
KeyError,
TypeError,
AttributeError,
RuntimeError,
OSError,
zipfile.BadZipFile,
) as e:
raise BundleError(f"invalid bundle: {e}") from None
pending, skipped = [], []
for snapshot, digest in versions:
if digest in registry.content_hashes(snapshot.name):
skipped.append((snapshot.name, snapshot.version))
else:
pending.append((snapshot, digest))
if not pending:
found = ", ".join(f"{name} v{version}" for name, version in skipped)
raise Conflict(f"every version is already registered: {found}")
imported = []
for snapshot, digest in pending:
tags = {key: val for key, val in snapshot.tags.items() if not key.startswith("bundle.")}
tags.update(
{
"bundle.sha256": sha256,
"bundle.source_name": snapshot.name,
"bundle.source_version": str(snapshot.version),
"bundle.content_sha256": digest,
}
)
with tempfile.TemporaryDirectory() as tmp:
model_dir = Path(tmp)
for path, content in snapshot.model.items():
target = model_dir / path
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(content)
try:
version = registry.restore(
snapshot.name,
model_dir,
snapshot.params,
snapshot.metrics,
snapshot.reports,
tags,
)
except ValueError as e:
raise BundleError(str(e)) from None
imported.append((snapshot.name, version))
return Imported(sha256, imported, skipped)
def staging() -> Path:
path = config.DATA_DIR / "bundles"
path.mkdir(parents=True, exist_ok=True)
return path
def staged(sha256: str) -> Path:
if not re.fullmatch(r"[0-9a-f]{64}", sha256):
raise ValueError("invalid bundle SHA-256")
return staging() / f"{sha256}.zip"
def stage(stream: BinaryIO) -> tuple[str, Path]:
digest = hashlib.sha256()
with tempfile.NamedTemporaryFile(dir=staging(), delete=False) as output:
temp = Path(output.name)
try:
while chunk := stream.read(1024**2):
digest.update(chunk)
output.write(chunk)
output.close()
sha256 = digest.hexdigest()
path = staged(sha256)
temp.replace(path)
finally:
temp.unlink(missing_ok=True)
return sha256, path
def trusted_file() -> Path:
return staging() / "trusted"
def trusted(sha256: str) -> bool:
try:
with trusted_file().open(encoding="utf-8") as file:
return any(
line == sha256
for raw in file
if (line := raw.strip().lower()) and not line.startswith("#")
)
except FileNotFoundError:
return False
+107 -1
View File
@@ -3,6 +3,7 @@
version that has all three. Where MLflow is comes from MLFLOW_TRACKING_URI."""
import tempfile
from dataclasses import dataclass
from importlib.metadata import version as installed
from pathlib import Path
@@ -22,12 +23,21 @@ class MissingReports(ValueError):
pass
def register(name: str, python_model, params: dict, metrics: dict, reports: dict) -> int:
def register(
name: str,
python_model,
params: dict,
metrics: dict,
reports: dict,
tags: dict[str, str] | None = None,
) -> int:
"""A new version of `name`: the model, its parameters and metrics, and its reports."""
mlflow.set_experiment(EXPERIMENT)
with mlflow.start_run(run_name=name):
mlflow.log_params(params)
mlflow.log_metrics({k: float(v) for k, v in metrics.items() if v is not None})
if tags:
mlflow.set_tags(tags)
for report, data in reports.items():
mlflow.log_dict(data, f"reports/{report}.json")
info = mlflow.pyfunc.log_model(
@@ -101,3 +111,99 @@ def names(prefix: str) -> list[str]:
"""Registered models whose name starts with `prefix` (a domain: `cacu.`)."""
found = MlflowClient().search_registered_models(f"name LIKE '{prefix}%'")
return sorted(m.name for m in found)
def champion_version(name: str) -> int | None:
try:
found = MlflowClient().get_model_version_by_alias(name, CHAMPION)
except mlflow.exceptions.MlflowException:
return None
return int(found.version)
def latest_version(name: str) -> int | None:
found = MlflowClient().search_model_versions(f"name = '{name}'")
return max((int(v.version) for v in found), default=None)
def content_hashes(name: str) -> set[str]:
client = MlflowClient()
return {
tags["bundle.content_sha256"]
for v in client.search_model_versions(f"name = '{name}'")
if "bundle.content_sha256" in (tags := client.get_run(v.run_id).data.tags)
}
@dataclass(frozen=True)
class Snapshot:
name: str
version: int
created: int
params: dict[str, str]
metrics: dict[str, float]
tags: dict[str, str]
reports: dict[str, tuple[str, bytes]]
model: dict[str, bytes]
def snapshot(name: str, version: int) -> Snapshot:
client = MlflowClient()
try:
found = client.get_model_version(name, str(version))
except mlflow.exceptions.MlflowException as e:
if e.error_code != "RESOURCE_DOES_NOT_EXIST":
raise
raise ValueError(f"no {name} version {version}") from e
run = client.get_run(found.run_id).data
saved_reports = {
key: item for key in reports(name, version) if (item := report(name, version, key))
}
with tempfile.TemporaryDirectory() as tmp:
root = Path(
mlflow.artifacts.download_artifacts(
artifact_uri=f"models:/{name}/{version}", dst_path=tmp
)
)
model = {
p.relative_to(root).as_posix(): p.read_bytes() for p in root.rglob("*") if p.is_file()
}
return Snapshot(
name,
version,
found.creation_timestamp,
run.params,
run.metrics,
{k: v for k, v in run.tags.items() if not k.startswith("mlflow.")},
saved_reports,
model,
)
def restore(
name: str,
model_dir: Path,
params: dict[str, str],
metrics: dict[str, float],
reports: dict[str, tuple[str, bytes]],
tags: dict[str, str],
) -> int:
mlflow.set_experiment(EXPERIMENT)
with mlflow.start_run(run_name=name), tempfile.TemporaryDirectory() as tmp:
mlflow.log_params(params)
mlflow.log_metrics(metrics)
mlflow.set_tags(tags)
for report, (filename, content) in reports.items():
path = Path(tmp) / f"{report}{Path(filename).suffix}"
path.write_bytes(content)
mlflow.log_artifact(str(path), "reports")
loaded = mlflow.pyfunc.load_model(str(model_dir))
try:
python_model = loaded.unwrap_python_model()
except mlflow.exceptions.MlflowException as e:
raise ValueError("this model cannot be re-registered") from e
info = mlflow.pyfunc.log_model(
name="model", python_model=python_model, registered_model_name=name,
pip_requirements=[f"{p}=={installed(p)}" for p in REQUIREMENTS],
) # fmt: skip
return int(info.registered_model_version)
+1 -1
Submodule WebApi updated: 4793cf01f0...88bbc6155f
+1 -1
Submodule WebApp updated: 43b5523f99...8b1cbec66a
+1 -1
Submodule models updated: cc95054a96...d954faa28e
+40
View File
@@ -0,0 +1,40 @@
import pytest
from core.domains import Domain, part
from core.tea.bundle import guard
from persistance import bundle, registry
@pytest.mark.parametrize(
("metrics", "problems"),
[
({"n_reference": 4}, ["reference group of 4 children is under 5"]),
({"n_reference": 5}, []),
({}, ["cannot tell the reference group size (no n_reference metric)"]),
],
)
def test_reference_group_size(metrics, problems):
assert guard({"metrics": metrics, "params": {}, "tags": {}, "reports": {}}) == problems
@pytest.mark.parametrize(
("field", "key", "where", "value"),
[
("params", "date", "param date", "2026-11-28"),
("tags", "study", "tag study", "eeg_12"),
("reports", "technical_validation", "report technical_validation", "/home/x"),
],
)
def test_guard_names_where_it_found_protected_values(field, key, where, value):
version = {"metrics": {"n_reference": 5}, "params": {}, "tags": {}, "reports": {}}
version[field][key] = value
match = "/home/" if value == "/home/x" else value
assert guard(version) == [f"{where} holds a study code, date or path ({match!r})"]
def test_clinical_validation_is_not_passed_and_cacu_has_no_guard():
reports = {"clinical_validation": ("review.txt", b"2026-11-28 eeg_12 /home/x")}
snapshot = registry.Snapshot("tea.curve_x", 1, 0, {}, {"n_reference": 5}, {}, reports, {})
assert bundle.guard(Domain.TEA, snapshot) == []
assert part(Domain.CACU, "bundle") is None
assert bundle.guard(Domain.CACU, snapshot) == []