- One file, three parts.
+ One file, four parts.
A .mlbundle is a ZIP with a closed list of files. Anything else
inside it is rejected before the model is read.
diff --git a/landing/src/data/example.json b/landing/src/data/example.json
index 6c0bc59..51801f3 100644
--- a/landing/src/data/example.json
+++ b/landing/src/data/example.json
@@ -1,8 +1,8 @@
{
- "version": "0.2.1",
+ "version": "0.3.0",
"code": "import pandas as pd\nfrom sklearn.tree import DecisionTreeClassifier\n\nfrom mlbundle import export, load\n\ntraining = pd.DataFrame(\n [[0.0, 1.0, \"cold\"], [1.0, 0.0, \"warm\"]] * 2,\n columns=[\"temperature\", \"humidity\", \"target\"],\n)\nfeatures = training.drop(columns=\"target\")\nmodel = DecisionTreeClassifier(random_state=7)\nmodel.fit(features, training[\"target\"])\n\nexport(\n model,\n \"trained.mlbundle\",\n training_data=training,\n target_names=[\"target\"],\n)\n\nbundle = load(\"trained.mlbundle\")\nrecord = {\"temperature\": 0.0, \"humidity\": 1.0}\nprediction = bundle.predict_record(record)[0]\nprint(prediction.predicted_label, prediction.probabilities)\n",
"printed": "cold (1.0, 0.0)",
- "bundleBytes": 9233,
+ "bundleBytes": 16176,
"members": [
{
"name": "manifest.json",
@@ -12,7 +12,7 @@
{
"name": "model.skops",
"size": 15011,
- "sha256": "b332c1e060939f16a2f300797c6ee1625e99d684f215e45ba8772fd7dfee5da2"
+ "sha256": "f80b074879ef70d486d63a86a19a3c38e13450d5d0a8b6f7832caf8f61307371"
},
{
"name": "schema.json",
@@ -23,14 +23,19 @@
"name": "structure.json",
"size": 511,
"sha256": "8cf658be94b826ba4f81f1a78ed2c8e5107fce656d212dc888bd8621a9068baa"
+ },
+ {
+ "name": "pylock.toml",
+ "size": 10275,
+ "sha256": "8db9cceb14ef0de76087c3b72f4ba6cd21b1f5a52ef8a8cef4a65bb895a3ac57"
}
],
"manifest": {
"format_name": "mlbundle",
"format_version": "1",
- "bundle_id": "869eb397-2dce-44b4-b0d0-b6a85d757b0b",
- "created_at": "2026-10-19T13:27:32.304933Z",
- "writer_version": "0.2.1",
+ "bundle_id": "9aca9f92-c0d2-41f1-a2f6-7a5264ddce4e",
+ "created_at": "2026-10-28T13:54:14.550040Z",
+ "writer_version": "0.3.0",
"model": {
"estimator_class": "DecisionTreeClassifier",
"kind": "classifier",
@@ -85,29 +90,21 @@
"environment": {
"python_version": "3.14.7",
"python_implementation": "CPython",
+ "free_threaded": false,
"os": "Windows",
"os_version": "11",
"architecture": "AMD64",
- "packages": {
- "catboost": "1.2.10",
- "mlbundle": "0.2.1",
- "mlschema": "0.3.0",
- "numpy": "2.5.4",
- "onnx": "1.23.0",
- "onnxruntime": "1.30.0",
- "pandas": "3.0.6",
- "scikit-learn": "1.9.1",
- "scipy": "1.18.1",
- "skops": "0.16.0",
- "xgboost": "3.4.1"
- },
"onnx": null
},
"integrity": {
"model.skops": {
- "sha256": "b332c1e060939f16a2f300797c6ee1625e99d684f215e45ba8772fd7dfee5da2",
+ "sha256": "f80b074879ef70d486d63a86a19a3c38e13450d5d0a8b6f7832caf8f61307371",
"size": 15011
},
+ "pylock.toml": {
+ "sha256": "8db9cceb14ef0de76087c3b72f4ba6cd21b1f5a52ef8a8cef4a65bb895a3ac57",
+ "size": 10275
+ },
"schema.json": {
"sha256": "e770ad53af881faf368c686de86b2b00f0a64a1444e241985643349bf7b0bba4",
"size": 388
@@ -119,6 +116,7 @@
},
"references": {
"schema": "schema.json",
+ "lock": "pylock.toml",
"structure": "structure.json",
"samples": null
},
@@ -159,7 +157,7 @@
},
"inspect": {
"exit": 0,
- "stdout": "Metadata and integrity validated; model claims NOT verified.\nFormat: mlbundle 1\nBundle id: 869eb397-2dce-44b4-b0d0-b6a85d757b0b\nCreated: 2026-10-19T13:27:32.304933+00:00\nWriter: \"0.2.1\"\nModel: sklearn \"DecisionTreeClassifier\" (classifier)\nCounts: features=2, outputs=1, classes=[2]\nFeatures (model): [\"temperature\", \"humidity\"]\nClass labels (output-major): [[\"cold\", \"warm\"]]\nTarget names (output-major): [\"target\"]\nMembers:\n manifest.json: validated (no self-integrity record)\n model.skops: 15011 bytes sha256=b332c1e060939f16a2f300797c6ee1625e99d684f215e45ba8772fd7dfee5da2\n schema.json: 388 bytes sha256=e770ad53af881faf368c686de86b2b00f0a64a1444e241985643349bf7b0bba4\n structure.json: 511 bytes sha256=8cf658be94b826ba4f81f1a78ed2c8e5107fce656d212dc888bd8621a9068baa\nTraining: {\"python\": \"3.14.7\", \"implementation\": \"CPython\", \"os\": \"Windows\", \"os_version\": \"11\", \"architecture\": \"AMD64\"}\nPackages: {\"catboost\": \"1.2.10\", \"mlbundle\": \"0.2.1\", \"mlschema\": \"0.3.0\", \"numpy\": \"2.5.4\", \"onnx\": \"1.23.0\", \"onnxruntime\": \"1.30.0\", \"pandas\": \"3.0.6\", \"scikit-learn\": \"1.9.1\", \"scipy\": \"1.18.1\", \"skops\": \"0.16.0\", \"xgboost\": \"3.4.1\"}\nONNX environment: null\nPresent: schema=yes, structure=yes, samples=no\nUser metadata: {}",
+ "stdout": "Metadata and integrity validated; model claims NOT verified.\nFormat: mlbundle 1\nBundle id: 9aca9f92-c0d2-41f1-a2f6-7a5264ddce4e\nCreated: 2026-10-28T13:54:14.550040+00:00\nWriter: \"0.3.0\"\nModel: sklearn \"DecisionTreeClassifier\" (classifier)\nCounts: features=2, outputs=1, classes=[2]\nFeatures (model): [\"temperature\", \"humidity\"]\nClass labels (output-major): [[\"cold\", \"warm\"]]\nTarget names (output-major): [\"target\"]\nMembers:\n manifest.json: validated (no self-integrity record)\n model.skops: 15011 bytes sha256=f80b074879ef70d486d63a86a19a3c38e13450d5d0a8b6f7832caf8f61307371\n schema.json: 388 bytes sha256=e770ad53af881faf368c686de86b2b00f0a64a1444e241985643349bf7b0bba4\n structure.json: 511 bytes sha256=8cf658be94b826ba4f81f1a78ed2c8e5107fce656d212dc888bd8621a9068baa\n pylock.toml: 10275 bytes sha256=8db9cceb14ef0de76087c3b72f4ba6cd21b1f5a52ef8a8cef4a65bb895a3ac57\nTraining: {\"python\": \"3.14.7\", \"implementation\": \"CPython\", \"free_threaded\": false, \"os\": \"Windows\", \"os_version\": \"11\", \"architecture\": \"AMD64\"}\nEnvironment lock: CPython 3.14.7 with the GIL, linux-x86_64, linux-aarch64, win-amd64 (Linux glibc 2.28+), 16 packages plus mlbundle \"0.3.0\"\nEnvironment id: c14224b054babe4236123cc648131ed436fb9e8ee7317ad929f29978144c8f1d\nLocked packages: {\"annotated-types\": \"0.8.0\", \"cloudpickle\": \"3.1.2\", \"joblib\": \"1.6.0\", \"narwhals\": \"2.27.1\", \"numpy\": \"2.5.4\", \"packaging\": \"26.3\", \"prettytable\": \"3.18.0\", \"pydantic\": \"2.14.1\", \"pydantic-core\": \"2.50.1\", \"scikit-learn\": \"1.9.1\", \"scipy\": \"1.18.1\", \"skops\": \"0.16.0\", \"threadpoolctl\": \"3.7.0\", \"typing-extensions\": \"4.16.0\", \"typing-inspection\": \"0.4.4\", \"wcwidth\": \"0.9.2\"}\nONNX environment: null\nPresent: schema=yes, structure=yes, samples=no\nUser metadata: {}",
"stderr": ""
},
"verify": {
@@ -169,7 +167,7 @@
},
"editedInspect": {
"exit": 0,
- "stdout": "Metadata and integrity validated; model claims NOT verified.\nFormat: mlbundle 1\nBundle id: 869eb397-2dce-44b4-b0d0-b6a85d757b0b\nCreated: 2026-10-19T13:27:32.304933+00:00\nWriter: \"0.2.1\"\nModel: sklearn \"DecisionTreeClassifier\" (classifier)\nCounts: features=2, outputs=1, classes=[2]\nFeatures (model): [\"temperature\", \"humidity\"]\nClass labels (output-major): [[\"cold\", \"warm\"]]\nTarget names (output-major): [\"target\"]\nMembers:\n manifest.json: validated (no self-integrity record)\n model.skops: 15011 bytes sha256=b332c1e060939f16a2f300797c6ee1625e99d684f215e45ba8772fd7dfee5da2\n schema.json: 388 bytes sha256=e770ad53af881faf368c686de86b2b00f0a64a1444e241985643349bf7b0bba4\n structure.json: 511 bytes sha256=8cf658be94b826ba4f81f1a78ed2c8e5107fce656d212dc888bd8621a9068baa\nTraining: {\"python\": \"3.14.7\", \"implementation\": \"CPython\", \"os\": \"Windows\", \"os_version\": \"11\", \"architecture\": \"AMD64\"}\nPackages: {\"catboost\": \"1.2.10\", \"mlbundle\": \"0.2.1\", \"mlschema\": \"0.3.0\", \"numpy\": \"2.5.4\", \"onnx\": \"1.23.0\", \"onnxruntime\": \"1.30.0\", \"pandas\": \"3.0.6\", \"scikit-learn\": \"1.9.1\", \"scipy\": \"1.18.1\", \"skops\": \"0.16.0\", \"xgboost\": \"3.4.1\"}\nONNX environment: null\nPresent: schema=yes, structure=yes, samples=no\nUser metadata: {}",
+ "stdout": "Metadata and integrity validated; model claims NOT verified.\nFormat: mlbundle 1\nBundle id: 9aca9f92-c0d2-41f1-a2f6-7a5264ddce4e\nCreated: 2026-10-28T13:54:14.550040+00:00\nWriter: \"0.3.0\"\nModel: sklearn \"DecisionTreeClassifier\" (classifier)\nCounts: features=2, outputs=1, classes=[2]\nFeatures (model): [\"temperature\", \"humidity\"]\nClass labels (output-major): [[\"cold\", \"warm\"]]\nTarget names (output-major): [\"target\"]\nMembers:\n manifest.json: validated (no self-integrity record)\n model.skops: 15011 bytes sha256=f80b074879ef70d486d63a86a19a3c38e13450d5d0a8b6f7832caf8f61307371\n schema.json: 388 bytes sha256=e770ad53af881faf368c686de86b2b00f0a64a1444e241985643349bf7b0bba4\n structure.json: 511 bytes sha256=8cf658be94b826ba4f81f1a78ed2c8e5107fce656d212dc888bd8621a9068baa\n pylock.toml: 10275 bytes sha256=8db9cceb14ef0de76087c3b72f4ba6cd21b1f5a52ef8a8cef4a65bb895a3ac57\nTraining: {\"python\": \"3.14.7\", \"implementation\": \"CPython\", \"free_threaded\": false, \"os\": \"Windows\", \"os_version\": \"11\", \"architecture\": \"AMD64\"}\nEnvironment lock: CPython 3.14.7 with the GIL, linux-x86_64, linux-aarch64, win-amd64 (Linux glibc 2.28+), 16 packages plus mlbundle \"0.3.0\"\nEnvironment id: c14224b054babe4236123cc648131ed436fb9e8ee7317ad929f29978144c8f1d\nLocked packages: {\"annotated-types\": \"0.8.0\", \"cloudpickle\": \"3.1.2\", \"joblib\": \"1.6.0\", \"narwhals\": \"2.27.1\", \"numpy\": \"2.5.4\", \"packaging\": \"26.3\", \"prettytable\": \"3.18.0\", \"pydantic\": \"2.14.1\", \"pydantic-core\": \"2.50.1\", \"scikit-learn\": \"1.9.1\", \"scipy\": \"1.18.1\", \"skops\": \"0.16.0\", \"threadpoolctl\": \"3.7.0\", \"typing-extensions\": \"4.16.0\", \"typing-inspection\": \"0.4.4\", \"wcwidth\": \"0.9.2\"}\nONNX environment: null\nPresent: schema=yes, structure=yes, samples=no\nUser metadata: {}",
"stderr": ""
},
"editedVerify": {
diff --git a/landing/src/data/site.ts b/landing/src/data/site.ts
index d150d33..cee19d4 100644
--- a/landing/src/data/site.ts
+++ b/landing/src/data/site.ts
@@ -33,7 +33,7 @@ export const description =
"Package a trained model, a verifiable manifest and a locally inferred schema in one .mlbundle file. Native formats for scikit-learn, XGBoost, CatBoost and ONNX, never pickle.";
// The release install from the docs; checkout installs live on the docs installation page.
-export const install = 'pip install "mlbundle[sklearn,schema]"';
+export const install = 'pip install "mlbundle[sklearn,schema,lock]"';
// The eshkra path from a trained model to a reviewed prediction, as on eshkra.dev.
export const family = [
diff --git a/landing/src/styles/sections.css b/landing/src/styles/sections.css
index 125e2de..e42046e 100644
--- a/landing/src/styles/sections.css
+++ b/landing/src/styles/sections.css
@@ -92,7 +92,7 @@
}
.parts {
display: grid;
- grid-template-columns: repeat(3, minmax(0, 1fr));
+ grid-template-columns: repeat(4, minmax(0, 1fr));
gap: clamp(1.5rem, 4vw, 3rem);
margin: 3rem 0 0;
padding: 0;
@@ -213,6 +213,9 @@
.split {
grid-template-columns: minmax(0, 1fr);
}
+ .parts {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
}
@media (max-width: 48rem) {
.hero-pair,
diff --git a/playground/README.md b/playground/README.md
index 8d27486..b949fa8 100644
--- a/playground/README.md
+++ b/playground/README.md
@@ -8,7 +8,7 @@ Intended host: . Documentation: =1.6`, but mlbundle's sklearn catalog is audited against 1.9.1, which has no build for this runtime. pandas 3.0.2 is likewise the newest Pyodide build. Bundles written here record the versions that actually ran, with `Emscripten`/`wasm32` as the platform; loading them with a different scikit-learn version may produce mlbundle's version diagnostics.
+PyPI pins match `uv.lock` (a unit test checks them). scikit-learn 1.8.0 satisfies mlbundle's `>=1.6`, but mlbundle's sklearn catalog is audited against 1.9.1, which has no build for this runtime. pandas 3.0.2 is likewise the newest Pyodide build. Bundles written here record `Emscripten`/`wasm32` as the training platform; loading them with a different scikit-learn version may produce mlbundle's version diagnostics.
+
+Export normally locks the runtime with uv, which cannot run in the browser. `src/runtime/pylock.toml` is the lock for this session's exact versions, generated by `uv run --project .. python scripts/lock.py` (a unit test checks it against Pyodide and the pins). Each run directory receives it as `pylock.toml`, and the examples pass `environment_lock="pylock.toml"`, so bundles written here lock the same scikit-learn 1.8.0 runtime for Linux and Windows. Regenerate it after changing the Pyodide release or `PYPI_PINS`.
Pyodide's `os` module has no `link`. The harness defines one that raises `ENOSYS`, so mlbundle takes its documented publication path for file systems without hard links.
The first visit downloads Python and the wheels from `cdn.jsdelivr.net`, `pypi.org` and `files.pythonhosted.org`; later visits use the browser cache. If those hosts are unreachable, the page reports that Python could not start and offers **Restart Python**.
-To move to a new Pyodide release, update `pyodide` in `package.json` and `PYODIDE_VERSION` in `src/runtime/versions.ts` together (a unit test checks they match), then review `PYPI_PINS`.
+To move to a new Pyodide release, update `pyodide` in `package.json` and `PYODIDE_VERSION` in `src/runtime/versions.ts` together (a unit test checks they match), then review `PYPI_PINS` and regenerate `src/runtime/pylock.toml`.
## Examples
diff --git a/playground/scripts/lock.py b/playground/scripts/lock.py
new file mode 100644
index 0000000..1553cc9
--- /dev/null
+++ b/playground/scripts/lock.py
@@ -0,0 +1,56 @@
+"""Write the playground's pylock.toml for the exact versions its Pyodide session runs.
+
+Pyodide cannot run uv, so playground exports pass this lock as environment_lock.
+It locks pydantic, scikit-learn and skops at the session's versions for Linux
+and Windows, like a training-machine export. Rerun after changing the Pyodide
+release or PYPI_PINS; export rejects a lock that disagrees with the installed
+versions.
+Usage, from playground/: uv run --project .. python scripts/lock.py
+"""
+
+import json
+import re
+import sys
+from pathlib import Path
+
+from mlbundle._lock_generation import resolve_lock
+from mlbundle._wheel_tags import normalize
+
+PLAYGROUND = Path(__file__).resolve().parents[1]
+VERSIONS = PLAYGROUND / "src" / "runtime" / "versions.ts"
+PYODIDE = PLAYGROUND / "node_modules" / "pyodide" / "pyodide-lock.json"
+OUTPUT = PLAYGROUND / "src" / "runtime" / "pylock.toml"
+ROOTS = ("pydantic", "scikit-learn", "skops")
+
+
+def session_versions() -> tuple[str, dict[str, str]]:
+ """Python and the distributions startSession loads: Pyodide packages, then pins."""
+ source = VERSIONS.read_text(encoding="utf-8")
+ loaded = re.search(r"PYODIDE_PACKAGES = \[(.*?)\]", source, re.DOTALL)
+ pins = re.search(r"PYPI_PINS = \[(.*?)\]", source, re.DOTALL)
+ assert loaded is not None and pins is not None
+ lock = json.loads(PYODIDE.read_text(encoding="utf-8"))
+ packages = {normalize(name): value for name, value in lock["packages"].items()}
+ versions: dict[str, str] = {}
+ pending = [normalize(name) for name in re.findall(r'"([^"]+)"', loaded[1])]
+ while pending:
+ name = pending.pop()
+ if name in versions:
+ continue
+ versions[name] = packages[name]["version"]
+ pending.extend(normalize(item) for item in packages[name]["depends"])
+ for name, version in re.findall(r'"([^"=]+)==([^"]+)"', pins[1]):
+ versions[normalize(name)] = version
+ return lock["info"]["python"], versions
+
+
+def main() -> None:
+ python, versions = session_versions()
+ pins = {name: versions[name] for name in ROOTS}
+ lock = resolve_lock(python, pins, versions)
+ OUTPUT.write_bytes(lock.to_bytes())
+ sys.stdout.write(f"{OUTPUT.name}: Python {python}, {len(lock.packages)} packages\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/playground/src/examples/classifier.py b/playground/src/examples/classifier.py
index db5a48b..926e831 100644
--- a/playground/src/examples/classifier.py
+++ b/playground/src/examples/classifier.py
@@ -17,11 +17,14 @@
# Writes classifier.mlbundle into this run's working directory. The playground then
# inspects it and verifies it with mlbundle.load before showing it on the right.
+# On your machine, export locks the runtime with uv; this browser cannot run uv, so
+# it passes the pylock.toml prepared for this page's exact package versions.
view = export(
model,
"classifier.mlbundle",
training_data=training,
target_names=["weather"],
metadata={"purpose": "playground example"},
+ environment_lock="pylock.toml",
)
view.manifest.target.class_labels
diff --git a/playground/src/examples/pipeline.py b/playground/src/examples/pipeline.py
index ca31cea..32b19ee 100644
--- a/playground/src/examples/pipeline.py
+++ b/playground/src/examples/pipeline.py
@@ -11,5 +11,11 @@
model = make_pipeline(StandardScaler(), SVR(C=3.0)).fit(rows, target)
# Without a frame, names are declared and the schema comes from one default row.
-view = export(model, "pipeline.mlbundle", feature_names=["dose_mg", "weight_kg"])
+# The browser cannot run uv: pass the lock prepared for this page's versions.
+view = export(
+ model,
+ "pipeline.mlbundle",
+ feature_names=["dose_mg", "weight_kg"],
+ environment_lock="pylock.toml",
+)
{"source": view.schema["source"], "dtypes": view.manifest.features.dtypes}
diff --git a/playground/src/examples/regressor.py b/playground/src/examples/regressor.py
index 2307acf..ce5f114 100644
--- a/playground/src/examples/regressor.py
+++ b/playground/src/examples/regressor.py
@@ -19,6 +19,13 @@
model = RandomForestRegressor(n_estimators=3, max_depth=3, random_state=0)
model.fit(frame.drop(columns="price_k"), frame["price_k"])
-export(model, "regressor.mlbundle", training_data=frame, target_names=["price_k"])
+# The browser cannot run uv: pass the lock prepared for this page's versions.
+export(
+ model,
+ "regressor.mlbundle",
+ training_data=frame,
+ target_names=["price_k"],
+ environment_lock="pylock.toml",
+)
model.feature_importances_.round(3).tolist()
diff --git a/playground/src/examples/samples.py b/playground/src/examples/samples.py
index 5a6b01b..3ae49fe 100644
--- a/playground/src/examples/samples.py
+++ b/playground/src/examples/samples.py
@@ -16,5 +16,12 @@
churned = ["no", "yes", "no", "no", "yes", "no"]
model = LogisticRegression(max_iter=500).fit(features, churned)
-view = export(model, "samples.mlbundle", training_data=features, sample_rows=3)
+# The browser cannot run uv: pass the lock prepared for this page's versions.
+view = export(
+ model,
+ "samples.mlbundle",
+ training_data=features,
+ sample_rows=3,
+ environment_lock="pylock.toml",
+)
[field["kind"] for field in view.schema["fields"]]
diff --git a/playground/src/inspector/overview.ts b/playground/src/inspector/overview.ts
index d2015ac..4b076dc 100644
--- a/playground/src/inspector/overview.ts
+++ b/playground/src/inspector/overview.ts
@@ -47,6 +47,7 @@ export const overview = (bundle: BundleReport) => {
const labels = asArray(target.class_labels);
const targetNames = asArray(target.names);
const metadata = asObject(manifest.user_metadata);
+ const lock = bundle.environment;
return [
facts("Model", [
["Estimator", model.estimator_class],
@@ -74,8 +75,15 @@ export const overview = (bundle: BundleReport) => {
section(
"Training environment",
note(`Python ${display(environment.python_version)} on ${display(environment.os)} ${display(environment.os_version)} (${display(environment.architecture)}). Declared by the writer, not authenticated.`),
- table("Package versions", ["Package", "Version"], Object.entries(asObject(environment.packages))),
),
+ lock
+ ? section(
+ "Runtime lock",
+ note(`pylock.toml for CPython ${lock.pythonVersion} with the GIL on ${lock.platforms.join(", ")}, plus mlbundle ${display(manifest.writer_version)}. Installing it runs these packages' code; a runtime decides which it trusts.`),
+ facts("Environment", [["Environment id", lock.environmentId]]),
+ table("Locked packages", ["Package", "Version", "Targets"], lock.packages.map(([name, version, platforms]) => [name, version, platforms.join(", ")])),
+ )
+ : null,
Object.keys(metadata).length
? section("User metadata", table("Author metadata", ["Key", "Value"], Object.entries(metadata)))
: null,
diff --git a/playground/src/runtime/harness.py b/playground/src/runtime/harness.py
index 5d6cbc8..dae8a40 100644
--- a/playground/src/runtime/harness.py
+++ b/playground/src/runtime/harness.py
@@ -16,6 +16,8 @@
FILENAME = ""
WORK_ROOT = Path("/playground")
+# session.ts writes the lock that scripts/lock.py generated for this runtime.
+LOCK = Path("/lock/pylock.toml")
MAX_BUNDLES = 8
MIB = 1024 * 1024
# Lowered with mlbundle's own ArchiveLimits: a browser tab is not a model server.
@@ -65,11 +67,18 @@ def _metadata(view) -> dict:
members = [
{"name": str(name), **integrity.get(str(name), {})} for name in view.members
]
+ lock = view.environment_lock
return {
"manifest": manifest,
"members": members,
"schema": view.schema,
"samples": view.samples,
+ "environment": {
+ "pythonVersion": lock.python_version,
+ "platforms": list(lock.platforms),
+ "environmentId": lock.environment_id,
+ "packages": [[p.name, p.version, list(p.platforms)] for p in lock.packages],
+ },
}
@@ -157,6 +166,7 @@ async def run(code: str) -> str:
shutil.rmtree(WORK_ROOT, ignore_errors=True)
directory = WORK_ROOT / f"run-{_runs}"
directory.mkdir(parents=True)
+ shutil.copyfile(LOCK, directory / "pylock.toml")
os.chdir(directory)
linecache.cache[FILENAME] = (len(code), None, code.splitlines(True), FILENAME)
namespace = {"__name__": "__main__"}
diff --git a/playground/src/runtime/protocol.ts b/playground/src/runtime/protocol.ts
index 2477d89..8145a6e 100644
--- a/playground/src/runtime/protocol.ts
+++ b/playground/src/runtime/protocol.ts
@@ -40,10 +40,20 @@ export interface BundleReport {
schema?: { [key: string]: Json } | null;
samples?: { [key: string]: Json }[] | null;
structure?: { [key: string]: Json } | null;
+ /** The validated pylock.toml: what a Linux runtime installs, besides mlbundle. */
+ environment?: EnvironmentLockReport;
/** The exact bytes mlbundle wrote, for download. Generated bundles only. */
bytes?: Uint8Array;
}
+export interface EnvironmentLockReport {
+ pythonVersion: string;
+ platforms: string[];
+ environmentId: string;
+ /** Name, version and the Linux architectures that install it. */
+ packages: [string, string, string[]][];
+}
+
export interface RunReport {
outcome: RunOutcome;
bundles: BundleReport[];
diff --git a/playground/src/runtime/pylock.toml b/playground/src/runtime/pylock.toml
new file mode 100644
index 0000000..7f5b56b
--- /dev/null
+++ b/playground/src/runtime/pylock.toml
@@ -0,0 +1,116 @@
+lock-version = "1.0"
+created-by = "mlbundle"
+environments = [
+ "sys_platform == 'linux' and platform_machine == 'x86_64'",
+ "sys_platform == 'linux' and platform_machine == 'aarch64'",
+ "sys_platform == 'win32' and platform_machine == 'AMD64'",
+]
+requires-python = "==3.14.2"
+
+[[packages]]
+name = "annotated-types"
+version = "0.8.0"
+wheels = [
+ { name = "annotated_types-0.8.0-py3-none-any.whl", url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", size = 13427, hashes = { sha256 = "f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0" } },
+]
+
+[[packages]]
+name = "joblib"
+version = "1.5.3"
+wheels = [
+ { name = "joblib-1.5.3-py3-none-any.whl", url = "https://files.pythonhosted.org/packages/7b/91/984aca2ec129e2757d1e4e3c81c3fcda9d0f85b74670a094cc443d9ee949/joblib-1.5.3-py3-none-any.whl", size = 309071, hashes = { sha256 = "5fc3c5039fc5ca8c0276333a188bbd59d6b7ab37fe6632daa76bc7f9ec18e713" } },
+]
+
+[[packages]]
+name = "numpy"
+version = "2.4.6"
+wheels = [
+ { name = "numpy-2.4.6-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", url = "https://files.pythonhosted.org/packages/d5/91/64288395ee1799bd2e0b04a305dce9666da90c961e1f3fe982a05ee1c036/numpy-2.4.6-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", size = 15685197, hashes = { sha256 = "40fdc1ae7125e518ea98e53e69a4ebc27e1fd50510c47b7ea130cf21e5e1d42b" } },
+ { name = "numpy-2.4.6-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", url = "https://files.pythonhosted.org/packages/f3/eb/ebffaa97dc55502df69584a8f0dcf07f69a3e0b3e2323670a2722db9aa39/numpy-2.4.6-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", size = 16638245, hashes = { sha256 = "a2c306dea656c12c68f51f4cea133cbe78ca7435eb28c735eac1d3ebe73be6e8" } },
+ { name = "numpy-2.4.6-cp314-cp314-win_amd64.whl", url = "https://files.pythonhosted.org/packages/df/ac/46de6dda46478f7942f839e094970be2d4a861e005c4b3bf07c92e291a09/numpy-2.4.6-cp314-cp314-win_amd64.whl", size = 12450334, hashes = { sha256 = "b507f5c4c1d508876d1819b6bf9a49d365b96320b5d4993426b33a23ca4b8261" } },
+]
+
+[[packages]]
+name = "packaging"
+version = "26.3"
+wheels = [
+ { name = "packaging-26.3-py3-none-any.whl", url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", size = 129956, hashes = { sha256 = "d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c" } },
+]
+
+[[packages]]
+name = "prettytable"
+version = "3.18.0"
+wheels = [
+ { name = "prettytable-3.18.0-py3-none-any.whl", url = "https://files.pythonhosted.org/packages/fe/be/2e6798ace5cc036f5d05d36b7b2fd85346f1a708c87060890b070d0ec607/prettytable-3.18.0-py3-none-any.whl", size = 37357, hashes = { sha256 = "b3346e0e6f79180833aebaac088ae926340586cf6d7d991b9eb125b65f72313a" } },
+]
+
+[[packages]]
+name = "pydantic"
+version = "2.14.1"
+wheels = [
+ { name = "pydantic-2.14.1-py3-none-any.whl", url = "https://files.pythonhosted.org/packages/35/ea/a56b9fe5066f3537b7882f77e9c5dfb26d8c2eefdaed9b5fc73d57b4dc22/pydantic-2.14.1-py3-none-any.whl", size = 488106, hashes = { sha256 = "9195d967ec791692a04438115466764fb8b9a27b31f14a760437694f40d6b454" } },
+]
+
+[[packages]]
+name = "pydantic-core"
+version = "2.50.1"
+wheels = [
+ { name = "pydantic_core-2.50.1-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", url = "https://files.pythonhosted.org/packages/a1/4e/5eb629f6efc2a27e421d789dd4bfacbb5f6d09c80c28b13d1e87d73163d5/pydantic_core-2.50.1-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", size = 2049435, hashes = { sha256 = "0036473f5583e6a60e50b8b21651511564277a3f05cc5dab8cf579f552cd5f6c" } },
+ { name = "pydantic_core-2.50.1-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", url = "https://files.pythonhosted.org/packages/45/35/38f6d6564fae57d9b12e5676dfa947e0e7d5c46dbeaa7eb3352261d6d299/pydantic_core-2.50.1-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", size = 2159857, hashes = { sha256 = "42b54c2c90ad348b5e3a85e03e715d572c1fde357ef104cdfe3b03b697a404ea" } },
+ { name = "pydantic_core-2.50.1-cp314-cp314-win_amd64.whl", url = "https://files.pythonhosted.org/packages/14/4c/350a2415209c43d670eb71d3c040f332c04a30583d39e311b05c7ac15762/pydantic_core-2.50.1-cp314-cp314-win_amd64.whl", size = 2171586, hashes = { sha256 = "d32f3acc081cc3923386d88f422cde8892335e95f034e0104bb4cf9310d9915f" } },
+]
+
+[[packages]]
+name = "scikit-learn"
+version = "1.8.0"
+wheels = [
+ { name = "scikit_learn-1.8.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", url = "https://files.pythonhosted.org/packages/be/ce/a0623350aa0b68647333940ee46fe45086c6060ec604874e38e9ab7d8e6c/scikit_learn-1.8.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", size = 8657133, hashes = { sha256 = "29ffc74089f3d5e87dfca4c2c8450f88bdc61b0fc6ed5d267f3988f19a1309f6" } },
+ { name = "scikit_learn-1.8.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", url = "https://files.pythonhosted.org/packages/b8/cb/861b41341d6f1245e6ca80b1c1a8c4dfce43255b03df034429089ca2a2c5/scikit_learn-1.8.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", size = 8923223, hashes = { sha256 = "fb65db5d7531bccf3a4f6bec3462223bea71384e2cda41da0f10b7c292b9e7c4" } },
+ { name = "scikit_learn-1.8.0-cp314-cp314-win_amd64.whl", url = "https://files.pythonhosted.org/packages/76/18/a8def8f91b18cd1ba6e05dbe02540168cb24d47e8dcf69e8d00b7da42a08/scikit_learn-1.8.0-cp314-cp314-win_amd64.whl", size = 8096518, hashes = { sha256 = "56079a99c20d230e873ea40753102102734c5953366972a71d5cb39a32bc40c6" } },
+]
+
+[[packages]]
+name = "scipy"
+version = "1.18.0"
+wheels = [
+ { name = "scipy-1.18.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", url = "https://files.pythonhosted.org/packages/f6/e6/ba89ec5abf6ee9257c0d1ec985573f3ae32742c24bc03e016388a40b1b15/scipy-1.18.0-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", size = 33998032, hashes = { sha256 = "40395a5fcd1abee49a5c7aaa98c29db393eedc835138560a588c47ec16156690" } },
+ { name = "scipy-1.18.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", url = "https://files.pythonhosted.org/packages/7f/c4/bc41eb19b0fd0db868f4132920879019318d80cc522ad8f2bca4611af808/scipy-1.18.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", size = 35283333, hashes = { sha256 = "8ca01e8ae69f1b18e9a58d91afead31be3cef0dd905a10249dac559ee15460a0" } },
+ { name = "scipy-1.18.0-cp314-cp314-win_amd64.whl", url = "https://files.pythonhosted.org/packages/93/3e/902d836831474b0ab5a37d16404f7bc5fafd9efba632890e271ba952635f/scipy-1.18.0-cp314-cp314-win_amd64.whl", size = 37288845, hashes = { sha256 = "2d8bbdc6c817f5b4006a54d799d4f5bab6f910193cbb9a1ff310833d4d270f61" } },
+]
+
+[[packages]]
+name = "skops"
+version = "0.16.0"
+wheels = [
+ { name = "skops-0.16.0-py3-none-any.whl", url = "https://files.pythonhosted.org/packages/44/a3/08ae9ea7f7c16e20a447d9289dce40f06f52607ed9a39f554a8426d96ba3/skops-0.16.0-py3-none-any.whl", size = 148650, hashes = { sha256 = "5b2eb1bc49392c74a38db04481e2d110f97d9a72d6ae38fbd698aa7a865a9070" } },
+]
+
+[[packages]]
+name = "threadpoolctl"
+version = "3.6.0"
+wheels = [
+ { name = "threadpoolctl-3.6.0-py3-none-any.whl", url = "https://files.pythonhosted.org/packages/32/d5/f9a850d79b0851d1d4ef6456097579a9005b31fea68726a4ae5f2d82ddd9/threadpoolctl-3.6.0-py3-none-any.whl", size = 18638, hashes = { sha256 = "43a0b8fd5a2928500110039e43a5eed8480b918967083ea48dc3ab9f13c4a7fb" } },
+]
+
+[[packages]]
+name = "typing-extensions"
+version = "4.16.0"
+wheels = [
+ { name = "typing_extensions-4.16.0-py3-none-any.whl", url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", size = 45571, hashes = { sha256 = "481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8" } },
+]
+
+[[packages]]
+name = "typing-inspection"
+version = "0.4.4"
+wheels = [
+ { name = "typing_inspection-0.4.4-py3-none-any.whl", url = "https://files.pythonhosted.org/packages/67/81/4add07e5172b7ac40d8ed5ff580409a7801a4fe26d529bdd915401dabfbe/typing_inspection-0.4.4-py3-none-any.whl", size = 14750, hashes = { sha256 = "65b8397ba37ccbce054456aaccddfc91e6e3083c92824df348d96ca832f3f147" } },
+]
+
+[[packages]]
+name = "wcwidth"
+version = "0.9.2"
+wheels = [
+ { name = "wcwidth-0.9.2-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", url = "https://files.pythonhosted.org/packages/bc/f0/b8ef7758003d66b60f093695831a86dcc726aac01ee6446ffcbda27b61e3/wcwidth-0.9.2-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", size = 771632, hashes = { sha256 = "674b518af28d38ee645ff97b74f5760abee5fad4bac74413bfc4b881ef2ce724" } },
+ { name = "wcwidth-0.9.2-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", url = "https://files.pythonhosted.org/packages/db/6c/f940133c71427c208575910e981942bd78c98b1f7cd0d1425ca4b7457c04/wcwidth-0.9.2-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", size = 769763, hashes = { sha256 = "751bef0ab404b6a1dc028b56b4b85d46486be1c55833f80da533e42dc691f389" } },
+ { name = "wcwidth-0.9.2-cp310-abi3-win_amd64.whl", url = "https://files.pythonhosted.org/packages/5a/d6/b0690f55ea0483530a18bac917fbadbf54f35122510446fc370f5f1c2453/wcwidth-0.9.2-cp310-abi3-win_amd64.whl", size = 597827, hashes = { sha256 = "2a9746de704242bd4fdaabb31dd46b82f694a56a8d21081ad89b679a89da9fec" } },
+]
diff --git a/playground/src/runtime/session.ts b/playground/src/runtime/session.ts
index 4c9fdac..d926973 100644
--- a/playground/src/runtime/session.ts
+++ b/playground/src/runtime/session.ts
@@ -37,17 +37,20 @@ const writeSources = (pyodide: PyodideAPI, sources: SourceTree, version: string)
};
const UPLOAD_PATH = "/uploads/upload.mlbundle";
+// harness.py copies it into each run directory as pylock.toml.
+const LOCK_PATH = "/lock/pylock.toml";
/**
* Prepare a loaded Pyodide instance: install the pinned wheels, write the real
- * mlbundle sources and load the execution harness. Shared by the browser worker
- * and the Node runtime tests so both exercise the same path.
+ * mlbundle sources and the session's runtime lock, and load the execution harness.
+ * Shared by the browser worker and the Node runtime tests so both exercise the same path.
*/
export const startSession = async (
pyodide: PyodideAPI,
sources: SourceTree,
pyproject: string,
harness: string,
+ lock: string,
onProgress: (message: string) => void = () => {},
): Promise => {
onProgress("Loading scikit-learn and pandas…");
@@ -61,6 +64,8 @@ export const startSession = async (
}
onProgress("Loading mlbundle…");
writeSources(pyodide, sources, projectVersion(pyproject));
+ pyodide.FS.mkdirTree(LOCK_PATH.slice(0, LOCK_PATH.lastIndexOf("/")));
+ pyodide.FS.writeFile(LOCK_PATH, lock);
const namespace = pyodide.toPy({});
pyodide.runPython(harness, { globals: namespace, filename: "harness.py" });
const versionsOf = namespace.get("runtime_versions");
diff --git a/playground/src/runtime/sources.ts b/playground/src/runtime/sources.ts
index cbfdf05..3222545 100644
--- a/playground/src/runtime/sources.ts
+++ b/playground/src/runtime/sources.ts
@@ -1,5 +1,6 @@
import type { SourceTree } from "./session.ts";
import pyproject from "../../../pyproject.toml?raw";
+import lock from "./pylock.toml?raw";
// The repository's real package source, bundled at build time. Never a copy.
// state_fields.json is package data the sklearn adapter reads at import time.
@@ -13,3 +14,6 @@ export const MLBUNDLE_SOURCES: SourceTree = Object.fromEntries(
);
export const PYPROJECT = pyproject;
+
+// Written by scripts/lock.py for this session's exact versions; Pyodide cannot run uv.
+export const PLAYGROUND_LOCK = lock;
diff --git a/playground/src/runtime/worker.ts b/playground/src/runtime/worker.ts
index 82b6a1e..bfa9339 100644
--- a/playground/src/runtime/worker.ts
+++ b/playground/src/runtime/worker.ts
@@ -1,7 +1,7 @@
import type { FromWorker, ToWorker } from "./protocol.ts";
import harness from "./harness.py?raw";
import { startSession, type PythonSession } from "./session.ts";
-import { MLBUNDLE_SOURCES, PYPROJECT } from "./sources.ts";
+import { MLBUNDLE_SOURCES, PLAYGROUND_LOCK, PYPROJECT } from "./sources.ts";
import { OUTPUT_LIMIT_CHARS, PYODIDE_INDEX_URL } from "./versions.ts";
// The DOM and WebWorker libs conflict in one program; type only what is used.
@@ -33,7 +33,7 @@ const boot = async (): Promise => {
stdout: forward("stdout"),
stderr: forward("stderr"),
});
- return startSession(pyodide, MLBUNDLE_SOURCES, PYPROJECT, harness, (message) =>
+ return startSession(pyodide, MLBUNDLE_SOURCES, PYPROJECT, harness, PLAYGROUND_LOCK, (message) =>
post({ type: "progress", message }),
);
};
diff --git a/playground/tests/runtime/examples.test.ts b/playground/tests/runtime/examples.test.ts
index 23b4045..dc588fa 100644
--- a/playground/tests/runtime/examples.test.ts
+++ b/playground/tests/runtime/examples.test.ts
@@ -56,7 +56,15 @@ test("the classifier example writes a verified bundle with a tree", async () =>
assert.deepEqual(value(report), [["cold", "warm"]]);
assert.equal(model(bundle).estimator_class, "DecisionTreeClassifier");
assert.equal(model(bundle).kind, "classifier");
- assert.deepEqual(names(bundle), ["manifest.json", "model.skops", "schema.json", "structure.json"]);
+ assert.deepEqual(names(bundle), [
+ "manifest.json",
+ "model.skops",
+ "schema.json",
+ "structure.json",
+ "pylock.toml",
+ ]);
+ assert.equal(bundle.environment?.pythonVersion, session.versions.python);
+ assert.ok(bundle.environment?.packages.some(([name, version]) => name === "scikit-learn" && version === session.versions["scikit-learn"]));
for (const member of bundle.members!.slice(1)) assert.match(member.sha256 ?? "", /^[0-9a-f]{64}$/);
assert.equal(bundle.structure!.family, "decision_tree");
assert.equal(bundle.samples, null);
@@ -65,7 +73,7 @@ test("the classifier example writes a verified bundle with a tree", async () =>
assert.deepEqual([...bundle.bytes!.subarray(0, 4)], [0x50, 0x4b, 0x03, 0x04]);
const environment = bundle.manifest!.environment as Obj;
assert.equal(environment.os, "Emscripten");
- assert.equal((environment.packages as Obj)["scikit-learn"], session.versions["scikit-learn"]);
+ assert.equal(environment.packages, undefined);
});
test("the regressor example records one tree per estimator", async () => {
@@ -143,8 +151,9 @@ test("user edits run as written in a fresh namespace and directory", async () =>
const stray = await session.run("open('stray.mlbundle', 'wb').write(b'not a zip')\nleftover = 1");
assert.equal(stray.bundles[0]!.status, "rejected");
assert.equal(stray.bundles[0]!.bytes, undefined);
+ // A fresh directory holds only the session's runtime lock, never earlier files.
const next = await session.run("import os\nsorted(os.listdir('.'))");
- assert.deepEqual(next.outcome, { kind: "json", text: "[]" });
+ assert.deepEqual(JSON.parse((next.outcome as { text: string }).text), ["pylock.toml"]);
assert.deepEqual(next.bundles, []);
const name = await session.run("leftover");
assert.match((name.outcome as { text: string }).text, /NameError/);
diff --git a/playground/tests/runtime/load.ts b/playground/tests/runtime/load.ts
index a8cf690..e366755 100644
--- a/playground/tests/runtime/load.ts
+++ b/playground/tests/runtime/load.ts
@@ -36,5 +36,6 @@ export const bootNodeSession = async (): Promise => {
readSources(),
readFileSync(join(repoRoot, "pyproject.toml"), "utf8"),
readFileSync(join(here, "../../src/runtime/harness.py"), "utf8"),
+ readFileSync(join(here, "../../src/runtime/pylock.toml"), "utf8"),
);
};
diff --git a/playground/tests/unit/config.test.ts b/playground/tests/unit/config.test.ts
index 18b1e5f..2cb0048 100644
--- a/playground/tests/unit/config.test.ts
+++ b/playground/tests/unit/config.test.ts
@@ -21,6 +21,27 @@ test("pure-Python pins match the repository lock", () => {
}
});
+test("the runtime lock matches this Pyodide release and the PyPI pins", () => {
+ // Regenerate with scripts/lock.py whenever Pyodide or PYPI_PINS change.
+ const lock = read("../../src/runtime/pylock.toml");
+ const pyodide = JSON.parse(read("../../node_modules/pyodide/pyodide-lock.json")) as {
+ info: { python: string };
+ packages: Record;
+ };
+ const locked = new Map(
+ [...lock.matchAll(/^name = "([^"]+)"\nversion = "([^"]+)"$/gm)].map((match) => [match[1]!, match[2]!]),
+ );
+ assert.match(lock, new RegExp(`^requires-python = "==${pyodide.info.python.replaceAll(".", "\\.")}"$`, "m"));
+ for (const name of ["numpy", "scipy", "scikit-learn", "joblib", "threadpoolctl"]) {
+ assert.equal(locked.get(name), pyodide.packages[name]!.version, name);
+ }
+ for (const pin of PYPI_PINS) {
+ const [name, version] = pin.split("==") as [string, string];
+ if (locked.has(name)) assert.equal(locked.get(name), version, pin);
+ }
+ assert.ok(!locked.has("mlbundle"));
+});
+
test("the bundled package reports the version pyproject.toml declares", () => {
const pyproject = read("../../../pyproject.toml");
const declared = /^version = "([^"]+)"/m.exec(pyproject)![1];
diff --git a/pyproject.toml b/pyproject.toml
index cab1387..c773bf6 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "mlbundle"
-version = "0.2.1"
+version = "0.3.0"
description = "Pickle-free, verifiable model bundles with a manifest, schema and structure."
readme = "README.md"
license = "MIT"
@@ -47,10 +47,12 @@ catboost = ["catboost>=1.2.10"]
onnx = ["onnx>=1.23.0", "onnxruntime>=1.30.0"]
# The reader validates the 0.3 vocabulary; schema inference requires Python 3.14.
schema = ["mlschema>=0.3.0,<0.4; python_version == '3.14'"]
+# Export resolves pylock.toml with uv's per-platform pylock output.
+lock = ["uv>=0.13.5"]
all = [
"scikit-learn>=1.6", "skops>=0.16.0", "xgboost>=3.4.1", "catboost>=1.2.10",
"onnx>=1.23.0", "onnxruntime>=1.30.0",
- "mlschema>=0.3.0,<0.4; python_version == '3.14'",
+ "mlschema>=0.3.0,<0.4; python_version == '3.14'", "uv>=0.13.5",
]
[project.urls]
@@ -78,6 +80,7 @@ build-backend = "uv_build"
[tool.pytest.ini_options]
minversion = "8.0"
testpaths = ["tests"]
+markers = ["network: resolves real locks through the package index"]
addopts = [
"-ra",
"--strict-markers",
diff --git a/scripts/package_smoke.py b/scripts/package_smoke.py
index 13cbefe..344c306 100644
--- a/scripts/package_smoke.py
+++ b/scripts/package_smoke.py
@@ -52,9 +52,12 @@ def _base(path: Path) -> None:
import mlbundle
- assert mlbundle.__version__ == "0.2.1"
+ assert mlbundle.__version__ == "0.3.0"
view = mlbundle.inspect(path)
assert view.manifest.model.library == "sklearn"
+ # The runtime lock parses with the standard library alone.
+ assert view.environment_lock.version("scikit-learn")
+ assert "Environment id: " in _console("inspect", str(path))
assert "cannot attest" in _console("--help")
assert "model claims NOT verified" in _console("inspect", str(path))
assert json.loads(
diff --git a/src/mlbundle/__init__.py b/src/mlbundle/__init__.py
index 6950961..cedeb37 100644
--- a/src/mlbundle/__init__.py
+++ b/src/mlbundle/__init__.py
@@ -2,6 +2,7 @@
from importlib.metadata import version as _version
+from ._environment_check import check_environment
from .claims import ModelClaims
from .contract import (
FORMAT_NAME,
@@ -19,12 +20,14 @@
EnvironmentMismatchError,
IntegrityMismatchError,
InvalidContainerError,
+ InvalidEnvironmentLockError,
InvalidJSONError,
InvalidManifestError,
InvalidModelError,
InvalidSamplesError,
InvalidSchemaError,
LimitExceededError,
+ LockGenerationError,
MissingOptionalDependencyError,
MLBundleError,
PredictionInputError,
@@ -34,6 +37,7 @@
from .inspection import inspect
from .integrity import IntegrityRecord
from .limits import ArchiveLimits
+from .lock import EnvironmentLock, LockedPackage, LockedWheel
from .manifest import FeatureInfo, Manifest, MemberReferences, ModelInfo, TargetInfo
from .model_io import export, load
from .records import OutputPrediction
@@ -47,12 +51,14 @@
"AdapterNotImplementedError",
"ArchiveLimits",
"ClaimMismatchError",
+ "EnvironmentLock",
"EnvironmentMismatchError",
"FeatureInfo",
"FeatureOrigin",
"IntegrityMismatchError",
"IntegrityRecord",
"InvalidContainerError",
+ "InvalidEnvironmentLockError",
"InvalidJSONError",
"InvalidManifestError",
"InvalidModelError",
@@ -61,6 +67,9 @@
"Library",
"LimitExceededError",
"LoadedBundle",
+ "LockGenerationError",
+ "LockedPackage",
+ "LockedWheel",
"MLBundleError",
"Manifest",
"MemberName",
@@ -80,6 +89,7 @@
"UnsupportedFormatVersionError",
"UnsupportedModelError",
"__version__",
+ "check_environment",
"export",
"inspect",
"load",
diff --git a/src/mlbundle/_container_rules.py b/src/mlbundle/_container_rules.py
index b584f0f..390e71a 100644
--- a/src/mlbundle/_container_rules.py
+++ b/src/mlbundle/_container_rules.py
@@ -20,6 +20,7 @@
MemberName.SCHEMA,
MemberName.STRUCTURE,
MemberName.SAMPLES,
+ MemberName.LOCK,
)
@@ -52,6 +53,10 @@ def check_members(
{MemberName.SKOPS, MemberName.CBM},
):
raise InvalidContainerError("Invalid model member combination.")
+ if MemberName.LOCK not in present:
+ raise InvalidContainerError(
+ "Bundle predates the required pylock.toml and must be re-exported."
+ )
if manifest is not None and present != {MemberName.MANIFEST, *manifest.integrity}:
raise InvalidContainerError("Members disagree with manifest references.")
diff --git a/src/mlbundle/_environment_check.py b/src/mlbundle/_environment_check.py
new file mode 100644
index 0000000..b2d9b24
--- /dev/null
+++ b/src/mlbundle/_environment_check.py
@@ -0,0 +1,111 @@
+"""Compare a running interpreter with a bundle's lock, before loading its model."""
+
+from __future__ import annotations
+
+import os
+import platform
+import re
+import sys
+import sysconfig
+from dataclasses import dataclass
+from importlib import metadata
+
+from ._display import display
+from ._lock_generation import source_tree
+from ._wheel_tags import normalize
+from .errors import EnvironmentMismatchError
+from .results import LoadedBundle, MetadataView
+
+_GLIBC = re.compile(r"glibc ([0-9]{1,3})\.([0-9]{1,3})")
+
+
+@dataclass(frozen=True)
+class RuntimeFacts:
+ implementation: str
+ python_version: str
+ gil_disabled: bool
+ # As sysconfig.get_platform() reports it, such as linux-x86_64 or win-amd64.
+ platform: str
+ glibc: tuple[int, int] | None
+ # Installed versions; None marks duplicate and editable, directory or VCS installs.
+ distributions: dict[str, str | None]
+
+ @classmethod
+ def current(cls) -> RuntimeFacts:
+ distributions: dict[str, str | None] = {}
+ for distribution in metadata.distributions():
+ name = distribution.metadata["Name"]
+ if not isinstance(name, str):
+ continue
+ key = normalize(name)
+ distributions[key] = (
+ None
+ if key in distributions or source_tree(distribution)
+ else distribution.version
+ )
+ try:
+ libc = os.confstr("CS_GNU_LIBC_VERSION") or ""
+ except (AttributeError, OSError, ValueError):
+ libc = ""
+ found = _GLIBC.fullmatch(libc)
+ return cls(
+ implementation=sys.implementation.name,
+ python_version=platform.python_version(),
+ gil_disabled=bool(sysconfig.get_config_var("Py_GIL_DISABLED")),
+ platform=sysconfig.get_platform(),
+ glibc=None if found is None else (int(found[1]), int(found[2])),
+ distributions=distributions,
+ )
+
+
+def environment_problems(
+ bundle: MetadataView | LoadedBundle, facts: RuntimeFacts
+) -> list[str]:
+ lock = bundle.environment_lock
+ problems = []
+ if facts.implementation != "cpython" or facts.gil_disabled:
+ problems.append("the interpreter is not CPython with the GIL")
+ if facts.python_version != lock.python_version:
+ problems.append(
+ f"Python {display(facts.python_version)} is not {lock.python_version}"
+ )
+ if facts.platform not in lock.platforms:
+ problems.append(f"platform {display(facts.platform)} is not a target")
+ elif facts.platform.startswith("linux-") and (
+ facts.glibc is None or facts.glibc < lock.glibc
+ ):
+ problems.append("glibc 2.28 or newer is required")
+ expected = {
+ package.name: package.version
+ for package in lock.packages
+ if facts.platform in package.platforms
+ }
+ expected["mlbundle"] = bundle.manifest.writer_version
+ for name in sorted(expected.keys() | facts.distributions.keys()):
+ wanted = expected.get(name)
+ if name not in facts.distributions:
+ problems.append(f"{name} {wanted} is not installed")
+ elif wanted is None:
+ problems.append(f"{display(name)} is installed but not locked")
+ elif facts.distributions[name] is None:
+ problems.append(f"{name} is duplicated or installed from a source tree")
+ elif facts.distributions[name] != wanted:
+ installed = display(facts.distributions[name])
+ problems.append(f"{name} {installed} is installed, {wanted} is locked")
+ return problems
+
+
+def check_environment(bundle: MetadataView | LoadedBundle) -> None:
+ """Require exactly the bundle's lock plus mlbundle at its writer version.
+
+ Runtimes call this in the isolated process that will load the model. It reads
+ installed distribution metadata only: it imports no model library and does
+ not verify file hashes, which the installer checks against the lock.
+ """
+ problems = environment_problems(bundle, RuntimeFacts.current())
+ if problems:
+ raise EnvironmentMismatchError(
+ "The environment differs from the bundle lock: "
+ + "; ".join(problems[:10])
+ + ("; ..." if len(problems) > 10 else "")
+ )
diff --git a/src/mlbundle/_export_manifest.py b/src/mlbundle/_export_manifest.py
index 5f92f06..614fba6 100644
--- a/src/mlbundle/_export_manifest.py
+++ b/src/mlbundle/_export_manifest.py
@@ -51,6 +51,7 @@ def manifest_parts(
"references": {
"structure": None if structure is None else MemberName.STRUCTURE.value,
"schema": MemberName.SCHEMA.value,
+ "lock": MemberName.LOCK.value,
"samples": None if training.samples is None else MemberName.SAMPLES.value,
},
"user_metadata": {} if metadata is None else dict(metadata),
diff --git a/src/mlbundle/_lock_generation.py b/src/mlbundle/_lock_generation.py
new file mode 100644
index 0000000..61ff75c
--- /dev/null
+++ b/src/mlbundle/_lock_generation.py
@@ -0,0 +1,247 @@
+"""Training-side locks: installed versions pin one uv resolution per target."""
+
+from __future__ import annotations
+
+import json
+import platform
+import re
+import subprocess
+import tempfile
+import tomllib
+from collections.abc import Mapping, Sequence
+from importlib import metadata
+from pathlib import Path
+from urllib.parse import unquote, urlsplit
+
+from pydantic import ValidationError
+
+from ._display import display
+from ._wheel_tags import PLATFORMS, UV_PLATFORMS, Platform, normalize, select
+from .errors import (
+ InvalidEnvironmentLockError,
+ LockGenerationError,
+ MissingOptionalDependencyError,
+)
+from .lock import (
+ NAME_PATTERN,
+ VERSION_PATTERN,
+ EnvironmentLock,
+ LockedPackage,
+ LockedWheel,
+)
+
+TIMEOUT_SECONDS = 600
+
+
+def source_tree(distribution: metadata.Distribution) -> bool:
+ """Whether PEP 610 records an editable, directory or VCS install.
+
+ Their versions do not identify files. Wheels installed from a file or URL
+ (archive_info) keep the version their metadata declares.
+ """
+ record = distribution.read_text("direct_url.json")
+ if record is None:
+ return False
+ try:
+ value = json.loads(record)
+ except ValueError:
+ return True
+ return not isinstance(value, dict) or "archive_info" not in value
+
+
+def installed_distributions() -> dict[str, str | None]:
+ """First distribution per normalized name on sys.path, as imports resolve it.
+
+ Source-tree and local-version installs map to None: no index can supply
+ their files, so they can never be pinned faithfully.
+ """
+ found: dict[str, str | None] = {}
+ for distribution in metadata.distributions():
+ name = distribution.metadata["Name"]
+ if not isinstance(name, str):
+ continue
+ name = normalize(name)
+ if name in found or re.fullmatch(NAME_PATTERN, name) is None:
+ continue
+ version = distribution.version
+ faithful = (
+ isinstance(version, str)
+ and re.fullmatch(VERSION_PATTERN, version) is not None
+ and not source_tree(distribution)
+ )
+ found[name] = version if faithful else None
+ return found
+
+
+def roots(
+ groups: Sequence[Sequence[str]], installed: Mapping[str, str | None]
+) -> dict[str, str]:
+ pinned: dict[str, str] = {}
+ for group in groups:
+ present = [name for name in group if name in installed]
+ if len(present) != 1:
+ raise LockGenerationError(
+ f"Exactly one of {', '.join(group)} must be installed to lock."
+ )
+ version = installed[present[0]]
+ if version is None:
+ raise LockGenerationError(
+ f"{present[0]} is installed from a source tree or local version."
+ )
+ pinned[present[0]] = version
+ return pinned
+
+
+def _uv() -> str:
+ try:
+ from uv import find_uv_bin # noqa: PLC0415
+ except ImportError:
+ raise MissingOptionalDependencyError("lock") from None
+ return find_uv_bin()
+
+
+def _compile(
+ uv: str, work: Path, python_version: str, target: Platform
+) -> list[dict[str, object]]:
+ output = work / f"pylock.{target.replace('-', '_')}.toml"
+ command = [
+ uv, "pip", "compile", "requirements.in", "--constraints", "constraints.txt",
+ "--python-version", python_version,
+ "--python-platform", UV_PLATFORMS[target],
+ "--only-binary", ":all:", "--no-header", "--quiet", "--color", "never",
+ "--output-file", output.name,
+ ] # fmt: skip
+ try:
+ result = subprocess.run(
+ command,
+ check=False,
+ cwd=work,
+ capture_output=True,
+ text=True,
+ timeout=TIMEOUT_SECONDS,
+ )
+ except subprocess.TimeoutExpired:
+ raise LockGenerationError("uv timed out resolving the lock.") from None
+ if result.returncode != 0:
+ detail = display(result.stderr.strip()[-2000:], limit=2048)
+ raise LockGenerationError(f"uv could not lock {target}: {detail}")
+ with output.open("rb") as stream:
+ packages = tomllib.load(stream).get("packages", [])
+ if not isinstance(packages, list):
+ raise LockGenerationError("uv wrote an unexpected lock.")
+ return packages
+
+
+def _wheel(
+ package: dict[str, object], target: Platform, minor: int
+) -> tuple[str, str, LockedWheel]:
+ name, version = package.get("name"), package.get("version")
+ files = package.get("wheels")
+ if not isinstance(name, str) or not isinstance(version, str):
+ raise LockGenerationError("uv wrote an unexpected lock.")
+ records = {}
+ for file in files if isinstance(files, list) else []:
+ url = file.get("url") if isinstance(file, dict) else None
+ if isinstance(url, str):
+ records[unquote(urlsplit(url).path.rpartition("/")[2])] = file
+ chosen = select(list(records), target, minor)
+ if chosen is None:
+ raise LockGenerationError(
+ f"{display(name)} {display(version)} has no single preferred CPython "
+ f"wheel for {target}."
+ )
+ file = records[chosen]
+ try:
+ wheel = LockedWheel.model_validate(
+ {
+ "name": chosen,
+ "url": file["url"],
+ "size": file.get("size"),
+ "sha256": (file.get("hashes") or {}).get("sha256"),
+ }
+ )
+ except (ValidationError, AttributeError):
+ raise LockGenerationError(
+ f"{display(name)} has an unsupported wheel record."
+ ) from None
+ return normalize(name), version, wheel
+
+
+def resolve_lock(
+ python_version: str, pins: Mapping[str, str], constraints: Mapping[str, str]
+) -> EnvironmentLock:
+ """Resolve pinned roots per target with uv, wheels only, and merge the results."""
+ uv = _uv()
+ minor = int(python_version.split(".")[1])
+ found: dict[str, tuple[str, list[Platform], dict[str, LockedWheel]]] = {}
+ with tempfile.TemporaryDirectory(prefix="mlbundle-lock-") as directory:
+ work = Path(directory)
+ lines = (f"{name}=={version}\n" for name, version in sorted(pins.items()))
+ (work / "requirements.in").write_text("".join(lines), encoding="utf-8")
+ lines = (
+ f"{name}=={version}\n" for name, version in sorted(constraints.items())
+ )
+ (work / "constraints.txt").write_text("".join(lines), encoding="utf-8")
+ for target in PLATFORMS:
+ for package in _compile(uv, work, python_version, target):
+ name, version, wheel = _wheel(package, target, minor)
+ previous = found.setdefault(name, (version, [], {}))
+ if previous[0] != version:
+ raise LockGenerationError(
+ f"{name} resolves to different versions per platform."
+ )
+ previous[1].append(target)
+ previous[2][wheel.name] = wheel
+ try:
+ return EnvironmentLock(
+ python_version=python_version,
+ packages=tuple(
+ LockedPackage(
+ name=name,
+ version=version,
+ platforms=tuple(targets),
+ wheels=tuple(wheels[key] for key in sorted(wheels)),
+ )
+ for name, (version, targets, wheels) in sorted(found.items())
+ if name != "mlbundle"
+ ),
+ )
+ except ValidationError:
+ raise LockGenerationError("The resolved environment is not lockable.") from None
+
+
+def check_fidelity(
+ lock: EnvironmentLock, installed: Mapping[str, str | None] | None = None
+) -> None:
+ """Every locked distribution present at training must be the installed one."""
+ current = installed_distributions() if installed is None else installed
+ if lock.python_version != platform.python_version():
+ raise InvalidEnvironmentLockError("The lock's Python is not the running one.")
+ problems = []
+ for package in lock.packages:
+ if package.name not in current:
+ continue # Needed only on other targets, such as NCCL on Linux.
+ version = current[package.name]
+ if version != package.version:
+ problems.append(
+ f"{package.name} locked {package.version}, installed "
+ f"{'from a source tree' if version is None else display(version)}"
+ )
+ if problems:
+ raise InvalidEnvironmentLockError(
+ "The lock disagrees with the training environment: "
+ + "; ".join(problems[:10])
+ + ("; ..." if len(problems) > 10 else "")
+ )
+
+
+def generate_lock(groups: Sequence[Sequence[str]]) -> EnvironmentLock:
+ """Lock the running interpreter's installed versions of the model's runtime."""
+ installed = installed_distributions()
+ pins = roots(groups, installed)
+ constraints = {
+ name: version
+ for name, version in installed.items()
+ if version is not None and name != "mlbundle"
+ }
+ return resolve_lock(platform.python_version(), pins, constraints)
diff --git a/src/mlbundle/_lock_toml.py b/src/mlbundle/_lock_toml.py
new file mode 100644
index 0000000..72b4355
--- /dev/null
+++ b/src/mlbundle/_lock_toml.py
@@ -0,0 +1,137 @@
+"""Canonical TOML for the lock: one spelling, so every TOML parser reads the same data."""
+
+from __future__ import annotations
+
+import tomllib
+from collections.abc import Sequence
+from itertools import combinations
+from typing import TYPE_CHECKING, Any, TypedDict
+
+from ._wheel_tags import MARKERS, PLATFORMS, Platform
+from .errors import InvalidEnvironmentLockError
+
+if TYPE_CHECKING:
+ from .lock import LockedPackage
+
+
+def marker(platforms: Sequence[Platform]) -> str:
+ """The canonical marker of a proper subset of targets, in target order."""
+ if len(platforms) == 1:
+ return MARKERS[platforms[0]]
+ return " or ".join(f"({MARKERS[platform]})" for platform in platforms)
+
+
+_SUBSETS = {
+ marker(subset): subset
+ for size in range(1, len(PLATFORMS))
+ for subset in combinations(PLATFORMS, size)
+}
+_TOP = {"lock-version", "created-by", "environments", "requires-python", "packages"}
+_PACKAGE = {"name", "version", "marker", "wheels"}
+_WHEEL = {"name", "url", "size", "hashes"}
+
+
+class WheelRecord(TypedDict):
+ name: str
+ url: str
+ size: int
+ sha256: str
+
+
+class PackageRecord(TypedDict):
+ name: str
+ version: str
+ platforms: tuple[Platform, ...]
+ wheels: list[WheelRecord]
+
+
+def dump(python_version: str, packages: Sequence[LockedPackage]) -> bytes:
+ """Emit validated values; their character sets need no TOML escapes."""
+ lines = [
+ 'lock-version = "1.0"',
+ 'created-by = "mlbundle"',
+ "environments = [",
+ *(f' "{MARKERS[platform]}",' for platform in PLATFORMS),
+ "]",
+ f'requires-python = "=={python_version}"',
+ ]
+ for package in packages:
+ lines += ["", "[[packages]]", f'name = "{package.name}"']
+ lines.append(f'version = "{package.version}"')
+ if package.platforms != PLATFORMS:
+ lines.append(f'marker = "{marker(package.platforms)}"')
+ lines.append("wheels = [")
+ lines += [
+ f' {{ name = "{wheel.name}", url = "{wheel.url}", size = {wheel.size}, '
+ f'hashes = {{ sha256 = "{wheel.sha256}" }} }},'
+ for wheel in package.wheels
+ ]
+ lines.append("]")
+ return ("\n".join(lines) + "\n").encode("ascii")
+
+
+def _invalid() -> InvalidEnvironmentLockError:
+ return InvalidEnvironmentLockError("Invalid environment lock.")
+
+
+def _table(value: object, keys: set[str], required: set[str]) -> dict[str, Any]:
+ if not isinstance(value, dict) or not required <= value.keys() <= keys:
+ raise _invalid()
+ return value
+
+
+def _string(value: object) -> str:
+ if not isinstance(value, str):
+ raise _invalid()
+ return value
+
+
+def _wheel(value: object) -> WheelRecord:
+ wheel = _table(value, _WHEEL, _WHEEL)
+ hashes = _table(wheel["hashes"], {"sha256"}, {"sha256"})
+ size = wheel["size"]
+ if type(size) is not int:
+ raise _invalid()
+ return {
+ "name": _string(wheel["name"]),
+ "url": _string(wheel["url"]),
+ "size": size,
+ "sha256": _string(hashes["sha256"]),
+ }
+
+
+def _package(value: object) -> PackageRecord:
+ package = _table(value, _PACKAGE, _PACKAGE - {"marker"})
+ platforms: tuple[Platform, ...] = PLATFORMS
+ if "marker" in package:
+ platforms = _SUBSETS.get(_string(package["marker"]), ())
+ if not platforms:
+ raise _invalid()
+ wheels = package["wheels"]
+ if not isinstance(wheels, list):
+ raise _invalid()
+ return {
+ "name": _string(package["name"]),
+ "version": _string(package["version"]),
+ "platforms": platforms,
+ "wheels": [_wheel(wheel) for wheel in wheels],
+ }
+
+
+def parse(data: bytes) -> tuple[str, list[PackageRecord]]:
+ """Decode bounded bytes into plain records; the caller validates and re-emits."""
+ try:
+ document = tomllib.loads(data.decode("utf-8"))
+ except (UnicodeDecodeError, tomllib.TOMLDecodeError, RecursionError):
+ raise _invalid() from None
+ top = _table(document, _TOP, _TOP)
+ requires = _string(top["requires-python"])
+ if (
+ top["lock-version"] != "1.0"
+ or top["created-by"] != "mlbundle"
+ or top["environments"] != [MARKERS[platform] for platform in PLATFORMS]
+ or not requires.startswith("==")
+ or not isinstance(top["packages"], list)
+ ):
+ raise _invalid()
+ return requires[2:], [_package(package) for package in top["packages"]]
diff --git a/src/mlbundle/_wheel_tags.py b/src/mlbundle/_wheel_tags.py
new file mode 100644
index 0000000..8c90ce6
--- /dev/null
+++ b/src/mlbundle/_wheel_tags.py
@@ -0,0 +1,102 @@
+"""Closed wheel filename and tag rules for the lock's fixed targets."""
+
+import re
+from typing import Literal
+
+# Targets are named as sysconfig.get_platform() reports them on the host.
+Platform = Literal["linux-x86_64", "linux-aarch64", "win-amd64"]
+PLATFORMS: tuple[Platform, ...] = ("linux-x86_64", "linux-aarch64", "win-amd64")
+# The oldest glibc every Linux target host must provide: manylinux_2_28 and older.
+GLIBC = (2, 28)
+# PEP 508 markers selecting each target, and uv's matching --python-platform.
+MARKERS: dict[Platform, str] = {
+ "linux-x86_64": "sys_platform == 'linux' and platform_machine == 'x86_64'",
+ "linux-aarch64": "sys_platform == 'linux' and platform_machine == 'aarch64'",
+ "win-amd64": "sys_platform == 'win32' and platform_machine == 'AMD64'",
+}
+UV_PLATFORMS: dict[Platform, str] = {
+ "linux-x86_64": "x86_64-manylinux_2_28",
+ "linux-aarch64": "aarch64-manylinux_2_28",
+ "win-amd64": "x86_64-pc-windows-msvc",
+}
+
+_WHEEL = re.compile(
+ r"(?P[A-Za-z0-9_.]+)-(?P[A-Za-z0-9_.!]+)"
+ r"(?:-[0-9][A-Za-z0-9_.]*)?"
+ r"-(?P[A-Za-z0-9_.]+)-(?P[A-Za-z0-9_.]+)-(?P[A-Za-z0-9_.]+)"
+ r"\.whl"
+)
+_MANYLINUX = re.compile(r"manylinux_([0-9]{1,3})_([0-9]{1,3})_(x86_64|aarch64)")
+_LEGACY = {"manylinux1": (2, 5), "manylinux2010": (2, 12), "manylinux2014": (2, 17)}
+_CPYTHON = re.compile(r"cp3([0-9]{1,3})")
+
+
+def normalize(name: str) -> str:
+ """PEP 503 project name normalization."""
+ return re.sub(r"[-_.]+", "-", name).lower()
+
+
+def wheel_identity(filename: str) -> tuple[str, str] | None:
+ """Normalized distribution name and version spelled by a wheel filename."""
+ match = _WHEEL.fullmatch(filename)
+ if match is None:
+ return None
+ return normalize(match["dist"]), match["version"]
+
+
+def _platform_compatible(tag: str, platform: Platform) -> bool:
+ if tag == "any":
+ return True
+ if platform == "win-amd64":
+ return tag == "win_amd64"
+ architecture = platform.removeprefix("linux-")
+ match = _MANYLINUX.fullmatch(tag)
+ if match is not None:
+ glibc = (int(match[1]), int(match[2]))
+ return match[3] == architecture and glibc <= GLIBC
+ legacy, _, machine = tag.partition("_")
+ return machine == architecture and legacy in _LEGACY
+
+
+def _abi_rank(python: str, abi: str, minor: int) -> int | None:
+ """Installer preference: exact CPython ABI, then the stable ABI, then none."""
+ cpython = _CPYTHON.fullmatch(python)
+ if abi == f"cp3{minor}" and python == f"cp3{minor}":
+ return 0
+ # Free-threaded builds use a distinct ABI tag (cp3Nt) and never match here.
+ if abi == "abi3" and cpython is not None and 2 <= int(cpython[1]) <= minor:
+ return 1
+ if abi == "none" and python in ("py3", f"py3{minor}", f"cp3{minor}"):
+ return 2
+ return None
+
+
+def rank(filename: str, platform: Platform, minor: int) -> tuple[int, int] | None:
+ """Preference of a wheel on a target, lower first, as installers order tags.
+
+ Platform wheels precede pure ones; None means the target cannot install it.
+ """
+ match = _WHEEL.fullmatch(filename)
+ if match is None:
+ return None
+ ranks = [
+ (int(tag == "any"), abi_rank)
+ for python in match["python"].split(".")
+ for abi in match["abi"].split(".")
+ for tag in match["platform"].split(".")
+ if (abi_rank := _abi_rank(python, abi, minor)) is not None
+ and _platform_compatible(tag, platform)
+ ]
+ return min(ranks, default=None)
+
+
+def select(filenames: list[str], platform: Platform, minor: int) -> str | None:
+ """The one wheel an installer takes on the target, or None if none or tied."""
+ ranked = sorted(
+ (value, name)
+ for name in filenames
+ if (value := rank(name, platform, minor)) is not None
+ )
+ if not ranked or (len(ranked) > 1 and ranked[0][0] == ranked[1][0]):
+ return None
+ return ranked[0][1]
diff --git a/src/mlbundle/cli.py b/src/mlbundle/cli.py
index 5840096..9730040 100644
--- a/src/mlbundle/cli.py
+++ b/src/mlbundle/cli.py
@@ -36,6 +36,7 @@ def _summary(view: MetadataView) -> str:
manifest = view.manifest
model = manifest.model
environment = manifest.environment
+ lock = view.environment_lock
lines = [
"Metadata and integrity validated; model claims NOT verified.",
f"Format: mlbundle {manifest.format_version}",
@@ -65,12 +66,18 @@ def _summary(view: MetadataView) -> str:
{
"python": environment.python_version,
"implementation": environment.python_implementation,
+ "free_threaded": environment.free_threaded,
"os": environment.os,
"os_version": environment.os_version,
"architecture": environment.architecture,
}
),
- f"Packages: {_display(environment.packages)}",
+ f"Environment lock: CPython {lock.python_version} with the GIL, "
+ f"{', '.join(lock.platforms)} (Linux glibc {lock.glibc[0]}.{lock.glibc[1]}+), "
+ f"{len(lock.packages)} packages plus mlbundle {_display(manifest.writer_version)}",
+ f"Environment id: {lock.environment_id}",
+ "Locked packages: "
+ + _display({package.name: package.version for package in lock.packages}),
f"ONNX environment: {_display(None if environment.onnx is None else environment.onnx.model_dump(mode='json'))}",
"Present: "
+ ", ".join(
diff --git a/src/mlbundle/container.py b/src/mlbundle/container.py
index 8fc3254..215fcba 100644
--- a/src/mlbundle/container.py
+++ b/src/mlbundle/container.py
@@ -14,6 +14,7 @@
from .errors import InvalidContainerError, LimitExceededError
from .integrity import verify_integrity
from .limits import ArchiveLimits
+from .lock import EnvironmentLock, check_bundle_lock
from .manifest import Manifest
@@ -43,12 +44,13 @@ class ValidatedContainer:
manifest: Manifest
members: dict[MemberName, bytes]
json: dict[MemberName, DecodedJSON]
+ lock: EnvironmentLock
def read_validated_container(
source: BundleSource, *, limits: ArchiveLimits | None = None
) -> ValidatedContainer:
- """Validate ZIP records, bounded decompression, manifest and member integrity.
+ """Validate ZIP records, bounded decompression, manifest, integrity and lock.
Streams are consumed from their current position and are never closed here.
Model bytes remain opaque: this function does not verify model claims.
@@ -82,7 +84,9 @@ def read_validated_container(
members[entry.name] = value
except (struct.error, zlib.error, OverflowError):
raise InvalidContainerError("Corrupt ZIP container.") from None
- return ValidatedContainer(manifest, members, decoded)
+ lock = EnvironmentLock.from_bytes(members[MemberName.LOCK])
+ check_bundle_lock(lock, manifest)
+ return ValidatedContainer(manifest, members, decoded, lock)
def read_container(
diff --git a/src/mlbundle/contract.py b/src/mlbundle/contract.py
index 9db9dcd..0f9dfb4 100644
--- a/src/mlbundle/contract.py
+++ b/src/mlbundle/contract.py
@@ -43,6 +43,7 @@ class MemberName(StrEnum):
SCHEMA = "schema.json"
STRUCTURE = "structure.json"
SAMPLES = "samples.json"
+ LOCK = "pylock.toml"
MODEL_MEMBERS = MappingProxyType(
diff --git a/src/mlbundle/environment.py b/src/mlbundle/environment.py
index 67807ad..cc3df7c 100644
--- a/src/mlbundle/environment.py
+++ b/src/mlbundle/environment.py
@@ -3,40 +3,13 @@
from __future__ import annotations
import platform
-from importlib import metadata
-from typing import Annotated, Literal
+import sysconfig
+from typing import Annotated
from pydantic import Field, model_validator
from ._base import ContractModel, ShortString
-PackageName = Literal[
- "mlbundle",
- "mlschema",
- "numpy",
- "pandas",
- "scipy",
- "scikit-learn",
- "xgboost",
- "catboost",
- "onnx",
- "onnxruntime",
- "skops",
-]
-PACKAGE_NAMES: tuple[PackageName, ...] = (
- "mlbundle",
- "mlschema",
- "numpy",
- "pandas",
- "scipy",
- "scikit-learn",
- "xgboost",
- "catboost",
- "onnx",
- "onnxruntime",
- "skops",
-)
-
class Opset(ContractModel):
domain: Annotated[str, Field(max_length=256)]
@@ -58,28 +31,24 @@ def unique_domains(self) -> OnnxInfo:
class TrainingEnvironment(ContractModel):
+ """The training machine; package versions live in the bundle's pylock.toml."""
+
python_version: ShortString
python_implementation: ShortString
+ free_threaded: bool
os: ShortString
os_version: ShortString
architecture: ShortString
- packages: dict[PackageName, ShortString] = Field(max_length=len(PACKAGE_NAMES))
onnx: OnnxInfo | None = None
def capture_environment(*, onnx: OnnxInfo | None = None) -> TrainingEnvironment:
- packages: dict[PackageName, str] = {}
- for name in PACKAGE_NAMES:
- try:
- packages[name] = metadata.version(name)
- except metadata.PackageNotFoundError:
- continue
return TrainingEnvironment(
python_version=platform.python_version(),
python_implementation=platform.python_implementation(),
+ free_threaded=bool(sysconfig.get_config_var("Py_GIL_DISABLED")),
os=platform.system(),
os_version=platform.release(),
architecture=platform.machine(),
- packages=packages,
onnx=onnx,
)
diff --git a/src/mlbundle/errors.py b/src/mlbundle/errors.py
index e2108ba..137b7da 100644
--- a/src/mlbundle/errors.py
+++ b/src/mlbundle/errors.py
@@ -69,7 +69,7 @@ class InvalidModelError(MLBundleError):
class EnvironmentMismatchError(InvalidModelError):
- """A sklearn load failed under a different declared package version."""
+ """The running environment differs from the one the bundle declares."""
class PredictionInputError(InvalidModelError, ValueError):
@@ -84,6 +84,14 @@ class InvalidSamplesError(MLBundleError):
"""Sample selection or row declarations violate the samples contract."""
+class InvalidEnvironmentLockError(MLBundleError):
+ """The lock violates its contract or disagrees with its bundle or training."""
+
+
+class LockGenerationError(MLBundleError):
+ """The training environment could not be resolved into a lock."""
+
+
class MissingOptionalDependencyError(MLBundleError):
def __init__(self, extra: str) -> None:
self.extra = _identifier(extra)
diff --git a/src/mlbundle/inspection.py b/src/mlbundle/inspection.py
index 952b0dc..edd511f 100644
--- a/src/mlbundle/inspection.py
+++ b/src/mlbundle/inspection.py
@@ -10,7 +10,7 @@
def inspect(
source: BundleSource, *, limits: ArchiveLimits | None = None
) -> MetadataView:
- """Validate the container, manifest, JSON bounds and hashes without loading.
+ """Validate the container, manifest, JSON bounds, hashes and lock without loading.
Inspection cannot attest that model-derived claims or structure match the
model. Only a full validating model load can provide that guarantee.
@@ -25,6 +25,7 @@ def metadata_view(container: ValidatedContainer, limits: ArchiveLimits) -> Metad
return MetadataView(
manifest,
tuple(name for name in MEMBER_ORDER if name in members),
+ container.lock,
schema=schema,
samples=samples,
)
diff --git a/src/mlbundle/limits.py b/src/mlbundle/limits.py
index 3f3b660..fdd5610 100644
--- a/src/mlbundle/limits.py
+++ b/src/mlbundle/limits.py
@@ -8,6 +8,7 @@
MIB = 1024 * 1024
MANIFEST_BYTES = 8 * MIB
STRUCTURE_BYTES = 256 * MIB
+LOCK_BYTES = MIB
METADATA_BYTES = 64 * 1024
HYPERPARAMETER_BYTES = MIB
JSON_DEPTH = 32
@@ -17,7 +18,7 @@
class ArchiveLimits(ContractModel):
- max_members: int = Field(default=6, ge=2, le=6)
+ max_members: int = Field(default=7, ge=2, le=7)
max_archive_bytes: int = Field(default=512 * MIB, gt=0, le=512 * MIB)
max_compressed_bytes: int = Field(default=512 * MIB, gt=0, le=512 * MIB)
max_member_bytes: int = Field(default=512 * MIB, gt=0, le=512 * MIB)
@@ -27,6 +28,7 @@ class ArchiveLimits(ContractModel):
max_structure_bytes: int = Field(default=STRUCTURE_BYTES, gt=0, le=STRUCTURE_BYTES)
max_schema_bytes: int = Field(default=16 * MIB, gt=0, le=16 * MIB)
max_samples_bytes: int = Field(default=16 * MIB, gt=0, le=16 * MIB)
+ max_lock_bytes: int = Field(default=LOCK_BYTES, gt=0, le=LOCK_BYTES)
def member_bytes(self, member: MemberName) -> int:
cap = {
@@ -34,5 +36,6 @@ def member_bytes(self, member: MemberName) -> int:
MemberName.STRUCTURE: self.max_structure_bytes,
MemberName.SCHEMA: self.max_schema_bytes,
MemberName.SAMPLES: self.max_samples_bytes,
+ MemberName.LOCK: self.max_lock_bytes,
}.get(member, self.max_member_bytes)
return min(cap, self.max_member_bytes)
diff --git a/src/mlbundle/lock.py b/src/mlbundle/lock.py
new file mode 100644
index 0000000..8fad1aa
--- /dev/null
+++ b/src/mlbundle/lock.py
@@ -0,0 +1,194 @@
+"""The bundle's PEP 751 runtime lock: a closed canonical subset mlbundle never installs."""
+
+from __future__ import annotations
+
+import hashlib
+import re
+from typing import Annotated
+
+from pydantic import Field, StringConstraints, ValidationError, model_validator
+
+from . import _lock_toml
+from ._base import ContractModel
+from ._wheel_tags import GLIBC, PLATFORMS, Platform, select, wheel_identity
+from .canonical import canonical_dumps
+from .contract import Library
+from .errors import InvalidEnvironmentLockError
+from .manifest import Manifest
+
+MAX_PACKAGES = 512
+# Normalized names and public versions: no local versions, which no index serves.
+NAME_PATTERN = r"[a-z0-9]+(?:-[a-z0-9]+)*"
+VERSION_PATTERN = (
+ r"[0-9]+(?:\.[0-9]+)*(?:(?:a|b|rc)[0-9]+)?(?:\.post[0-9]+)?(?:\.dev[0-9]+)?"
+)
+PackageName = Annotated[
+ str, StringConstraints(max_length=128, pattern=f"^{NAME_PATTERN}$")
+]
+PackageVersion = Annotated[
+ str, StringConstraints(max_length=64, pattern=f"^{VERSION_PATTERN}$")
+]
+_PYTHON = re.compile(r"3\.([0-9]{1,3})\.[0-9]{1,3}(?:(?:a|b|rc)[0-9]{1,3})?")
+# Quotes, backslashes, spaces and controls never occur, so TOML needs no escapes.
+_URL = re.compile(r"https://[A-Za-z0-9._~:/?#@!$&'()*+,;=%-]{1,2040}")
+
+# Distributions a loaded model needs besides mlbundle itself, as in the extras.
+# Each group needs exactly one member; xgboost-cpu is XGBoost without NCCL.
+_BASE = (("pydantic",),)
+_LIBRARY = {
+ Library.SKLEARN: (("scikit-learn",), ("skops",)),
+ Library.XGBOOST: (("xgboost", "xgboost-cpu"), ("scikit-learn",)),
+ Library.CATBOOST: (("catboost",),),
+ Library.ONNX: (("onnx",), ("onnxruntime",)),
+}
+
+
+class LockedWheel(ContractModel):
+ """One wheel file: name, download URL, size and SHA-256 digest."""
+
+ name: Annotated[str, StringConstraints(max_length=256)]
+ url: Annotated[str, StringConstraints(max_length=2048)]
+ size: int = Field(gt=0, le=2**40)
+ sha256: Annotated[str, StringConstraints(pattern=r"^[0-9a-f]{64}$")]
+
+ @model_validator(mode="after")
+ def addressed_file(self) -> LockedWheel:
+ if wheel_identity(self.name) is None:
+ raise ValueError("Invalid wheel filename.")
+ if _URL.fullmatch(self.url) is None or not self.url.endswith("/" + self.name):
+ raise ValueError("Wheel URLs are HTTPS and end with the wheel filename.")
+ return self
+
+
+class LockedPackage(ContractModel):
+ """A pinned distribution, the targets that install it and their wheels."""
+
+ name: PackageName
+ version: PackageVersion
+ platforms: tuple[Platform, ...] = Field(min_length=1, max_length=len(PLATFORMS))
+ wheels: tuple[LockedWheel, ...] = Field(min_length=1, max_length=len(PLATFORMS))
+
+ @model_validator(mode="after")
+ def consistent_files(self) -> LockedPackage:
+ if list(self.platforms) != [p for p in PLATFORMS if p in self.platforms]:
+ raise ValueError("Package platforms must be unique and ordered.")
+ names = [wheel.name for wheel in self.wheels]
+ if names != sorted(set(names)):
+ raise ValueError("Wheels must be unique and sorted by name.")
+ if any(wheel_identity(name) != (self.name, self.version) for name in names):
+ raise ValueError("Wheel filenames must match the package and version.")
+ return self
+
+
+class EnvironmentLock(ContractModel):
+ """Validated lock contents; an unauthenticated claim, never instructions here."""
+
+ python_version: Annotated[str, StringConstraints(max_length=32)]
+ packages: tuple[LockedPackage, ...] = Field(min_length=1, max_length=MAX_PACKAGES)
+
+ @model_validator(mode="after")
+ def installable(self) -> EnvironmentLock:
+ version = _PYTHON.fullmatch(self.python_version)
+ if version is None:
+ raise ValueError("Invalid CPython version.")
+ names = [package.name for package in self.packages]
+ if names != sorted(set(names)):
+ raise ValueError("Packages must be unique and sorted by name.")
+ if "mlbundle" in names:
+ raise ValueError("The writer_version pins mlbundle; the lock omits it.")
+ minor = int(version[1])
+ for package in self.packages:
+ names = [wheel.name for wheel in package.wheels]
+ chosen = {select(names, platform, minor) for platform in package.platforms}
+ # Each target installs one unambiguous file; no file is unused.
+ if None in chosen or chosen != set(names):
+ raise ValueError("Each target needs one preferred wheel, all used.")
+ return self
+
+ @property
+ def platforms(self) -> tuple[Platform, ...]:
+ """Linux x86_64/aarch64 with glibc >= 2.28 and Windows x64, with the GIL."""
+ return PLATFORMS
+
+ @property
+ def glibc(self) -> tuple[int, int]:
+ return GLIBC
+
+ @property
+ def environment_id(self) -> str:
+ """SHA-256 identity of Python and every file, independent of download URLs."""
+ record = {
+ "python": self.python_version,
+ "packages": [
+ [
+ p.name,
+ p.version,
+ list(p.platforms),
+ [[w.name, w.sha256] for w in p.wheels],
+ ]
+ for p in self.packages
+ ],
+ }
+ return hashlib.sha256(canonical_dumps(record)).hexdigest()
+
+ def version(self, name: str) -> str | None:
+ for package in self.packages:
+ if package.name == name:
+ return package.version
+ return None
+
+ def to_bytes(self) -> bytes:
+ return _lock_toml.dump(self.python_version, self.packages)
+
+ @classmethod
+ def from_bytes(cls, data: bytes) -> EnvironmentLock:
+ """Parse the canonical TOML subset; other spellings are rejected."""
+ python_version, packages = _lock_toml.parse(data)
+ try:
+ lock = cls(
+ python_version=python_version,
+ packages=tuple(
+ LockedPackage(
+ name=package["name"],
+ version=package["version"],
+ platforms=package["platforms"],
+ wheels=tuple(LockedWheel(**w) for w in package["wheels"]),
+ )
+ for package in packages
+ ),
+ )
+ except (ValidationError, TypeError):
+ raise InvalidEnvironmentLockError("Invalid environment lock.") from None
+ if lock.to_bytes() != data:
+ raise InvalidEnvironmentLockError("Environment lock is not canonical.")
+ return lock
+
+
+def runtime_requirements(
+ library: Library, leaf: Library | None = None
+) -> tuple[tuple[str, ...], ...]:
+ """Distribution groups a loaded model needs: pydantic and the adapters' libraries."""
+ groups = [*_BASE, *_LIBRARY[library]]
+ if leaf is not None:
+ groups.extend(group for group in _LIBRARY[leaf] if group not in groups)
+ return tuple(groups)
+
+
+def check_bundle_lock(lock: EnvironmentLock, manifest: Manifest) -> None:
+ """Bind the lock to the manifest's Python and to the model's libraries."""
+ environment = manifest.environment
+ if environment.python_implementation != "CPython":
+ raise InvalidEnvironmentLockError("Environment locks require CPython.")
+ if lock.python_version != environment.python_version:
+ raise InvalidEnvironmentLockError(
+ "The lock's Python differs from the training Python."
+ )
+ pipeline = manifest.model.pipeline
+ leaf = None if pipeline is None else pipeline.estimator.library
+ names = {package.name: package for package in lock.packages}
+ for group in runtime_requirements(manifest.model.library, leaf):
+ present = [names[name] for name in group if name in names]
+ if len(present) != 1 or present[0].platforms != PLATFORMS:
+ raise InvalidEnvironmentLockError(
+ f"The lock needs exactly one of {', '.join(group)} on every target."
+ )
diff --git a/src/mlbundle/manifest.py b/src/mlbundle/manifest.py
index 84b0f3f..1734373 100644
--- a/src/mlbundle/manifest.py
+++ b/src/mlbundle/manifest.py
@@ -105,6 +105,7 @@ class TargetInfo(ContractModel):
class MemberReferences(ContractModel):
schema_: Literal["schema.json"] = Field(alias="schema")
+ lock: Literal["pylock.toml"]
structure: Literal["structure.json"] | None = None
samples: Literal["samples.json"] | None = None
@@ -119,7 +120,7 @@ class Manifest(ContractModel):
features: FeatureInfo
target: TargetInfo
environment: TrainingEnvironment
- integrity: dict[MemberName, IntegrityRecord] = Field(min_length=1, max_length=5)
+ integrity: dict[MemberName, IntegrityRecord] = Field(min_length=1, max_length=6)
references: MemberReferences
user_metadata: dict[str, JsonValue] = Field(default_factory=dict, max_length=1024)
@@ -183,8 +184,6 @@ def consistent_manifest(self) -> Manifest:
raise ValueError("A member exceeds its format size cap.")
if (self.model.library == Library.ONNX) != (self.environment.onnx is not None):
raise ValueError("ONNX graph metadata is required only for ONNX models.")
- if self.environment.packages.get("mlbundle") != self.writer_version:
- raise ValueError("Writer and environment mlbundle versions must agree.")
return self
def verified_claims(self) -> ModelClaims:
diff --git a/src/mlbundle/model_io.py b/src/mlbundle/model_io.py
index 757eaf5..4bbf640 100644
--- a/src/mlbundle/model_io.py
+++ b/src/mlbundle/model_io.py
@@ -3,10 +3,12 @@
from collections.abc import Mapping, Sequence
from contextlib import nullcontext
from os import PathLike
+from pathlib import Path
from typing import cast
from pydantic import JsonValue
+from . import _lock_generation
from ._container_rules import MEMBER_ORDER, BundleSource, effective_limits
from ._export_manifest import manifest_parts
from ._load_diagnostics import sklearn_environment
@@ -20,9 +22,10 @@
export_target_names,
resolve_labels,
)
-from .errors import ClaimMismatchError
+from .errors import ClaimMismatchError, LimitExceededError
from .inspection import metadata_view
from .limits import ArchiveLimits
+from .lock import EnvironmentLock, runtime_requirements
from .registry import find_adapter, get_adapter, is_composite
from .results import LoadedBundle, MetadataView
from .schema import read_declarations, validate_separator
@@ -41,6 +44,7 @@ def export(
sample_rows: int | None = None,
onehot_separator: str = "__",
metadata: Mapping[str, JsonValue] | None = None,
+ environment_lock: bytes | str | PathLike[str] | None = None,
overwrite: bool = False,
limits: ArchiveLimits | None = None,
) -> MetadataView:
@@ -63,6 +67,12 @@ def export(
user data. N must be a positive integer within the frame; target values and
the index are excluded. Missing values become null, timestamps ISO strings,
categorical/NumPy scalars JSON scalars and infinities canonical float tags.
+ Export locks the model's runtime as pylock.toml for Linux and Windows: the
+ installed versions of pydantic, the model libraries and their dependencies,
+ resolved by uv for CPython with the GIL. That requires mlbundle[lock] and
+ index access. environment_lock instead supplies canonical lock bytes or a
+ path, such as another bundle's EnvironmentLock.to_bytes(). Either way every
+ locked distribution installed here must have the installed version.
"""
selected = effective_limits(limits)
separator = validate_separator(onehot_separator)
@@ -87,6 +97,14 @@ def export(
)
members = prepared.members
structure = prepared.structure
+ leaf = None if composite is None else composite.leaf.library
+ lock = (
+ _lock_generation.generate_lock(runtime_requirements(prepared.library, leaf))
+ if environment_lock is None
+ else _read_lock(environment_lock, selected.member_bytes(MemberName.LOCK))
+ )
+ _lock_generation.check_fidelity(lock)
+ members[MemberName.LOCK] = lock.to_bytes()
members[MemberName.SCHEMA] = training.schema
if training.samples is not None:
members[MemberName.SAMPLES] = training.samples
@@ -110,12 +128,26 @@ def export(
return metadata_view(validated, selected)
+def _read_lock(source: bytes | str | PathLike[str], cap: int) -> EnvironmentLock:
+ if isinstance(source, bytes):
+ data = source
+ else:
+ path = Path(source)
+ if path.stat().st_size > cap:
+ raise LimitExceededError("Member size limit exceeded: pylock.toml.")
+ data = path.read_bytes()
+ if len(data) > cap:
+ raise LimitExceededError("Member size limit exceeded: pylock.toml.")
+ return EnvironmentLock.from_bytes(data)
+
+
def load(source: BundleSource, *, limits: ArchiveLimits | None = None) -> LoadedBundle:
"""Verify format, integrity and recomputed native claims before returning a model."""
selected = effective_limits(limits)
container = read_validated_container(source, limits=selected)
manifest, members = container.manifest, container.members
schema, samples = read_declarations(manifest, container.json, selected)
+ declared_sklearn = container.lock.version("scikit-learn")
if manifest.model.pipeline is not None:
get_adapter(Library.SKLEARN)
from ._composite.io import load_components
@@ -125,13 +157,13 @@ def load(source: BundleSource, *, limits: ArchiveLimits | None = None) -> Loaded
members,
manifest.features.names,
cast(bool, manifest.model.hyperparameters["verbose"]),
- manifest.environment.packages.get("scikit-learn"),
+ declared_sklearn,
)
verify_claims(manifest.verified_claims(), actual)
else:
adapter = get_adapter(manifest.model.library)
with (
- sklearn_environment(manifest.environment.packages.get("scikit-learn"))
+ sklearn_environment(declared_sklearn)
if adapter.model_member == MemberName.SKOPS
else nullcontext()
):
@@ -162,6 +194,7 @@ def load(source: BundleSource, *, limits: ArchiveLimits | None = None) -> Loaded
return LoadedBundle(
manifest=manifest,
members=tuple(name for name in MEMBER_ORDER if name in members),
+ environment_lock=container.lock,
native_model=model,
predictor=predictor,
schema=schema,
diff --git a/src/mlbundle/results.py b/src/mlbundle/results.py
index d03d57a..fcbd0b8 100644
--- a/src/mlbundle/results.py
+++ b/src/mlbundle/results.py
@@ -7,6 +7,7 @@
from .adapters import Predictor, ProbabilityOutput, RegressionOutput
from .claims import ClassLabels
from .contract import FeatureOrigin, Library, MemberName, ModelKind
+from .lock import EnvironmentLock
from .manifest import Manifest
from .records import OutputPrediction, predict_record, row_from_record
@@ -17,6 +18,7 @@ class MetadataView:
manifest: Manifest
members: tuple[MemberName, ...]
+ environment_lock: EnvironmentLock
schema: dict[str, JsonValue] | None = None
samples: list[dict[str, JsonValue]] | None = None
@@ -27,6 +29,7 @@ class LoadedBundle:
manifest: Manifest
members: tuple[MemberName, ...]
+ environment_lock: EnvironmentLock
native_model: object = field(repr=False)
predictor: Predictor = field(repr=False)
schema: dict[str, JsonValue] | None = None
diff --git a/tests/conftest.py b/tests/conftest.py
index 8d79221..bd6cdbe 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -8,7 +8,8 @@
import pytest
-from mlbundle import MemberName, __version__
+from lock_helpers import sklearn_lock_bytes, synthetic_lock
+from mlbundle import MemberName, __version__, _lock_generation
from mlbundle.canonical import canonical_dumps
from mlbundle.integrity import hash_member
@@ -50,6 +51,16 @@ def align_schema(parts, members):
members[MemberName.SCHEMA] = canonical_dumps(schema_for_manifest(parts))
+@pytest.fixture(autouse=True)
+def offline_lock(monkeypatch):
+ """Exports resolve their installed pins offline; uv has its own tests."""
+
+ def resolve(python_version, pins, constraints):
+ return synthetic_lock(python_version, dict(pins))
+
+ monkeypatch.setattr(_lock_generation, "resolve_lock", resolve)
+
+
@pytest.fixture
def manifest_data() -> dict:
value = {
@@ -79,14 +90,22 @@ def manifest_data() -> dict:
"environment": {
"python_version": "3.14.0",
"python_implementation": "CPython",
+ "free_threaded": False,
"os": "Windows",
"os_version": "11",
"architecture": "AMD64",
- "packages": {"mlbundle": __version__, "scikit-learn": "1.9.1"},
"onnx": None,
},
- "integrity": {"model.skops": hash_member(b"native model bytes").model_dump()},
- "references": {"schema": "schema.json", "structure": None, "samples": None},
+ "integrity": {
+ "model.skops": hash_member(b"native model bytes").model_dump(),
+ "pylock.toml": hash_member(sklearn_lock_bytes()).model_dump(),
+ },
+ "references": {
+ "schema": "schema.json",
+ "lock": "pylock.toml",
+ "structure": None,
+ "samples": None,
+ },
"user_metadata": {"name": "example", "metrics": {"accuracy": 0.95}},
}
value["integrity"]["schema.json"] = hash_member(
@@ -115,6 +134,7 @@ def parts(manifest_data):
("manifest.json", canonical_dumps(manifest_data)),
("model.skops", b"native model bytes"),
("schema.json", canonical_dumps(schema_for_manifest(manifest_data))),
+ ("pylock.toml", sklearn_lock_bytes()),
]
diff --git a/tests/lock_helpers.py b/tests/lock_helpers.py
new file mode 100644
index 0000000..73f806d
--- /dev/null
+++ b/tests/lock_helpers.py
@@ -0,0 +1,50 @@
+"""Synthetic canonical locks: valid structure with placeholder files, for offline tests."""
+
+import hashlib
+
+from mlbundle import EnvironmentLock, LockedPackage, LockedWheel
+from mlbundle._wheel_tags import PLATFORMS
+
+
+def pure_wheel(name: str, version: str) -> LockedWheel:
+ filename = f"{name.replace('-', '_')}-{version}-py3-none-any.whl"
+ return LockedWheel(
+ name=filename,
+ url=f"https://files.example.org/packages/{filename}",
+ size=1024,
+ sha256=hashlib.sha256(filename.encode()).hexdigest(),
+ )
+
+
+def synthetic_lock(python_version: str, packages: dict[str, str]) -> EnvironmentLock:
+ return EnvironmentLock(
+ python_version=python_version,
+ packages=tuple(
+ LockedPackage(
+ name=name,
+ version=version,
+ platforms=PLATFORMS,
+ wheels=(pure_wheel(name, version),),
+ )
+ for name, version in sorted(packages.items())
+ ),
+ )
+
+
+SKLEARN_PACKAGES = {"pydantic": "2.14.1", "scikit-learn": "1.9.1", "skops": "0.16.0"}
+
+
+def sklearn_lock_bytes(python_version: str = "3.14.0") -> bytes:
+ return synthetic_lock(python_version, SKLEARN_PACKAGES).to_bytes()
+
+
+LIBRARY_PACKAGES = {
+ "sklearn": SKLEARN_PACKAGES,
+ "xgboost": {"pydantic": "2.14.1", "scikit-learn": "1.9.1", "xgboost": "3.4.1"},
+ "catboost": {"pydantic": "2.14.1", "catboost": "1.2.10"},
+ "onnx": {"pydantic": "2.14.1", "onnx": "1.23.0", "onnxruntime": "1.30.0"},
+}
+
+
+def library_lock_bytes(library: str, python_version: str = "3.14.0") -> bytes:
+ return synthetic_lock(python_version, LIBRARY_PACKAGES[library]).to_bytes()
diff --git a/tests/test_catboost.py b/tests/test_catboost.py
index 030bc68..baea540 100644
--- a/tests/test_catboost.py
+++ b/tests/test_catboost.py
@@ -30,7 +30,7 @@ def test_classifier_roundtrip(labels, tmp_path):
assert model._serialize_model() == before
assert loaded.library == "catboost"
assert view.manifest.model.serialization == "cbm"
- assert view.manifest.environment.packages["catboost"] == cb.__version__
+ assert view.environment_lock.version("catboost") == cb.__version__
assert loaded.class_labels == [labels]
assert list(loaded.feature_names) == list("abc")
assert loaded.feature_origin == "model"
@@ -129,6 +129,7 @@ def test_schema_samples_and_lowered_limits(tmp_path):
mlbundle.MemberName.STRUCTURE,
mlbundle.MemberName.SCHEMA,
mlbundle.MemberName.SAMPLES,
+ mlbundle.MemberName.LOCK,
}
for limits in [
mlbundle.ArchiveLimits(max_member_bytes=1),
diff --git a/tests/test_cli.py b/tests/test_cli.py
index f0fa012..993ebed 100644
--- a/tests/test_cli.py
+++ b/tests/test_cli.py
@@ -53,7 +53,9 @@ def test_inspect_and_verify(bundle_path, capsys):
"Features (generated):",
"Class labels (output-major):",
"Training:",
- "Packages:",
+ "Environment lock: CPython",
+ "Environment id: ",
+ "Locked packages: ",
"schema=yes",
"samples=no",
):
diff --git a/tests/test_container.py b/tests/test_container.py
index 08dc853..4d4cf69 100644
--- a/tests/test_container.py
+++ b/tests/test_container.py
@@ -219,7 +219,7 @@ def test_optional_caps_count_and_json(parts, manifest_data, name):
def test_honest_and_lying_bombs(parts):
bundle = build_zip(
- [parts[0], ("model.skops", b"0" * 4096), parts[2]], compression=8
+ [parts[0], ("model.skops", b"0" * 4096), *parts[2:]], compression=8
)
with pytest.raises(LimitExceededError):
read_container(bundle, limits=ArchiveLimits(max_compression_ratio=10))
@@ -247,7 +247,7 @@ def test_descriptor_length_checked_before_copy(parts):
with pytest.raises(InvalidContainerError):
read_container(
oversized_descriptor(parts),
- limits=ArchiveLimits(max_member_bytes=2048, max_total_bytes=2048),
+ limits=ArchiveLimits(max_member_bytes=2048, max_total_bytes=3072),
)
diff --git a/tests/test_environment.py b/tests/test_environment.py
index 6705a04..1f4c652 100644
--- a/tests/test_environment.py
+++ b/tests/test_environment.py
@@ -1,6 +1,6 @@
-"""Environment declarations use installed distribution metadata."""
+"""Training environment declarations; package versions live in the lock."""
-from importlib import metadata
+import sysconfig
import pytest
from pydantic import ValidationError
@@ -10,20 +10,17 @@
def test_installed_environment():
environment = module.capture_environment()
- assert environment.packages["mlbundle"] == metadata.version("mlbundle")
+ assert environment.free_threaded is bool(
+ sysconfig.get_config_var("Py_GIL_DISABLED")
+ )
assert environment.python_version.startswith("3.14")
assert environment.python_implementation
assert environment.os and environment.os_version and environment.architecture
assert environment.onnx is None
-def test_missing_distributions_and_onnx(monkeypatch):
- def version(name):
- if name == "mlbundle":
- return "0.1.0a3"
- raise metadata.PackageNotFoundError(name)
-
- monkeypatch.setattr(module.metadata, "version", version)
+def test_free_threaded_build_and_onnx(monkeypatch):
+ monkeypatch.setattr(module.sysconfig, "get_config_var", lambda name: 1)
graph = OnnxInfo(
opsets=[Opset(domain="", version=21)],
ir_version=10,
@@ -31,7 +28,7 @@ def version(name):
producer_version="",
)
environment = module.capture_environment(onnx=graph)
- assert environment.packages == {"mlbundle": "0.1.0a3"}
+ assert environment.free_threaded is True
assert environment.onnx == graph
diff --git a/tests/test_environment_check.py b/tests/test_environment_check.py
new file mode 100644
index 0000000..4742ea6
--- /dev/null
+++ b/tests/test_environment_check.py
@@ -0,0 +1,134 @@
+"""Runtime checks: exactly the lock plus mlbundle, on a GIL CPython target."""
+
+import pytest
+
+import mlbundle
+from lock_helpers import sklearn_lock_bytes
+from mlbundle import (
+ EnvironmentLock,
+ EnvironmentMismatchError,
+ LockedPackage,
+ Manifest,
+ MemberName,
+ MetadataView,
+ _environment_check,
+)
+from mlbundle._environment_check import RuntimeFacts, environment_problems
+from mlbundle.canonical import canonical_dumps
+from mlbundle.lock import LockedWheel
+
+
+def bundle(manifest_data, *extra):
+ lock = EnvironmentLock.from_bytes(sklearn_lock_bytes("3.14.7"))
+ lock = lock.model_copy(update={"packages": (*lock.packages, *extra)})
+ manifest_data["environment"]["python_version"] = "3.14.7"
+ return MetadataView(
+ Manifest.from_bytes(canonical_dumps(manifest_data)), (MemberName.LOCK,), lock
+ )
+
+
+def facts(view, **changes):
+ distributions = {p.name: p.version for p in view.environment_lock.packages}
+ distributions["mlbundle"] = view.manifest.writer_version
+ values = {
+ "implementation": "cpython",
+ "python_version": "3.14.7",
+ "gil_disabled": False,
+ "platform": "linux-x86_64",
+ "glibc": (2, 36),
+ "distributions": distributions,
+ }
+ return RuntimeFacts(**(values | changes))
+
+
+NCCL = LockedPackage(
+ name="nvidia-nccl-cu13",
+ version="2.32.3",
+ platforms=("linux-x86_64",),
+ wheels=(
+ LockedWheel(
+ name="nvidia_nccl_cu13-2.32.3-py3-none-manylinux_2_27_x86_64.whl",
+ url="https://files.example.org/"
+ "nvidia_nccl_cu13-2.32.3-py3-none-manylinux_2_27_x86_64.whl",
+ size=1,
+ sha256="0" * 64,
+ ),
+ ),
+)
+
+
+def test_exact_environment_passes_per_target(manifest_data):
+ view = bundle(manifest_data, NCCL)
+ assert environment_problems(view, facts(view)) == []
+ for platform, glibc in [("linux-aarch64", (2, 28)), ("win-amd64", None)]:
+ other = facts(view, platform=platform, glibc=glibc)
+ other.distributions.pop("nvidia-nccl-cu13") # Locked only for x86_64.
+ assert environment_problems(view, other) == []
+
+
+@pytest.mark.parametrize(
+ "changes,problem",
+ [
+ ({"implementation": "pypy"}, "not CPython with the GIL"),
+ ({"gil_disabled": True}, "not CPython with the GIL"),
+ ({"python_version": "3.14.8"}, 'Python "3.14.8" is not 3.14.7'),
+ ({"platform": "win-arm64"}, 'platform "win-arm64" is not a target'),
+ ({"platform": "macosx-14.0-arm64"}, "is not a target"),
+ ({"platform": "linux-riscv64"}, "is not a target"),
+ ({"glibc": None}, "glibc 2.28 or newer"),
+ ({"glibc": (2, 27)}, "glibc 2.28 or newer"),
+ ],
+)
+def test_interpreter_and_platform_mismatches(manifest_data, changes, problem):
+ view = bundle(manifest_data)
+ assert any(
+ problem in item for item in environment_problems(view, facts(view, **changes))
+ )
+
+
+def test_distribution_mismatches(manifest_data):
+ view = bundle(manifest_data)
+ current = facts(view)
+ current.distributions.update(
+ {"skops": "0.15.0", "pip": "26.0", "scikit-learn": None}
+ )
+ del current.distributions["pydantic"]
+ current.distributions["mlbundle"] = "0.2.1"
+ problems = environment_problems(view, current)
+ assert problems == [
+ f'mlbundle "0.2.1" is installed, {view.manifest.writer_version} is locked',
+ '"pip" is installed but not locked',
+ "pydantic 2.14.1 is not installed",
+ "scikit-learn is duplicated or installed from a source tree",
+ 'skops "0.15.0" is installed, 0.16.0 is locked',
+ ]
+
+
+def test_check_environment_reports_bounded_problems(manifest_data, monkeypatch):
+ view = bundle(manifest_data)
+ many = facts(view)
+ many.distributions.update({f"extra-{index}": "1.0" for index in range(20)})
+ monkeypatch.setattr(RuntimeFacts, "current", classmethod(lambda cls: many))
+ with pytest.raises(EnvironmentMismatchError) as error:
+ mlbundle.check_environment(view)
+ assert str(error.value).endswith("; ...")
+ assert str(error.value).count("is installed but not locked") == 10
+ monkeypatch.setattr(RuntimeFacts, "current", classmethod(lambda cls: facts(view)))
+ mlbundle.check_environment(view)
+
+
+def test_current_facts_read_this_interpreter(monkeypatch):
+ current = RuntimeFacts.current()
+ assert current.implementation == "cpython"
+ # None for an editable checkout, the version for the installed wheel in CI.
+ assert current.distributions["mlbundle"] in (None, mlbundle.__version__)
+ monkeypatch.setattr(
+ _environment_check.os, "confstr", lambda _: "glibc 2.39", raising=False
+ )
+ assert RuntimeFacts.current().glibc == (2, 39)
+
+ def unsupported(_):
+ raise ValueError
+
+ monkeypatch.setattr(_environment_check.os, "confstr", unsupported, raising=False)
+ assert RuntimeFacts.current().glibc is None
diff --git a/tests/test_environment_lock.py b/tests/test_environment_lock.py
new file mode 100644
index 0000000..614e863
--- /dev/null
+++ b/tests/test_environment_lock.py
@@ -0,0 +1,250 @@
+"""The pylock.toml contract: canonical round trips, bundle binding and rejections."""
+
+import hashlib
+import tomllib
+
+import pytest
+from pydantic import ValidationError
+
+from lock_helpers import sklearn_lock_bytes, synthetic_lock
+from mlbundle import (
+ EnvironmentLock,
+ InvalidEnvironmentLockError,
+ LockedPackage,
+ LockedWheel,
+)
+
+URL = "https://files.pythonhosted.org/packages/ab/cd/"
+PLATFORMS = ("linux-x86_64", "linux-aarch64", "win-amd64")
+LINUX = ("linux-x86_64", "linux-aarch64")
+
+
+def wheel(filename):
+ return LockedWheel(
+ name=filename,
+ url=URL + filename,
+ size=10,
+ sha256=hashlib.sha256(filename.encode()).hexdigest(),
+ )
+
+
+def numpy_package(*filenames, platforms=PLATFORMS):
+ return LockedPackage(
+ name="numpy",
+ version="2.5.4",
+ platforms=platforms,
+ wheels=tuple(wheel(name) for name in sorted(filenames)),
+ )
+
+
+X86 = "numpy-2.5.4-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl"
+ARM = "numpy-2.5.4-cp314-cp314-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl"
+WIN = "numpy-2.5.4-cp314-cp314-win_amd64.whl"
+
+
+def test_canonical_round_trip_identity_and_consumers():
+ lock = synthetic_lock("3.14.7", {"pydantic": "2.14.1", "scikit-learn": "1.9.1"})
+ lock = lock.model_copy(
+ update={
+ "packages": (
+ *lock.packages,
+ LockedPackage(
+ name="zeta-nccl",
+ version="2.0",
+ platforms=LINUX,
+ wheels=(
+ wheel("zeta_nccl-2.0-py3-none-manylinux_2_27_aarch64.whl"),
+ wheel("zeta_nccl-2.0-py3-none-manylinux_2_27_x86_64.whl"),
+ ),
+ ),
+ LockedPackage(
+ name="zeta-win",
+ version="1.0",
+ platforms=("win-amd64",),
+ wheels=(wheel("zeta_win-1.0-py3-none-any.whl"),),
+ ),
+ )
+ }
+ )
+ data = lock.to_bytes()
+ assert EnvironmentLock.from_bytes(data) == lock
+ # Any TOML parser reads PEP 751 fields from the canonical spelling.
+ document = tomllib.loads(data.decode())
+ assert document["lock-version"] == "1.0"
+ assert document["requires-python"] == "==3.14.7"
+ assert document["environments"][-1] == (
+ "sys_platform == 'win32' and platform_machine == 'AMD64'"
+ )
+ assert document["packages"][-2]["marker"] == (
+ "(sys_platform == 'linux' and platform_machine == 'x86_64') or "
+ "(sys_platform == 'linux' and platform_machine == 'aarch64')"
+ )
+ assert document["packages"][-1]["marker"] == document["environments"][-1]
+ assert lock.version("scikit-learn") == "1.9.1" and lock.version("x") is None
+ assert lock.platforms == PLATFORMS and lock.glibc == (2, 28)
+ moved = lock.model_copy(
+ update={
+ "packages": tuple(
+ p.model_copy(
+ update={
+ "wheels": tuple(
+ w.model_copy(
+ update={"url": "https://mirror.example/" + w.name}
+ )
+ for w in p.wheels
+ )
+ }
+ )
+ for p in lock.packages
+ )
+ }
+ )
+ assert moved.environment_id == lock.environment_id # URLs are not identity.
+ changed = synthetic_lock("3.14.8", {"pydantic": "2.14.1", "scikit-learn": "1.9.1"})
+ assert (
+ changed.environment_id
+ != synthetic_lock(
+ "3.14.7", {"pydantic": "2.14.1", "scikit-learn": "1.9.1"}
+ ).environment_id
+ )
+
+
+def test_preferred_wheel_per_target():
+ abi3 = "wcwidth-0.9.2-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl"
+ windows = "wcwidth-0.9.2-cp310-abi3-win_amd64.whl"
+ pure = "wcwidth-0.9.2-py3-none-any.whl"
+ package = LockedPackage(
+ name="wcwidth",
+ version="0.9.2",
+ platforms=PLATFORMS,
+ wheels=(wheel(abi3), wheel(windows), wheel(pure)),
+ )
+ # Each target prefers its platform wheel; aarch64 uses the pure one.
+ EnvironmentLock(python_version="3.14.7", packages=(package,))
+ lock = EnvironmentLock(
+ python_version="3.14.7", packages=(numpy_package(X86, ARM, WIN),)
+ )
+ assert len(lock.packages[0].wheels) == 3
+
+
+@pytest.mark.parametrize(
+ "files,platforms",
+ [
+ ((X86, ARM), PLATFORMS), # Windows has no wheel.
+ ((X86, ARM, WIN.replace("win_amd64", "win_arm64")), PLATFORMS),
+ ((X86, WIN), PLATFORMS), # aarch64 has no wheel.
+ ((X86.replace("cp314-cp314", "cp314-cp314t"), ARM, WIN), PLATFORMS),
+ ((WIN.replace("cp314-cp314", "cp314-cp314t"), X86, ARM), PLATFORMS),
+ (("numpy-2.5.4-cp314-cp314-manylinux_2_31_x86_64.whl", ARM, WIN), PLATFORMS),
+ ((X86, "numpy-2.5.4-cp314-cp314-musllinux_1_2_x86_64.whl"), ("linux-x86_64",)),
+ ((X86, ARM), ("linux-x86_64",)), # An unused wheel.
+ ((X86.replace("cp314", "cp313"), ARM, WIN), PLATFORMS),
+ ((WIN,), ("x86_64",)),
+ (
+ (X86, X86.replace("_x86_64.many", "_x86_64.linux_x86_64.many")),
+ ("linux-x86_64",),
+ ),
+ ((X86, ARM), ("linux-aarch64", "linux-x86_64")),
+ ],
+)
+def test_unresolvable_targets(files, platforms):
+ with pytest.raises(ValidationError):
+ EnvironmentLock(
+ python_version="3.14.7",
+ packages=(numpy_package(*files, platforms=platforms),),
+ )
+
+
+@pytest.mark.parametrize(
+ "change",
+ [
+ {"name": "Numpy"},
+ {"name": "numpy_core"},
+ {"version": "2.5.4+local"},
+ {"version": "v2.5.4"},
+ {"platforms": ()},
+ ],
+)
+def test_invalid_package_records(change):
+ fields = {
+ "name": "numpy",
+ "version": "2.5.4",
+ "platforms": PLATFORMS,
+ "wheels": (wheel(X86), wheel(ARM), wheel(WIN)),
+ } | change
+ with pytest.raises(ValidationError):
+ LockedPackage(**fields)
+
+
+@pytest.mark.parametrize(
+ "fields",
+ [
+ {"url": "http://files.example/" + ARM},
+ {"url": URL + "other.whl"},
+ {"url": URL + 'a"b/' + ARM},
+ {"name": "numpy-2.5.4.tar.gz", "url": URL + "numpy-2.5.4.tar.gz"},
+ {"sha256": "A" * 64},
+ {"size": 0},
+ ],
+)
+def test_invalid_wheel_records(fields):
+ with pytest.raises(ValidationError):
+ LockedWheel(
+ **({"name": ARM, "url": URL + ARM, "size": 1, "sha256": "a" * 64} | fields)
+ )
+
+
+@pytest.mark.parametrize(
+ "packages,python",
+ [
+ ({"mlbundle": "0.3.0"}, "3.14.7"), # writer_version pins mlbundle.
+ ({"pydantic": "2.14.1"}, "3.14"),
+ ({"pydantic": "2.14.1"}, "2.7.18"),
+ ],
+)
+def test_invalid_locks(packages, python):
+ with pytest.raises(ValidationError):
+ synthetic_lock(python, packages)
+
+
+def test_empty_lock():
+ with pytest.raises(ValidationError):
+ EnvironmentLock(python_version="3.14.7", packages=())
+
+
+def mutate(old, new):
+ return sklearn_lock_bytes().replace(old, new, 1)
+
+
+@pytest.mark.parametrize(
+ "data",
+ [
+ mutate(b'created-by = "mlbundle"', b'created-by = "uv"'),
+ mutate(b'lock-version = "1.0"', b'lock-version = "1.1"'),
+ mutate(b'"==3.14.0"', b'">=3.14.0"'),
+ mutate(b"[[packages]]", b"[tool.uv]\n\n[[packages]]"),
+ mutate(b"[[packages]]\n", b'[[packages]]\nindex = "https://pypi.org/simple"\n'),
+ mutate(b"size = 1024", b"size = true"),
+ mutate(b"size = 1024", b'size = "1024"'),
+ mutate(b"hashes = { sha256", b'hashes = { md5 = "x", sha256'),
+ mutate(b"wheels = [", b"marker = \"os_name == 'nt'\"\nwheels = ["),
+ mutate(b"wheels = [", b"marker = \"sys_platform == 'win32'\"\nwheels = ["),
+ mutate(b'name = "pydantic"', b'name = "pydantic"\nsdist = { url = "x" }'),
+ mutate(b'name = "skops"', b'name = "aaa"'), # Unsorted, wheel mismatch.
+ mutate(b"\n", b"\n# comment\n"), # Valid TOML, not canonical.
+ mutate(b"size = 1024", b"size=1024"),
+ sklearn_lock_bytes() + b"\n",
+ sklearn_lock_bytes().replace(b"\n", b"\r\n"),
+ b"\xff\xfe",
+ b"packages = " + b"[" * 2000 + b"]" * 2000,
+ b"lock-version = ",
+ b"",
+ ],
+)
+def test_parser_rejections(data):
+ with pytest.raises(InvalidEnvironmentLockError) as error:
+ EnvironmentLock.from_bytes(data)
+ assert str(error.value) in (
+ "Invalid environment lock.",
+ "Environment lock is not canonical.",
+ )
diff --git a/tests/test_inspection.py b/tests/test_inspection.py
index d773a98..258e241 100644
--- a/tests/test_inspection.py
+++ b/tests/test_inspection.py
@@ -5,6 +5,7 @@
import pytest
+from lock_helpers import sklearn_lock_bytes
from mlbundle import (
ArchiveLimits,
InvalidContainerError,
@@ -41,11 +42,21 @@ def test_inspect_and_optional_json(manifest_data):
}
bundle = write_container(
manifest_data,
- {MemberName.SKOPS: b"model", MemberName.SCHEMA: canonical_dumps(schema)},
+ {
+ MemberName.SKOPS: b"model",
+ MemberName.SCHEMA: canonical_dumps(schema),
+ MemberName.LOCK: sklearn_lock_bytes(),
+ },
)
view = inspect(bundle)
assert isinstance(view, MetadataView)
- assert view.members == (MemberName.MANIFEST, MemberName.SKOPS, MemberName.SCHEMA)
+ assert view.members == (
+ MemberName.MANIFEST,
+ MemberName.SKOPS,
+ MemberName.SCHEMA,
+ MemberName.LOCK,
+ )
+ assert view.environment_lock.to_bytes() == sklearn_lock_bytes()
assert view.manifest.integrity[MemberName.SKOPS].size == 5
assert not hasattr(view, "native_model")
assert view.schema == schema and view.samples is None
@@ -61,6 +72,7 @@ def test_inspect_no_model_imports(manifest_data, tmp_path):
{
MemberName.SKOPS: b"model",
MemberName.SCHEMA: canonical_dumps(schema_for_manifest(manifest_data)),
+ MemberName.LOCK: sklearn_lock_bytes(),
},
destination=target,
)
diff --git a/tests/test_limits.py b/tests/test_limits.py
index a5f7dd6..6691097 100644
--- a/tests/test_limits.py
+++ b/tests/test_limits.py
@@ -8,8 +8,9 @@
def test_limits():
limits = ArchiveLimits()
- assert limits.max_members == 6
+ assert limits.max_members == 7
assert limits.member_bytes(MemberName.SKOPS) == 512 * 1024**2
+ assert limits.member_bytes(MemberName.LOCK) == 1024**2
assert limits.member_bytes(MemberName.STRUCTURE) == 256 * 1024**2
assert (
ArchiveLimits(max_member_bytes=1024).member_bytes(MemberName.MANIFEST) == 1024
@@ -19,7 +20,8 @@ def test_limits():
@pytest.mark.parametrize(
"fields",
[
- {"max_members": 7},
+ {"max_members": 8},
+ {"max_lock_bytes": 1024**2 + 1},
{"max_compression_ratio": 201},
{"max_total_bytes": 0},
{"max_structure_bytes": "10"},
diff --git a/tests/test_lock_binding.py b/tests/test_lock_binding.py
new file mode 100644
index 0000000..a2f8478
--- /dev/null
+++ b/tests/test_lock_binding.py
@@ -0,0 +1,139 @@
+"""The lock inside bundles: manifest binding, container bounds and export fidelity."""
+
+import pytest
+from sklearn.tree import DecisionTreeClassifier
+
+import mlbundle
+from lock_helpers import pure_wheel, sklearn_lock_bytes, synthetic_lock
+from mlbundle import (
+ InvalidContainerError,
+ InvalidEnvironmentLockError,
+ LimitExceededError,
+ LockedPackage,
+ MemberName,
+)
+from mlbundle.container import read_container
+from mlbundle.writing import write_container
+
+
+def bundle_parts(manifest_data, lock):
+ from conftest import schema_for_manifest
+ from mlbundle.canonical import canonical_dumps
+
+ manifest_data.pop("integrity")
+ members = {
+ MemberName.SKOPS: b"native model bytes",
+ MemberName.SCHEMA: canonical_dumps(schema_for_manifest(manifest_data)),
+ }
+ if lock is not None:
+ members[MemberName.LOCK] = lock
+ return members
+
+
+@pytest.mark.parametrize(
+ "packages,python,implementation",
+ [
+ ({"pydantic": "2.14.1", "scikit-learn": "1.9.1"}, "3.14.0", "CPython"),
+ ({"pydantic": "2.14.1", "skops": "0.16.0"}, "3.14.0", "CPython"),
+ ({"scikit-learn": "1.9.1", "skops": "0.16.0"}, "3.14.0", "CPython"),
+ (None, "3.14.1", "CPython"),
+ (None, "3.14.0", "PyPy"),
+ ],
+)
+def test_lock_binds_to_manifest(manifest_data, packages, python, implementation):
+ manifest_data["environment"]["python_implementation"] = implementation
+ lock = (
+ sklearn_lock_bytes(python)
+ if packages is None
+ else synthetic_lock(python, packages).to_bytes()
+ )
+ with pytest.raises(InvalidEnvironmentLockError):
+ write_container(manifest_data, bundle_parts(manifest_data, lock))
+
+
+def test_xgboost_cpu_alternative_and_platform_coverage(manifest_data):
+ manifest_data["model"].update(library="xgboost", serialization="ubjson")
+ base = {"pydantic": "2.14.1", "scikit-learn": "1.9.1"}
+ for name in ("xgboost", "xgboost-cpu"):
+ members = bundle_parts(dict(manifest_data, integrity={}), None)
+ members[MemberName.UBJSON] = members.pop(MemberName.SKOPS)
+ members[MemberName.LOCK] = synthetic_lock(
+ "3.14.0", base | {name: "3.4.1"}
+ ).to_bytes()
+ assert write_container(manifest_data, members)
+ both = synthetic_lock("3.14.0", base | {"xgboost": "3.4.1", "xgboost-cpu": "3.4.1"})
+ members[MemberName.LOCK] = both.to_bytes()
+ with pytest.raises(InvalidEnvironmentLockError):
+ write_container(manifest_data, members)
+ partial = synthetic_lock("3.14.0", base).model_copy(
+ update={
+ "packages": (
+ *synthetic_lock("3.14.0", base).packages,
+ LockedPackage(
+ name="xgboost",
+ version="3.4.1",
+ platforms=("linux-x86_64", "linux-aarch64"),
+ wheels=(pure_wheel("xgboost", "3.4.1"),),
+ ),
+ )
+ }
+ )
+ members[MemberName.LOCK] = partial.to_bytes()
+ with pytest.raises(InvalidEnvironmentLockError):
+ write_container(manifest_data, members)
+
+
+def test_container_requires_and_bounds_the_lock(parts):
+ from conftest import build_zip
+
+ with pytest.raises(InvalidContainerError, match="predates the required pylock"):
+ read_container(build_zip(parts[:3]))
+ with pytest.raises(LimitExceededError):
+ read_container(
+ build_zip(parts), limits=mlbundle.ArchiveLimits(max_lock_bytes=64)
+ )
+ tampered = [*parts[:3], ("pylock.toml", parts[3][1].replace(b"1024", b"1025", 1))]
+ with pytest.raises(mlbundle.IntegrityMismatchError):
+ read_container(build_zip(tampered))
+ assert read_container(build_zip(parts))[1][MemberName.LOCK] == parts[3][1]
+
+
+def test_export_with_explicit_lock_and_fidelity(tmp_path):
+ model = DecisionTreeClassifier().fit([[0], [1]], [0, 1])
+ generated = mlbundle.export(model, tmp_path / "a.mlbundle").environment_lock
+ for source in (generated.to_bytes(), tmp_path / "pylock.toml"):
+ (tmp_path / "pylock.toml").write_bytes(generated.to_bytes())
+ view = mlbundle.export(
+ model, tmp_path / "b.mlbundle", environment_lock=source, overwrite=True
+ )
+ assert view.environment_lock == generated
+ assert mlbundle.load(tmp_path / "b.mlbundle").environment_lock == generated
+ stale = generated.model_copy(
+ update={
+ "packages": tuple(
+ p.model_copy(
+ update={"version": "1.0", "wheels": (pure_wheel(p.name, "1.0"),)}
+ )
+ if p.name == "scikit-learn"
+ else p
+ for p in generated.packages
+ )
+ }
+ )
+ with pytest.raises(InvalidEnvironmentLockError, match=r"scikit-learn locked 1.0"):
+ mlbundle.export(
+ model, tmp_path / "c.mlbundle", environment_lock=stale.to_bytes()
+ )
+ other = generated.model_copy(update={"python_version": "3.14.99"})
+ with pytest.raises(InvalidEnvironmentLockError, match="Python"):
+ mlbundle.export(
+ model, tmp_path / "c.mlbundle", environment_lock=other.to_bytes()
+ )
+ with pytest.raises(LimitExceededError):
+ mlbundle.export(
+ model,
+ tmp_path / "c.mlbundle",
+ environment_lock=generated.to_bytes(),
+ limits=mlbundle.ArchiveLimits(max_lock_bytes=16),
+ )
+ assert not (tmp_path / "c.mlbundle").exists()
diff --git a/tests/test_lock_generation.py b/tests/test_lock_generation.py
new file mode 100644
index 0000000..e28ac7b
--- /dev/null
+++ b/tests/test_lock_generation.py
@@ -0,0 +1,239 @@
+"""Training-side lock generation: installed pins, per-target uv output and its errors."""
+
+import hashlib
+import platform
+import re
+import subprocess
+import sys
+from importlib import metadata
+from pathlib import Path
+
+import pytest
+
+from mlbundle import (
+ LockGenerationError,
+ MissingOptionalDependencyError,
+ _lock_generation,
+)
+from mlbundle._wheel_tags import PLATFORMS, UV_PLATFORMS, normalize
+from mlbundle.contract import Library
+from mlbundle.lock import runtime_requirements
+
+
+@pytest.fixture
+def offline_lock():
+ """This module exercises the real resolver; the shared fixture replaces it."""
+
+
+class Distribution:
+ def __init__(self, name, version, direct=None):
+ self.metadata = {"Name": name}
+ self.version = version
+ self.direct = direct
+
+ def read_text(self, filename):
+ return self.direct if filename == "direct_url.json" else None
+
+
+def test_installed_distributions(monkeypatch):
+ found = [
+ Distribution("Scikit_Learn", "1.9.1"),
+ Distribution("scikit-learn", "1.0"), # Shadowed by the first on sys.path.
+ Distribution("mlbundle", "0.3.0", direct='{"dir_info": {"editable": true}}'),
+ Distribution(
+ "skops", "0.16.0", direct='{"url": "file:///w.whl", "archive_info": {}}'
+ ),
+ Distribution(
+ "scipy", "1.18.1", direct='{"url": "git+https://x", "vcs_info": {}}'
+ ),
+ Distribution("numpy", "2.5.4", direct="not json"),
+ Distribution("torch", "2.0+cpu"),
+ Distribution("--index-url", "1.0"),
+ Distribution(None, "1.0"),
+ ]
+ monkeypatch.setattr(_lock_generation.metadata, "distributions", lambda: found)
+ # A wheel installed from a file keeps its version; source trees cannot be pinned.
+ assert _lock_generation.installed_distributions() == {
+ "scikit-learn": "1.9.1",
+ "mlbundle": None,
+ "skops": "0.16.0",
+ "scipy": None,
+ "numpy": None,
+ "torch": None,
+ }
+
+
+def test_roots_pick_one_installed_distribution_per_group():
+ groups = runtime_requirements(Library.XGBOOST)
+ installed = {"pydantic": "2.14.1", "scikit-learn": "1.9.1", "xgboost-cpu": "3.4.1"}
+ assert _lock_generation.roots(groups, installed) == installed
+ for broken, message in [
+ (installed | {"xgboost": "3.4.1"}, "Exactly one of xgboost, xgboost-cpu"),
+ ({"pydantic": "2.14.1", "scikit-learn": "1.9.1"}, "Exactly one of xgboost"),
+ (installed | {"pydantic": None}, "pydantic is installed from a source tree"),
+ ]:
+ with pytest.raises(LockGenerationError, match=message):
+ _lock_generation.roots(groups, broken)
+ composite = runtime_requirements(Library.SKLEARN, Library.CATBOOST)
+ assert [group[0] for group in composite] == [
+ "pydantic",
+ "scikit-learn",
+ "skops",
+ "catboost",
+ ]
+
+
+def test_runtime_groups_follow_the_package_extras():
+ extras: dict[str | None, set[str]] = {}
+ for line in metadata.requires("mlbundle") or []:
+ name = re.match(r"[A-Za-z0-9_.-]+", line)
+ extra = re.search(r"extra == [\"']([a-z]+)", line)
+ assert name is not None
+ extras.setdefault(extra and extra[1], set()).add(normalize(name[0]))
+ for library in Library:
+ groups = runtime_requirements(library)
+ assert {group[0] for group in groups} == extras[None] | extras[library.value]
+
+
+def uv_record(filename, size=10):
+ digest = hashlib.sha256(filename.encode()).hexdigest()
+ url = f"https://files.pythonhosted.org/packages/aa/{filename}"
+ return f'{{ url = "{url}", size = {size}, hashes = {{ sha256 = "{digest}" }} }}'
+
+
+def uv_output(packages):
+ lines = ['lock-version = "1.0"', 'created-by = "uv"', 'requires-python = ">=3.14"']
+ for name, version, files in packages:
+ wheels = ", ".join(uv_record(file) for file in files)
+ lines += ["[[packages]]", f'name = "{name}"', f'version = "{version}"']
+ lines.append(f"wheels = [{wheels}]")
+ return "\n".join(lines) + "\n"
+
+
+def fake_uv(monkeypatch, outputs, returncode=0, stderr=""):
+ """Write per-target uv output; outputs are keyed by mlbundle target names."""
+ calls = []
+ targets = {uv: target for target, uv in UV_PLATFORMS.items()}
+
+ def run(command, *, cwd, **_):
+ calls.append(command)
+ target = targets[command[command.index("--python-platform") + 1]]
+ if returncode == 0:
+ out = Path(cwd) / command[command.index("--output-file") + 1]
+ out.write_text(uv_output(outputs.get(target, [])), encoding="utf-8")
+ return subprocess.CompletedProcess(command, returncode, "", stderr)
+
+ monkeypatch.setattr(_lock_generation, "_uv", lambda: "uv")
+ monkeypatch.setattr(_lock_generation.subprocess, "run", run)
+ return calls
+
+
+PURE = ("pydantic", "2.14.1", ["pydantic-2.14.1-py3-none-any.whl"])
+NUMPY = {
+ "linux-x86_64": "numpy-2.5.4-cp314-cp314-manylinux_2_28_x86_64.whl",
+ "linux-aarch64": "numpy-2.5.4-cp314-cp314-manylinux_2_28_aarch64.whl",
+ "win-amd64": "numpy-2.5.4-cp314-cp314-win_amd64.whl",
+}
+WCWIDTH = {
+ "linux-x86_64": "wcwidth-0.9.2-cp310-abi3-manylinux2014_x86_64.whl",
+ "linux-aarch64": "wcwidth-0.9.2-py3-none-any.whl",
+ "win-amd64": "wcwidth-0.9.2-cp310-abi3-win_amd64.whl",
+}
+NCCL = ("nvidia-nccl-cu13", "2.32.3", ["nvidia_nccl_cu13-2.32.3-py3-none-manylinux_2_27_x86_64.whl"]) # fmt: skip
+
+
+def test_resolve_merges_targets(monkeypatch):
+ outputs = {
+ target: [
+ PURE,
+ ("mlbundle", "0.3.0", ["mlbundle-0.3.0-py3-none-any.whl"]),
+ ("numpy", "2.5.4", [NUMPY[target], "numpy-2.5.4.tar.gz"]),
+ # uv also lists the pure fallback; installers take the platform wheel.
+ ("wcwidth", "0.9.2", [WCWIDTH[target], "wcwidth-0.9.2-py3-none-any.whl"]),
+ ]
+ + ([NCCL] if target == "linux-x86_64" else [])
+ for target in PLATFORMS
+ }
+ calls = fake_uv(monkeypatch, outputs)
+ lock = _lock_generation.resolve_lock(
+ "3.14.7", {"pydantic": "2.14.1"}, {"numpy": "2.5.4"}
+ )
+ assert [call[call.index("--python-platform") + 1] for call in calls] == [
+ "x86_64-manylinux_2_28",
+ "aarch64-manylinux_2_28",
+ "x86_64-pc-windows-msvc",
+ ]
+ assert all("--only-binary" in call and ":all:" in call for call in calls)
+ assert [p.name for p in lock.packages] == [
+ "numpy",
+ "nvidia-nccl-cu13",
+ "pydantic",
+ "wcwidth",
+ ]
+ numpy, nccl, _, wcwidth = lock.packages
+ assert [w.name for w in numpy.wheels] == sorted(NUMPY.values())
+ assert [w.name for w in wcwidth.wheels] == sorted(WCWIDTH.values())
+ assert nccl.platforms == ("linux-x86_64",)
+ assert [len(p.wheels) for p in lock.packages] == [3, 1, 1, 3]
+
+
+@pytest.mark.parametrize(
+ "outputs,message",
+ [
+ (
+ {"linux-x86_64": [PURE], "win-amd64": [("pydantic", "2.14.0", PURE[2])]},
+ "different versions",
+ ),
+ (
+ {"linux-x86_64": [("numpy", "2.5.4", ["numpy-2.5.4.tar.gz"])]},
+ "no single preferred CPython wheel",
+ ),
+ (
+ {"win-amd64": [("numpy", "2.5.4", [NUMPY["linux-x86_64"]])]},
+ "no single preferred CPython wheel for win-amd64",
+ ),
+ (
+ {"linux-x86_64": [("Bad Name", "1.0", ["bad-1.0-py3-none-any.whl"])]},
+ "not lockable",
+ ),
+ ],
+)
+def test_resolve_rejects_unlockable_environments(monkeypatch, outputs, message):
+ fake_uv(monkeypatch, outputs)
+ with pytest.raises(LockGenerationError, match=message):
+ _lock_generation.resolve_lock("3.14.7", {"pydantic": "2.14.1"}, {})
+
+
+def test_uv_failures(monkeypatch):
+ fake_uv(monkeypatch, {}, returncode=1, stderr="No solution\x1b[31m found")
+ with pytest.raises(LockGenerationError) as error:
+ _lock_generation.resolve_lock("3.14.7", {"pydantic": "2.14.1"}, {})
+ assert "linux-x86_64" in str(error.value) and "\x1b" not in str(error.value)
+
+ def timeout(command, **_):
+ raise subprocess.TimeoutExpired(command, 1)
+
+ monkeypatch.setattr(_lock_generation.subprocess, "run", timeout)
+ with pytest.raises(LockGenerationError, match="timed out"):
+ _lock_generation.resolve_lock("3.14.7", {"pydantic": "2.14.1"}, {})
+
+
+def test_missing_uv(monkeypatch):
+ monkeypatch.setitem(sys.modules, "uv", None)
+ with pytest.raises(MissingOptionalDependencyError) as error:
+ _lock_generation.resolve_lock("3.14.7", {"pydantic": "2.14.1"}, {})
+ assert error.value.extra == "lock"
+
+
+@pytest.mark.network
+def test_generate_locks_the_installed_runtime_with_uv():
+ """Resolve the sklearn runtime of this interpreter through the package index."""
+ lock = _lock_generation.generate_lock(runtime_requirements(Library.SKLEARN))
+ installed = _lock_generation.installed_distributions()
+ assert lock.python_version == platform.python_version()
+ for name in ("pydantic", "scikit-learn", "skops", "numpy", "scipy"):
+ assert lock.version(name) == installed[name]
+ _lock_generation.check_fidelity(lock, installed)
+ assert all(
+ wheel.url.startswith("https://") for p in lock.packages for wheel in p.wheels
+ )
diff --git a/tests/test_manifest.py b/tests/test_manifest.py
index db2e3d8..0f90973 100644
--- a/tests/test_manifest.py
+++ b/tests/test_manifest.py
@@ -21,7 +21,6 @@ def read(data: dict) -> Manifest:
@pytest.mark.parametrize("writer_version", ["0.1.0", "0.1.0a3"])
def test_writer_version_is_independent_of_reader(manifest_data, writer_version):
manifest_data["writer_version"] = writer_version
- manifest_data["environment"]["packages"]["mlbundle"] = writer_version
assert read(manifest_data).writer_version == writer_version
@@ -241,12 +240,15 @@ def test_member_cap_and_bad_integrity(manifest_data):
def test_environment_invariants_and_onnx(manifest_data):
- manifest_data["environment"]["packages"]["mlbundle"] = "different"
- with pytest.raises(InvalidManifestError):
- read(manifest_data)
- manifest_data["environment"]["packages"]["mlbundle"] = manifest_data[
- "writer_version"
- ]
+ for key, value in [("free_threaded", 0), ("packages", {"mlbundle": "0.2.1"})]:
+ environment = dict(manifest_data["environment"])
+ environment[key] = value
+ with pytest.raises(InvalidManifestError):
+ read({**manifest_data, "environment": environment})
+ for lock in [None, "lock.toml"]:
+ references = {**manifest_data["references"], "lock": lock}
+ with pytest.raises(InvalidManifestError):
+ read({**manifest_data, "references": references})
manifest_data["model"].update(library="onnx", serialization="onnx")
manifest_data["integrity"].pop("model.skops")
manifest_data["integrity"]["model.onnx"] = hash_member(b"onnx").model_dump()
diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py
index 16bfed5..11811e1 100644
--- a/tests/test_pipeline.py
+++ b/tests/test_pipeline.py
@@ -69,7 +69,7 @@ def test_schema_samples_lowered_limits_and_labels(tmp_path):
class_labels=[["no", "yes"]],
)
bundle = mlbundle.load(destination)
- assert len(bundle.members) == 6
+ assert len(bundle.members) == 7
assert bundle.samples == frame.head(2).to_dict("records")
assert bundle.class_labels == [["no", "yes"]]
assert list(bundle.native_model.classes_) == [0, 1]
diff --git a/tests/test_results.py b/tests/test_results.py
index b694ec7..6b6548e 100644
--- a/tests/test_results.py
+++ b/tests/test_results.py
@@ -4,7 +4,9 @@
import pytest
+from lock_helpers import sklearn_lock_bytes
from mlbundle import (
+ EnvironmentLock,
FeatureOrigin,
Library,
LoadedBundle,
@@ -15,6 +17,8 @@
)
from mlbundle.canonical import canonical_dumps
+LOCK = EnvironmentLock.from_bytes(sklearn_lock_bytes())
+
class Predictor:
def predict(self, data):
@@ -28,7 +32,9 @@ def test_metadata_view(manifest_data):
view = MetadataView(
Manifest.from_bytes(canonical_dumps(manifest_data)),
(MemberName.MANIFEST, MemberName.SKOPS),
+ LOCK,
)
+ assert view.environment_lock.version("skops") == "0.16.0"
assert not hasattr(view, "native_model")
with pytest.raises(FrozenInstanceError):
view.members = ()
@@ -39,6 +45,7 @@ def test_loaded_classifier(manifest_data):
bundle = LoadedBundle(
Manifest.from_bytes(canonical_dumps(manifest_data)),
(MemberName.MANIFEST, MemberName.SKOPS),
+ LOCK,
native,
Predictor(),
)
@@ -60,7 +67,11 @@ def test_loaded_regressor(manifest_data):
manifest_data["model"].update(kind="regressor", n_classes=None)
manifest_data["target"]["class_labels"] = None
bundle = LoadedBundle(
- Manifest.from_bytes(canonical_dumps(manifest_data)), (), object(), Predictor()
+ Manifest.from_bytes(canonical_dumps(manifest_data)),
+ (),
+ LOCK,
+ object(),
+ Predictor(),
)
assert bundle.class_labels is None
assert bundle.predict([[2]]) == [2.0]
diff --git a/tests/test_samples.py b/tests/test_samples.py
index c9514e7..49a37c1 100644
--- a/tests/test_samples.py
+++ b/tests/test_samples.py
@@ -129,6 +129,7 @@ def test_exact_sample_selection_and_conversion(data, model, tmp_path):
MemberName.SKOPS,
MemberName.SCHEMA,
MemberName.SAMPLES,
+ MemberName.LOCK,
}
# Include the final row only when the explicitly selected count is three.
full = mlbundle.export(
@@ -153,7 +154,7 @@ def test_schema_structure_samples_coexist(tmp_path):
target_names=["target"],
sample_rows=1,
)
- assert len(view.members) == 5
+ assert len(view.members) == 6
assert view.samples == [{"a": 0}]
assert mlbundle.load(tmp_path / "all.mlbundle").structure is not None
diff --git a/tests/test_version_diagnostics.py b/tests/test_version_diagnostics.py
index f9bb371..61ddf13 100644
--- a/tests/test_version_diagnostics.py
+++ b/tests/test_version_diagnostics.py
@@ -9,6 +9,7 @@
from xgboost import XGBClassifier
import mlbundle
+from lock_helpers import pure_wheel, sklearn_lock_bytes
from mlbundle import _load_diagnostics
from mlbundle._sklearn import Adapter, transformers
from mlbundle.canonical import canonical_dumps
@@ -30,14 +31,25 @@ def path(tmp_path):
def declared_package(path, declared):
+ """Rewrite the locked scikit-learn version, the declaration diagnostics read."""
manifest, members = read_container(path)
- parts = manifest.model_dump(mode="json", by_alias=True)
- if declared is None:
- parts["environment"]["packages"].pop("scikit-learn", None)
- else:
- parts["environment"]["packages"]["scikit-learn"] = declared
+ lock = mlbundle.EnvironmentLock.from_bytes(members[mlbundle.MemberName.LOCK])
+ packages = tuple(
+ package.model_copy(
+ update={
+ "version": declared,
+ "wheels": (pure_wheel(package.name, declared),),
+ }
+ )
+ if package.name == "scikit-learn"
+ else package
+ for package in lock.packages
+ )
+ members[mlbundle.MemberName.LOCK] = lock.model_copy(
+ update={"packages": packages}
+ ).to_bytes()
del members[mlbundle.MemberName.MANIFEST]
- return write_container(parts, members)
+ return write_container(manifest, members)
def test_environment_mismatch_after_failure(path, monkeypatch):
@@ -55,12 +67,8 @@ def test_environment_mismatch_after_failure(path, monkeypatch):
)
-@pytest.mark.parametrize(
- "declared",
- [None, "1.9.0", "private\n\x1b", "1.9.1 ", "9" * 65, "v1.9.1", "1.9.1;evil"],
-)
-def test_invalid_or_equal_environment_keeps_original(path, monkeypatch, declared):
- data = declared_package(path, declared)
+def test_equal_environment_keeps_original(path, monkeypatch):
+ data = declared_package(path, "1.9.0")
monkeypatch.setattr(_load_diagnostics, "version", lambda _: "1.9.0")
monkeypatch.setattr(Adapter, "deserialize", failed_load)
with pytest.raises(mlbundle.InvalidModelError) as error:
@@ -69,6 +77,16 @@ def test_invalid_or_equal_environment_keeps_original(path, monkeypatch, declared
assert str(error.value) == "Skops state does not survive native construction."
+@pytest.mark.parametrize(
+ "declared", ["private\\n", "1.9.1 ", "9" * 65, "v1.9.1", "1.9.1;evil", "1.9+x"]
+)
+def test_unsafe_declared_versions_never_reach_diagnostics(declared):
+ # The lock rejects such versions before any reader can display them.
+ data = sklearn_lock_bytes().replace(b'"1.9.1"', f'"{declared}"'.encode())
+ with pytest.raises(mlbundle.InvalidEnvironmentLockError):
+ mlbundle.EnvironmentLock.from_bytes(data)
+
+
def test_unavailable_installed_metadata_keeps_original(path, monkeypatch):
def absent(_):
raise importlib.metadata.PackageNotFoundError
@@ -124,13 +142,13 @@ def test_old_manifest_diagnosis_shared_by_inspect_and_load(manifest_data, writer
from conftest import build_zip, schema_for_manifest
manifest_data["writer_version"] = writer
- manifest_data["environment"]["packages"]["mlbundle"] = writer
manifest_data["target"]["name"] = manifest_data["target"].pop("names")
data = build_zip(
[
("manifest.json", canonical_dumps(manifest_data)),
("model.skops", b"native model bytes"),
("schema.json", canonical_dumps(schema_for_manifest(manifest_data))),
+ ("pylock.toml", sklearn_lock_bytes()),
]
)
expected = (
diff --git a/tests/test_writing.py b/tests/test_writing.py
index 57691c6..ee59d51 100644
--- a/tests/test_writing.py
+++ b/tests/test_writing.py
@@ -9,6 +9,7 @@
import pytest
+from lock_helpers import library_lock_bytes, sklearn_lock_bytes
from mlbundle import (
ArchiveLimits,
InvalidContainerError,
@@ -23,6 +24,18 @@
from mlbundle.integrity import hash_member
from mlbundle.writing import write_container
+LOCK = sklearn_lock_bytes()
+
+
+def members(model=b"model", extra=None):
+ """The required model, schema and lock members, plus optional ones."""
+ return {
+ MemberName.SKOPS: model,
+ MemberName.SCHEMA: b"{}",
+ MemberName.LOCK: LOCK,
+ **(extra or {}),
+ }
+
@pytest.mark.parametrize(
"library,serialization,member",
@@ -44,7 +57,11 @@ def test_roundtrip_and_determinism(
"producer_name": "",
"producer_version": "",
}
- members = {member: b"dummy native bytes", MemberName.SCHEMA: b"{}"}
+ members = {
+ member: b"dummy native bytes",
+ MemberName.SCHEMA: b"{}",
+ MemberName.LOCK: library_lock_bytes(library),
+ }
if optional:
for name in (MemberName.SCHEMA, MemberName.STRUCTURE, MemberName.SAMPLES):
members[name] = b"[]" if name == MemberName.SAMPLES else b"{}"
@@ -74,7 +91,7 @@ def test_atomic_write_and_failure(manifest_data, tmp_path, monkeypatch, overwrit
target = tmp_path / "model.mlbundle"
args = (
Manifest.from_bytes(canonical_dumps(manifest_data)),
- {MemberName.SKOPS: b"model", MemberName.SCHEMA: b"{}"},
+ members(),
)
first = write_container(*args, destination=target)
assert read_container(str(target)) == read_container(io.BytesIO(first))
@@ -102,7 +119,10 @@ def fail(*args, **kwargs):
({"../model.skops": b"x"}, InvalidContainerError),
({"mödél.skops": b"x"}, InvalidContainerError),
({}, InvalidContainerError),
- ({MemberName.SKOPS: "text", MemberName.SCHEMA: b"{}"}, TypeError),
+ (
+ members("text"),
+ TypeError,
+ ),
],
)
def test_invalid_writer_inputs(manifest_data, members, error):
@@ -129,7 +149,7 @@ def test_writer_limits_leave_destination_untouched(
with pytest.raises(LimitExceededError):
write_container(
manifest_data,
- {MemberName.SKOPS: data, MemberName.SCHEMA: b"{}"},
+ members(data),
destination=target,
overwrite=True,
limits=limits,
@@ -147,11 +167,7 @@ def race(temporary, destination):
monkeypatch.setattr("os.link", race)
with pytest.raises(FileExistsError):
- write_container(
- manifest_data,
- {MemberName.SKOPS: b"model", MemberName.SCHEMA: b"{}"},
- destination=target,
- )
+ write_container(manifest_data, members(), destination=target)
assert target.read_bytes() == b"concurrent writer"
assert list(tmp_path.glob(".mlbundle-*")) == []
@@ -159,7 +175,8 @@ def race(temporary, destination):
def test_chunked_model_and_empty_model(manifest_data):
for data in (b"", random.Random(0).randbytes(200_000)):
bundle = write_container(
- manifest_data, {MemberName.SKOPS: data, MemberName.SCHEMA: b"{}"}
+ manifest_data,
+ members(data),
)
assert read_container(bundle)[1][MemberName.SKOPS] == data
@@ -169,32 +186,32 @@ def test_chunked_model_and_empty_model(manifest_data):
[
(
b"native model bytes",
- "04135705c8b64e3a492fc543b0cb150a747cc2214533c9425ba93d61870b7494",
+ "40e99a2b18f553f472e80a927d9e91bc6a9dbc3898d74af77ad9c824b1607bf0",
),
(
random.Random(0).randbytes(200_000),
- "af4a7e26486a59a105f9363c4b8d034172c27a7058d80635d2dadadf26b8ac05",
+ "d0b89eb6cf6bb8111c0092e82ff68ef6e7e3e4d0358ab80f8d39350471e36bd2",
),
(
b"hello world " * 10_000,
- "a69ad3950fbf46b8524f38f65b92911215dc435060b4158b7be2c01adb6b79dc",
+ "6307dad280d669bdfde636ec9c28944ed846223ecf8d626324e7002252032ab9",
),
(
bytes(range(256)) * 500,
- "605ab1cb22b719643413342f342258cb92d81be9aa65bbfe19ebeccc27a9b1f3",
+ "972bc3cdaab56f8a29a91d425db3763f1b4e03c13f5ada1aee04b469fd76f744",
),
(
b"0" * 1000,
- "1f1facf21a7f91d32984764a4efb4c8b9bf9992aa4c639c0abe2cd3b943e14d9",
+ "a912f364d08d799a2a9eaf9b1bafcb459f2c9133c132891d95d2adfedee9b0a1",
),
],
ids=["native", "noise", "text", "uniform", "runs"],
)
def test_fixed_archive_bytes_on_both_platforms(manifest_data, data, expected):
manifest_data["writer_version"] = "0.1.0a3"
- manifest_data["environment"]["packages"]["mlbundle"] = "0.1.0a3"
bundle = write_container(
- manifest_data, {MemberName.SKOPS: data, MemberName.SCHEMA: b"{}"}
+ manifest_data,
+ members(data),
)
assert hashlib.sha256(bundle).hexdigest() == expected
@@ -210,15 +227,13 @@ def test_writer_optional_member_errors(manifest_data, name):
]:
with pytest.raises(error):
write_container(
- manifest_data,
- {MemberName.SKOPS: b"model", MemberName.SCHEMA: b"{}", member: data},
- limits=limits,
+ manifest_data, members(b"model", {member: data}), limits=limits
)
manifest_data["references"][name] = None
with pytest.raises(InvalidManifestError):
write_container(
manifest_data,
- {MemberName.SKOPS: b"model", MemberName.SCHEMA: b"{}", member: b"{}"},
+ members(b"model", {member: b"{}"}),
)
@@ -236,10 +251,7 @@ def observed(data, cap):
with pytest.raises(LimitExceededError):
write_container(
manifest_data,
- {
- MemberName.SKOPS: random.Random(0).randbytes(2000),
- MemberName.SCHEMA: b"{}",
- },
+ members(random.Random(0).randbytes(2000)),
limits=ArchiveLimits(max_archive_bytes=2048, max_compressed_bytes=1000),
)
assert len(caps) == 2 and 0 < caps[1] < caps[0] == 1000
@@ -272,25 +284,13 @@ def fail_second(fd):
monkeypatch.setattr(os, "fsync", fail_second)
if race or fail_copy:
with pytest.raises(FileExistsError if race else OSError):
- write_container(
- manifest_data,
- {MemberName.SKOPS: b"model", MemberName.SCHEMA: b"{}"},
- destination=target,
- )
+ write_container(manifest_data, members(), destination=target)
assert target.read_bytes() == b"other writer" if race else not target.exists()
else:
- result = write_container(
- manifest_data,
- {MemberName.SKOPS: b"model", MemberName.SCHEMA: b"{}"},
- destination=target,
- )
+ result = write_container(manifest_data, members(), destination=target)
assert target.read_bytes() == result
if os.name != "nt":
assert stat.S_IMODE(target.stat().st_mode) == 0o600
with pytest.raises(FileExistsError):
- write_container(
- manifest_data,
- {MemberName.SKOPS: b"model", MemberName.SCHEMA: b"{}"},
- destination=target,
- )
+ write_container(manifest_data, members(), destination=target)
assert not list(tmp_path.glob(".mlbundle-*"))
diff --git a/uv.lock b/uv.lock
index 29e8825..6d4d31a 100644
--- a/uv.lock
+++ b/uv.lock
@@ -459,7 +459,7 @@ wheels = [
[[package]]
name = "mlbundle"
-version = "0.2.1"
+version = "0.3.0"
source = { editable = "." }
dependencies = [
{ name = "pydantic" },
@@ -473,11 +473,15 @@ all = [
{ name = "onnxruntime" },
{ name = "scikit-learn" },
{ name = "skops" },
+ { name = "uv" },
{ name = "xgboost" },
]
catboost = [
{ name = "catboost" },
]
+lock = [
+ { name = "uv" },
+]
onnx = [
{ name = "onnx" },
{ name = "onnxruntime" },
@@ -521,10 +525,12 @@ requires-dist = [
{ name = "scikit-learn", marker = "extra == 'xgboost'", specifier = ">=1.2" },
{ name = "skops", marker = "extra == 'all'", specifier = ">=0.16.0" },
{ name = "skops", marker = "extra == 'sklearn'", specifier = ">=0.16.0" },
+ { name = "uv", marker = "extra == 'all'", specifier = ">=0.13.5" },
+ { name = "uv", marker = "extra == 'lock'", specifier = ">=0.13.5" },
{ name = "xgboost", marker = "extra == 'all'", specifier = ">=3.4.1" },
{ name = "xgboost", marker = "extra == 'xgboost'", specifier = ">=3.4.1" },
]
-provides-extras = ["sklearn", "xgboost", "catboost", "onnx", "schema", "all"]
+provides-extras = ["sklearn", "xgboost", "catboost", "onnx", "schema", "lock", "all"]
[package.metadata.requires-dev]
dev = [
@@ -1229,6 +1235,32 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/94/21/1e5995a1c920cce14e4bffae20c665ec10e7ed03ab25e006cd741092b718/tzdata-2026.5-py2.py3-none-any.whl", hash = "sha256:b683bd1b6659ddcd810ff02ad09ba821d4bf1065072805063eb35c49617905ac", size = 347996, upload-time = "2026-10-03T09:23:12.535Z" },
]
+[[package]]
+name = "uv"
+version = "0.13.6"
+source = { registry = "https://pypi.org/simple" }
+sdist = { url = "https://files.pythonhosted.org/packages/08/d5/88d43310d425f6e3a43997ad771658ded3237d0ed78c16a89b2353eddf56/uv-0.13.6.tar.gz", hash = "sha256:d762215478854f6cf20c3faed8f1eb30c8101d568e7bc32a3abafc063929d5c5", size = 7545242, upload-time = "2026-10-27T00:45:57.605Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/e4/05/74c9ae1b59e0aa49f1fa84f31ea4ee0ec930825681d3af8430c017faa848/uv-0.13.6-py3-none-linux_armv6l.whl", hash = "sha256:4d20de8a3ed6c3d39b4e2f8f7d0411cd13a3959f5191b2b5d0209344034ed056", size = 18118786, upload-time = "2026-10-27T00:45:02.635Z" },
+ { url = "https://files.pythonhosted.org/packages/33/55/ff10d3f756c39a239e492e57262bd22fcda412a9f85a268175447cf33b09/uv-0.13.6-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:95f042b95e67ef8c3d3569bb6e9d895e592002c5e871cf3f1afe407c9d77a294", size = 17172613, upload-time = "2026-10-27T00:45:06.331Z" },
+ { url = "https://files.pythonhosted.org/packages/f4/14/77230cc4f6a73a31578cb8070a5f67f58a76946ead643ae8a4155620d6da/uv-0.13.6-py3-none-macosx_11_0_arm64.whl", hash = "sha256:51361029b7cf91185d0092c4b356d110b4ad629e9cb11593f1e006ac72a72ca9", size = 14344205, upload-time = "2026-10-27T00:45:09.125Z" },
+ { url = "https://files.pythonhosted.org/packages/05/3b/f78583af6504f1270da95fd0d0935e381f58330c007260f450e81a1e5e1b/uv-0.13.6-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.musllinux_1_1_aarch64.whl", hash = "sha256:7ec5486476d67a4214c460b5492393ee2300d84e1de17b293100a019b413568b", size = 17764510, upload-time = "2026-10-27T00:45:12.133Z" },
+ { url = "https://files.pythonhosted.org/packages/2b/c3/ee263d5c8e0f0bbd553b19692b1de2ce5860baf0f9653c6217535ff27833/uv-0.13.6-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.musllinux_1_1_armv7l.whl", hash = "sha256:710c68ea4853aaf70ab2d0ccf2e147dee59449f035a1f8fe7759f087a31cdbf5", size = 17679194, upload-time = "2026-10-27T00:45:15.052Z" },
+ { url = "https://files.pythonhosted.org/packages/27/33/172e323f6e424f7bf4aef0480b514132dce6350b2acf14235d9b0671fa82/uv-0.13.6-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d4d7026c7327dd11fc2c0d4bae4735ff6944293d370644f35d2e6e917cdcae04", size = 17699951, upload-time = "2026-10-27T00:45:18.118Z" },
+ { url = "https://files.pythonhosted.org/packages/96/e6/29fa137fe3699a9f61f0e05640caff4713ac485cdf09b005f99f9bd595d4/uv-0.13.6-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:46c2ef1f744f20007be0cdd66db3022bb1ddcac477c754efda875e401a48d810", size = 18467553, upload-time = "2026-10-27T00:45:21.104Z" },
+ { url = "https://files.pythonhosted.org/packages/2f/8c/bf3672027b68bd930e6764122147fcbd1f2dd9d76fc8e02707916c3e0727/uv-0.13.6-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:b2d25a49d135a441f688a6869d6d8062fb6f0a2e3e32e18b72c9de1d0eb9521e", size = 19763440, upload-time = "2026-10-27T00:45:25.536Z" },
+ { url = "https://files.pythonhosted.org/packages/a3/c0/77c56a78a94b488cf0b54e505df5ecfae65b90b08cddb8e018bb2ae66268/uv-0.13.6-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b9f57153fc98b7aa41dd6720e3de7578747f60b7bff22f50b76dcc47205bdde3", size = 19616511, upload-time = "2026-10-27T00:45:28.505Z" },
+ { url = "https://files.pythonhosted.org/packages/5c/43/0688ff5142934238f2812e348f4a24e09b57d48bfb38dd8f850325a0d9de/uv-0.13.6-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:22759b8895e1103578de6fb4cd27e94b4399d021023378d29f01333717751fba", size = 17333810, upload-time = "2026-10-27T00:45:31.291Z" },
+ { url = "https://files.pythonhosted.org/packages/99/3a/451b544e105b3595b27f74535c0d6b1105b1b2dcb9b49ca5282dd27bcbc3/uv-0.13.6-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:2e9a99100abe4f99605366974c4f9fe27f236615e05de8e78c0f357e38f09f97", size = 16527707, upload-time = "2026-10-27T00:45:34.282Z" },
+ { url = "https://files.pythonhosted.org/packages/ab/59/9483985fadf5b2e60e64ca89e215f9e2da45a54d7323b9765ba03a5ebd80/uv-0.13.6-py3-none-manylinux_2_31_riscv64.musllinux_1_1_riscv64.whl", hash = "sha256:1cd4b0a35fa599b83da5437748150319ae0917c522da60898327645382942faa", size = 18014028, upload-time = "2026-10-27T00:45:37.33Z" },
+ { url = "https://files.pythonhosted.org/packages/8d/c9/a412c2aa0494b307fce8c9c8234827f2fedb888954d3b3c8930a32a047c9/uv-0.13.6-py3-none-manylinux_2_31_riscv64.whl", hash = "sha256:8542dcf118ce8a7cf2e4ba1fea7f5cc1638bc02b5b30dab1ead7e9034dc62fd3", size = 17906467, upload-time = "2026-10-27T00:45:40.424Z" },
+ { url = "https://files.pythonhosted.org/packages/28/51/4fecb1d7a32ebf5c444643a4da9d1ae0878de0c71284792dbcdaaf61a5b8/uv-0.13.6-py3-none-musllinux_1_1_i686.whl", hash = "sha256:feb0f1d555798f68f28719cab437ab1dfb5d918db86ab4554215cbf9d940f63b", size = 17822518, upload-time = "2026-10-27T00:45:43.335Z" },
+ { url = "https://files.pythonhosted.org/packages/3a/10/7a4c287b1d377353c939f451881529528c78815d57f36097a6607187ab1a/uv-0.13.6-py3-none-musllinux_1_1_x86_64.whl", hash = "sha256:d1efed1d15102ffdbf5e0fd49a440643dda2d921a2ad856792ae42ccd43c253f", size = 18932884, upload-time = "2026-10-27T00:45:46.227Z" },
+ { url = "https://files.pythonhosted.org/packages/c8/b3/288467a6d1fdd99aca73dec3d4a919b80c201ec0d680093cd494d5b8efc7/uv-0.13.6-py3-none-win32.whl", hash = "sha256:29135609166960c74539abdaf4264f9819a0381be18b224125418356d67dd208", size = 16215356, upload-time = "2026-10-27T00:45:49.078Z" },
+ { url = "https://files.pythonhosted.org/packages/7c/9d/714523188aea3054644d8e69ae8089aac70325a3cee2d3d05509d4f23398/uv-0.13.6-py3-none-win_amd64.whl", hash = "sha256:7c9bc35ccb65932d8dc10a0669f9c805eaa3c9827ce18ecbecb1bd67944b2cdf", size = 15334118, upload-time = "2026-10-27T00:45:52.086Z" },
+ { url = "https://files.pythonhosted.org/packages/6a/7d/5ebb4cccbb11ae9e10f6cda704ce382722ab9dc68c9280a5b810378aee3e/uv-0.13.6-py3-none-win_arm64.whl", hash = "sha256:722c7f96803f115e53918b8ee8858d1680ea6077c614b6db750747d709ab8d9a", size = 15533875, upload-time = "2026-10-27T00:45:55.013Z" },
+]
+
[[package]]
name = "virtualenv"
version = "21.14.6"