diff --git a/AGENTS.md b/AGENTS.md index 7b0e0b4..b2f2275 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,7 +5,7 @@ inferred schema and model structure in one compressed `.mlbundle` file. It owns export, metadata-only inspection and validated loading. It is the training-side companion to MLSuite, whose runtime accepts `.mlbundle` uploads. -MLSuite does not train models. The package version is 0.3.0; format 1 is not frozen. +MLSuite does not train models. The package version is 0.3.1; format 1 is not frozen. Implementation claims require code and test proof. ## What must remain true diff --git a/README.md b/README.md index fce266b..28c4951 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ Website Documentation Playground - Version 0.3.0 + Version 0.3.1 Source on GitHub CI status MIT license @@ -45,11 +45,11 @@ pins the exact wheels a Linux or Windows runtime needs to serve it. ## Installation -MLbundle **0.3.0** requires Python **3.14** for export with the schema extra. +MLbundle **0.3.1** requires Python **3.14** for export with the schema extra. The installation command for this release is: ```bash -python -m pip install "mlbundle[sklearn,schema,lock]==0.3.0" +python -m pip install "mlbundle[sklearn,schema,lock]==0.3.1" ``` To use a local checkout, run `python -m pip install -e ".[sklearn,schema,lock]"` @@ -136,8 +136,8 @@ or training history. ## Runtime environment -Export locks the installed versions of pydantic, the model libraries and their -dependencies as `pylock.toml` for CPython with the GIL on Linux `x86_64` and +Export locks the installed versions of pydantic, the model libraries (and pandas +for scikit-learn pipelines that select columns by name) and their dependencies as `pylock.toml` for CPython with the GIL on Linux `x86_64` and `aarch64` and on Windows `amd64`. mlbundle itself is pinned by the manifest's `writer_version`. A runtime installs that lock plus `mlbundle==writer_version` in an isolated @@ -164,7 +164,8 @@ structure, and all-sklearn Pipeline structure is null. The ## Some notes Package versions and wire-format versions are independent. Format 1 is not frozen; -incompatible schema shapes and bundles without `pylock.toml` require re-export. The security design has not had an +incompatible schema shapes, bundles without `pylock.toml` and 0.3.0 bundles of +pipelines selecting columns by name whose lock lacks `pandas` require re-export. The security design has not had an independent review; do not accept bundles from untrusted parties. The reader bounds ZIP/JSON data, verifies integrity and uses closed native loaders. diff --git a/SECURITY.md b/SECURITY.md index 91fe2ed..ea12a49 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,6 +1,6 @@ # Security policy -MLbundle 0.3.0 has not had an independent security review; do not accept bundles +MLbundle 0.3.1 has not had an independent security review; do not accept bundles from untrusted parties. Format version 1 is not frozen. It implements strict manifest validation, secure container reading/writing, metadata-only `inspect`, export/load, sklearn, XGBoost, CatBoost and ONNX adapters, local schema inference, diff --git a/docs/format-environment.md b/docs/format-environment.md index ebbdb22..bd3259c 100644 --- a/docs/format-environment.md +++ b/docs/format-environment.md @@ -86,7 +86,11 @@ The same code validates the lock in the writer, `inspect` and `load`: lock contains pydantic and the model's library distributions on every target: `scikit-learn` and `skops`; `xgboost` or `xgboost-cpu` (not both) and `scikit-learn`; `catboost`; or `onnx` and `onnxruntime`. Composite pipelines - combine their sklearn and leaf requirements. + combine their sklearn and leaf requirements. A scikit-learn model whose + hyperparameters (or a composite's transformer hyperparameters) contain a + `ColumnTransformer` selecting any column by name also needs `pandas`, because + its records are predicted from a DataFrame. Inspection reads this from the + hyperparameter claim; `load` recomputes that claim from the model. - Bounds: the member cap is 1 MiB (`max_lock_bytes`). Invalid UTF-8, TOML errors, excessive nesting and non-canonical bytes raise `InvalidEnvironmentLockError` without echoing values. @@ -100,9 +104,9 @@ trained with them. `export` locks the running interpreter with mlbundle's `lock` extra, which provides uv: -1. Pin pydantic and the model's library distributions at their installed - versions. Exactly one distribution per requirement group must be installed; - `xgboost-cpu` satisfies XGBoost. Editable, directory, VCS and local-version +1. Pin pydantic, the model's library distributions and, where binding requires + it, pandas at their installed versions. Exactly one distribution per + requirement group must be installed; `xgboost-cpu` satisfies XGBoost. Editable, directory, VCS and local-version installs cannot be pinned; wheels installed from a file or URL keep their version. 2. Constrain every other installed distribution to its installed version. 3. For each target, resolve wheels only with diff --git a/docs/format-schema.md b/docs/format-schema.md index b1a1339..908e958 100644 --- a/docs/format-schema.md +++ b/docs/format-schema.md @@ -166,7 +166,8 @@ fallback is computed. Decisions may disagree with probabilities and are never checked against them. There is no new public array-level class-decision method. The existing predictor validates the numeric row and its output as usual. Sklearn/composite predictors supply a one-row pandas DataFrame only when their -fitted name-based column selectors require one; missing pandas raises +fitted name-based column selectors require one, so their lock pins pandas +([binding](format-environment.md#validation)); missing pandas raises `MissingOptionalDependencyError` naming the existing schema extra. Other models receive a nested numeric row, preserving native categorical behavior. This optional native-owned `record_input` hook does not change array/DataFrame diff --git a/docs/publishing.md b/docs/publishing.md index 23f64e2..d926299 100644 --- a/docs/publishing.md +++ b/docs/publishing.md @@ -1,6 +1,6 @@ # Publishing to PyPI -Version `0.3.0` is prepared by this checkout. Merging a version change into +Version `0.3.1` is prepared by this checkout. Merging a version change into `main` automatically starts the PyPI workflow; no one needs to start a release run manually. Format version 1 is not frozen, so incompatible manifest/schema shapes require re-export; 0.3.0 requires every bundle to carry `pylock.toml`, as @@ -19,7 +19,7 @@ independent review; do not accept bundles from untrusted parties. tests on Ubuntu and Windows, and all frontend checks, tests and builds. 4. If every check passes, Actions uploads the exact CI-built wheel and source archive to [mlbundle on PyPI](https://pypi.org/project/mlbundle/). - Install with `python -m pip install "mlbundle[sklearn,schema,lock]==0.3.0"` on + Install with `python -m pip install "mlbundle[sklearn,schema,lock]==0.3.1"` on Python 3.14, replacing the example version as needed. The GitHub `pypi_env` environment contains the project-scoped diff --git a/docs/src/content/docs/getting-started/installation.md b/docs/src/content/docs/getting-started/installation.md index 1188fcf..317c07c 100644 --- a/docs/src/content/docs/getting-started/installation.md +++ b/docs/src/content/docs/getting-started/installation.md @@ -1,15 +1,15 @@ --- title: Installation -description: Install mlbundle 0.3.0 with the extras for your model library, from PyPI or a local checkout, and check the Python and dependency ranges. +description: Install mlbundle 0.3.1 with the extras for your model library, from PyPI or a local checkout, and check the Python and dependency ranges. --- mlbundle requires **Python 3.14 or newer**. Its only core dependency is Pydantic v2; every model library is an optional extra that is imported lazily, only when a bundle needs it. -These pages document mlbundle 0.3.0. +These pages document mlbundle 0.3.1. ```bash -python -m pip install "mlbundle[sklearn,schema,lock]==0.3.0" +python -m pip install "mlbundle[sklearn,schema,lock]==0.3.1" ``` Replace `sklearn` with the extra for your model library; the extras are listed @@ -17,7 +17,7 @@ Replace `sklearn` with the extra for your model library; the extras are listed ## From a local checkout -To work from source, or before 0.3.0 is available from your package index, install a checkout of +To work from source, or before 0.3.1 is available from your package index, install a checkout of the repository: ```bash @@ -69,7 +69,7 @@ from importlib.metadata import version import mlbundle -print(version("mlbundle")) # 0.3.0 +print(version("mlbundle")) # 0.3.1 print(mlbundle.FORMAT_NAME, mlbundle.FORMAT_VERSION) # mlbundle 1 ``` diff --git a/docs/src/content/docs/guides/cli.md b/docs/src/content/docs/guides/cli.md index 368ddc2..38aab35 100644 --- a/docs/src/content/docs/guides/cli.md +++ b/docs/src/content/docs/guides/cli.md @@ -22,7 +22,7 @@ Metadata and integrity validated; model claims NOT verified. Format: mlbundle 1 Bundle id: aa6f6b39-574a-499b-a0ff-de4cdd334050 Created: 2026-10-19T11:17:51.949658+00:00 -Writer: "0.3.0" +Writer: "0.3.1" Model: sklearn "DecisionTreeClassifier" (classifier) Counts: features=2, outputs=1, classes=[2] Features (declared): ["temperature", "humidity"] @@ -35,7 +35,7 @@ Members: structure.json: 526 bytes sha256=66204da26781a4e2a800a1f3ed246ab1a43e8c97ced73d06a2640f897eeda03c pylock.toml: 8595 bytes sha256=b6eabc0870b4c313819d225f3be69fb320dcf0b338cb4d06b3cf24423d3af924 Training: {"python": "3.14.7", "implementation": "CPython", "free_threaded": false, "os": "Windows", "os_version": "11", "architecture": "AMD64"} -Environment 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" +Environment 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.1" Environment id: b8a31c89e5ed683e2f214cc486b83dc49e5292175c57606b11b515d494e81b57 Locked packages: {"annotated-types": "0.8.0", "cloudpickle": "3.1.2", "joblib": "1.6.0", "narwhals": "2.27.1", ...} ONNX environment: null diff --git a/docs/src/content/docs/guides/export.md b/docs/src/content/docs/guides/export.md index a3fcf55..039f545 100644 --- a/docs/src/content/docs/guides/export.md +++ b/docs/src/content/docs/guides/export.md @@ -126,7 +126,8 @@ print(view.manifest.user_metadata["name"]) # weather ## The runtime lock Every bundle contains `pylock.toml`, a PEP 751 lock of what serving the model needs: pydantic, the -model libraries and their dependencies, for CPython with the GIL on Linux `x86_64` and `aarch64` +model libraries, pandas for scikit-learn pipelines whose `ColumnTransformer` selects columns by name, +and their dependencies, for CPython with the GIL on Linux `x86_64` and `aarch64` (glibc 2.28 or newer) and on Windows `amd64`. The manifest's `writer_version` pins mlbundle itself. Export pins those distributions at their installed versions, constrains every other installed diff --git a/docs/src/content/docs/guides/inspect-and-load.md b/docs/src/content/docs/guides/inspect-and-load.md index 2bb54aa..dedb290 100644 --- a/docs/src/content/docs/guides/inspect-and-load.md +++ b/docs/src/content/docs/guides/inspect-and-load.md @@ -28,7 +28,7 @@ from mlbundle import inspect view = inspect("trained.mlbundle") manifest = view.manifest -print(manifest.format_version, manifest.writer_version) # 1 0.3.0 +print(manifest.format_version, manifest.writer_version) # 1 0.3.1 print(manifest.model.n_features, manifest.model.n_outputs) # 2 1 print([member.value for member in view.members]) # ['manifest.json', 'model.skops', 'schema.json', 'structure.json', 'pylock.toml'] diff --git a/docs/src/content/docs/guides/records.md b/docs/src/content/docs/guides/records.md index 8165ff9..55403d3 100644 --- a/docs/src/content/docs/guides/records.md +++ b/docs/src/content/docs/guides/records.md @@ -120,7 +120,7 @@ print(regression.predict_record({"temperature": 0.5, "humidity": 0.5})) ## Pipelines that select columns by name scikit-learn pipelines whose fitted column selectors use names receive a one-row pandas DataFrame -from `predict_record`; this needs pandas, which the `schema` extra installs. Other models receive a +from `predict_record`; this needs pandas, which their lock pins and the `schema` extra installs. Other models receive a numeric row, preserving their native categorical handling. The normative record rules are in [Runtime record input](/format/schema/#runtime-record-input). diff --git a/landing/src/data/example.json b/landing/src/data/example.json index 51801f3..7dc4238 100644 --- a/landing/src/data/example.json +++ b/landing/src/data/example.json @@ -1,5 +1,5 @@ { - "version": "0.3.0", + "version": "0.3.1", "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": 16176, @@ -35,7 +35,7 @@ "format_version": "1", "bundle_id": "9aca9f92-c0d2-41f1-a2f6-7a5264ddce4e", "created_at": "2026-10-28T13:54:14.550040Z", - "writer_version": "0.3.0", + "writer_version": "0.3.1", "model": { "estimator_class": "DecisionTreeClassifier", "kind": "classifier", @@ -157,7 +157,7 @@ }, "inspect": { "exit": 0, - "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: {}", + "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.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=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.1\"\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": { @@ -167,7 +167,7 @@ }, "editedInspect": { "exit": 0, - "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: {}", + "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.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=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.1\"\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/playground/README.md b/playground/README.md index b949fa8..651e149 100644 --- a/playground/README.md +++ b/playground/README.md @@ -8,7 +8,7 @@ Intended host: . Documentation: None: import mlbundle - assert mlbundle.__version__ == "0.3.0" + assert mlbundle.__version__ == "0.3.1" view = mlbundle.inspect(path) assert view.manifest.model.library == "sklearn" # The runtime lock parses with the standard library alone. diff --git a/src/mlbundle/lock.py b/src/mlbundle/lock.py index 8fad1aa..b3e7c05 100644 --- a/src/mlbundle/lock.py +++ b/src/mlbundle/lock.py @@ -6,7 +6,13 @@ import re from typing import Annotated -from pydantic import Field, StringConstraints, ValidationError, model_validator +from pydantic import ( + Field, + JsonValue, + StringConstraints, + ValidationError, + model_validator, +) from . import _lock_toml from ._base import ContractModel @@ -14,7 +20,7 @@ from .canonical import canonical_dumps from .contract import Library from .errors import InvalidEnvironmentLockError -from .manifest import Manifest +from .manifest import Manifest, ModelInfo MAX_PACKAGES = 512 # Normalized names and public versions: no local versions, which no index serves. @@ -164,13 +170,43 @@ def from_bytes(cls, data: bytes) -> EnvironmentLock: 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) +def _selects_by_name(value: JsonValue) -> bool: + """Whether sklearn hyperparameters hold a ColumnTransformer selecting by name. + + Such a model's records arrive as DataFrames (see _sklearn/record_input.py), + so it needs pandas to predict. Load recomputes these hyperparameters. + """ + if isinstance(value, list): + return any(_selects_by_name(item) for item in value) + if not isinstance(value, dict): + return False + record = value.get("$estimator") + if isinstance(record, dict) and record.get("class") == "ColumnTransformer": + params = record.get("params") + entries = params.get("transformers") if isinstance(params, dict) else None + for entry in entries if isinstance(entries, list) else []: + columns = entry[2] if isinstance(entry, list) and len(entry) == 3 else None + if isinstance(columns, str) or ( + isinstance(columns, list) and any(isinstance(c, str) for c in columns) + ): + return True + return any(_selects_by_name(item) for item in value.values()) + + +def runtime_requirements(model: ModelInfo) -> tuple[tuple[str, ...], ...]: + """Distribution groups a loaded model needs: pydantic, the adapters' libraries + and pandas when it predicts records from DataFrames.""" + groups = [*_BASE, *_LIBRARY[model.library]] + pipeline = model.pipeline + if pipeline is not None: + leaf = _LIBRARY[pipeline.estimator.library] + groups.extend(group for group in leaf if group not in groups) + prefix = None if pipeline is None else pipeline.transformers + if model.library == Library.SKLEARN and ( + _selects_by_name(model.hyperparameters) + or (prefix is not None and _selects_by_name(prefix.hyperparameters)) + ): + groups.append(("pandas",)) return tuple(groups) @@ -183,10 +219,8 @@ def check_bundle_lock(lock: EnvironmentLock, manifest: Manifest) -> None: 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): + for group in runtime_requirements(manifest.model): present = [names[name] for name in group if name in names] if len(present) != 1 or present[0].platforms != PLATFORMS: raise InvalidEnvironmentLockError( diff --git a/src/mlbundle/model_io.py b/src/mlbundle/model_io.py index 4bbf640..fb00430 100644 --- a/src/mlbundle/model_io.py +++ b/src/mlbundle/model_io.py @@ -13,6 +13,7 @@ from ._export_manifest import manifest_parts from ._load_diagnostics import sklearn_environment from ._native_io import prepare_native +from .canonical import canonical_dumps from .claims import Label, verify_claims, verify_structure_bytes from .container import read_validated_container from .contract import Library, MemberName @@ -26,6 +27,7 @@ from .inspection import metadata_view from .limits import ArchiveLimits from .lock import EnvironmentLock, runtime_requirements +from .manifest import ModelInfo from .registry import find_adapter, get_adapter, is_composite from .results import LoadedBundle, MetadataView from .schema import read_declarations, validate_separator @@ -68,10 +70,11 @@ def export( 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 + installed versions of pydantic, the model libraries (and pandas when a + ColumnTransformer selects columns by name) 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) @@ -97,14 +100,6 @@ 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 @@ -122,6 +117,17 @@ def export( cast(list[str], cast(dict, parts["features"])["names"]) ) cast(dict, parts["model"])["pipeline"] = recipe.model_dump(mode="json") + lock = ( + _lock_generation.generate_lock( + runtime_requirements( + ModelInfo.model_validate_json(canonical_dumps(parts["model"])) + ) + ) + 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() _, validated = write_validated_container( parts, members, destination=destination, overwrite=overwrite, limits=selected ) diff --git a/tests/test_lock_binding.py b/tests/test_lock_binding.py index a2f8478..906298e 100644 --- a/tests/test_lock_binding.py +++ b/tests/test_lock_binding.py @@ -13,6 +13,7 @@ MemberName, ) from mlbundle.container import read_container +from mlbundle.lock import runtime_requirements from mlbundle.writing import write_container @@ -137,3 +138,89 @@ def test_export_with_explicit_lock_and_fidelity(tmp_path): limits=mlbundle.ArchiveLimits(max_lock_bytes=16), ) assert not (tmp_path / "c.mlbundle").exists() + + +def _relocked(path, lock, change=lambda text: text): + """Rebuild a bundle around other lock bytes, as an older writer could have.""" + from conftest import build_zip + from mlbundle._container_rules import MEMBER_ORDER + from mlbundle.canonical import canonical_dumps + from mlbundle.integrity import hash_member + + manifest, members = read_container(path) + members[MemberName.LOCK] = lock + value = manifest.model_dump(mode="json", by_alias=True) + value["integrity"]["pylock.toml"] = hash_member(lock).model_dump() + members[MemberName.MANIFEST] = change(canonical_dumps(value)) + return build_zip( + [(name, members[name]) for name in MEMBER_ORDER if name in members] + ) + + +@pytest.mark.parametrize("kind", ["classifier", "composite"]) +def test_by_name_selection_locks_pandas(kind, tmp_path): + from importlib import metadata + + from record_helpers import named_pipeline + + model, _ = named_pipeline(kind) + path = tmp_path / "named.mlbundle" + lock = mlbundle.export(model, path).environment_lock + assert lock.version("pandas") == metadata.version("pandas") + assert mlbundle.load(path).environment_lock == lock + lacking = synthetic_lock( + lock.python_version, + {p.name: p.version for p in lock.packages if p.name != "pandas"}, + ).to_bytes() + with pytest.raises(InvalidEnvironmentLockError, match="exactly one of pandas"): + mlbundle.export(model, tmp_path / "x.mlbundle", environment_lock=lacking) + assert not (tmp_path / "x.mlbundle").exists() + stale = _relocked(path, lacking) + for reader in (mlbundle.inspect, mlbundle.load): + with pytest.raises(InvalidEnvironmentLockError, match="exactly one of pandas"): + reader(stale) + + +def test_hidden_name_selection_fails_verification(tmp_path): + from record_helpers import named_pipeline + + model, _ = named_pipeline("classifier") + path = tmp_path / "named.mlbundle" + lock = mlbundle.export(model, path).environment_lock + lacking = synthetic_lock( + lock.python_version, + {p.name: p.version for p in lock.packages if p.name != "pandas"}, + ).to_bytes() + # The derivation reads hyperparameters, a claim that load recomputes. + hidden = _relocked(path, lacking, lambda text: text.replace(b'["a"]', b"[0]")) + assert mlbundle.inspect(hidden).environment_lock.version("pandas") is None + with pytest.raises(mlbundle.ClaimMismatchError, match="hyperparameters"): + mlbundle.load(hidden) + + +def test_other_models_lock_no_pandas(tmp_path): + import pandas as pd + from sklearn.compose import ColumnTransformer + from sklearn.pipeline import make_pipeline + + from pipeline_helpers import pipeline + + frame = pd.DataFrame({"a": [0, 1], "b": [1, 0]}) + positional = make_pipeline( + ColumnTransformer([("select", "passthrough", [0])]), DecisionTreeClassifier() + ).fit(frame, [0, 1]) + for name, model in [ + ("positional", positional), + ("tree", DecisionTreeClassifier().fit(frame, [0, 1])), + ("catboost", pipeline("catboost")[0]), + ]: + view = mlbundle.export(model, tmp_path / f"{name}.mlbundle") + groups = runtime_requirements(view.manifest.model) + assert ("pandas",) not in groups + assert view.environment_lock.version("pandas") is None + assert [group[0] for group in groups] == [ + "pydantic", + "scikit-learn", + "skops", + "catboost", + ] diff --git a/tests/test_lock_generation.py b/tests/test_lock_generation.py index e28ac7b..3423f92 100644 --- a/tests/test_lock_generation.py +++ b/tests/test_lock_generation.py @@ -16,8 +16,9 @@ _lock_generation, ) from mlbundle._wheel_tags import PLATFORMS, UV_PLATFORMS, normalize -from mlbundle.contract import Library +from mlbundle.contract import MODEL_MEMBERS, Library, ModelKind from mlbundle.lock import runtime_requirements +from mlbundle.manifest import ModelInfo @pytest.fixture @@ -25,6 +26,19 @@ def offline_lock(): """This module exercises the real resolver; the shared fixture replaces it.""" +def model_info(library: Library) -> ModelInfo: + return ModelInfo( + library=library, + serialization=MODEL_MEMBERS[library][0], + estimator_class="Model", + kind=ModelKind.REGRESSOR, + hyperparameters={}, + n_features=1, + n_classes=None, + n_outputs=1, + ) + + class Distribution: def __init__(self, name, version, direct=None): self.metadata = {"Name": name} @@ -64,7 +78,7 @@ def test_installed_distributions(monkeypatch): def test_roots_pick_one_installed_distribution_per_group(): - groups = runtime_requirements(Library.XGBOOST) + groups = runtime_requirements(model_info(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 [ @@ -74,13 +88,6 @@ def test_roots_pick_one_installed_distribution_per_group(): ]: 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(): @@ -91,7 +98,7 @@ def test_runtime_groups_follow_the_package_extras(): assert name is not None extras.setdefault(extra and extra[1], set()).add(normalize(name[0])) for library in Library: - groups = runtime_requirements(library) + groups = runtime_requirements(model_info(library)) assert {group[0] for group in groups} == extras[None] | extras[library.value] @@ -228,7 +235,9 @@ def test_missing_uv(monkeypatch): @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)) + lock = _lock_generation.generate_lock( + runtime_requirements(model_info(Library.SKLEARN)) + ) installed = _lock_generation.installed_distributions() assert lock.python_version == platform.python_version() for name in ("pydantic", "scikit-learn", "skops", "numpy", "scipy"): diff --git a/uv.lock b/uv.lock index 6d4d31a..180a5e9 100644 --- a/uv.lock +++ b/uv.lock @@ -459,7 +459,7 @@ wheels = [ [[package]] name = "mlbundle" -version = "0.3.0" +version = "0.3.1" source = { editable = "." } dependencies = [ { name = "pydantic" },