diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..cad5747 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Canonical lock bytes are LF-only; any CRLF checkout would make them invalid. +playground/src/runtime/pylock.toml text eol=lf diff --git a/AGENTS.md b/AGENTS.md index 8b59b4a..7b0e0b4 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.2.1; format 1 is not frozen. +MLSuite does not train models. The package version is 0.3.0; format 1 is not frozen. Implementation claims require code and test proof. ## What must remain true @@ -36,7 +36,9 @@ Names, categories, learned models and structure can still reveal training inform Support scikit-learn through skops, XGBoost through in-memory UBJSON, CatBoost through CBM and existing ONNX bytes unchanged. Do not convert models. Adapters import their libraries lazily; model dependencies belong in optional -`sklearn`, `xgboost`, `catboost` and `onnx` extras. +`sklearn`, `xgboost`, `catboost` and `onnx` extras. Every bundle's `pylock.toml` +locks those runtimes for Linux and Windows through uv (`lock` extra); it is a claim that +mlbundle validates and never installs. Runtimes own installation policy. ### 5. Inspection and verification mean different things @@ -81,7 +83,7 @@ dead stubs and undocumented fallback behavior. - Tests for a feature keep successful round trips and rejection cases together in one file. - Verification claims describe commands actually run and their real results. - `C:\software\mlsuite`, `C:\software\mlschema`, `C:\software\mlform` and `C:\software\eshkra` are read-only references. Never modify, commit or run write commands in them. -- sklearn-to-ONNX conversion, per-model environments, bundle signing and additional model libraries (including LightGBM and PyTorch) are outside scope. +- sklearn-to-ONNX conversion, provisioning per-model environments (bundles only describe them), bundle signing and additional model libraries (including LightGBM and PyTorch) are outside scope. ## Reader security @@ -107,14 +109,15 @@ changing skops trust, fitted state or supported types. 1. A closed adapter recognizes the model and prepares it without mutating the user's object. 2. Shared extraction derives model claims and structure from native state. 3. Native serialization and reload prove those claims before export publishes the bundle. -4. Local mlschema inference supplies fields/reports; shared code resolves features, targets and environment. +4. Local mlschema inference supplies fields/reports; shared code resolves features, targets, environment and the runtime lock. 5. The writer computes integrity records, validates through the reader and writes a deterministic ZIP. -6. Inspect validates bounded container/JSON data and declarations without adapter resolution. +6. Inspect validates bounded container/JSON/lock data and declarations without adapter resolution. 7. Load uses the closed adapter and compares recomputed claims and structure. 8. The predictor and record APIs expose validated inputs and output-major report results. The allowed members are manifest, required schema, one native member (or a declared -skops + UBJSON/CBM pair), extractable structure and explicit samples: at most six. +skops + UBJSON/CBM pair), extractable structure, explicit samples and the required +lock: at most seven. Publication uses atomic hard links or replacement and requires explicit overwrite. The exclusive-create fallback removes partial destinations on failure but exposes the file during copying. Preserve that behavior and document its limits honestly. @@ -126,6 +129,7 @@ Use the entry points and linked contracts to find the owning implementation: - **Public I/O:** `model_io.py`, `inspection.py`, `results.py` and `cli.py`; `__init__.py` owns public exports. - **Container:** `container.py`, `writing.py`, `_container_rules.py`, `_zip_directory.py`, `_zip_members.py`, `limits.py` and `integrity.py`. - **Declarations:** `manifest.py`, `canonical.py`, `declarations.py`, `environment.py`, `training.py`, `schema.py` and `samples.py`. +- **Runtime lock:** `lock.py`, `_lock_toml.py`, `_wheel_tags.py`, `_lock_generation.py` and `_environment_check.py`; read `docs/format-environment.md` before changing them. - **Adapters:** `adapters.py` and `registry.py` define closed lazy resolution; `_sklearn/`, `_xgboost/`, `_catboost/`, `_onnx/` and `_composite/` own native behavior. - **Claims and predictions:** `claims.py`, `records.py`, `_prediction_input.py`, `_prediction_decisions.py` and `_display.py`. - **Websites:** `landing/`, `docs/` and `playground/`; `brand/` owns the shared identity sourced from eshkra. diff --git a/README.md b/README.md index 7c19263..fce266b 100644 --- a/README.md +++ b/README.md @@ -15,15 +15,16 @@ Website Documentation Playground - Version 0.2.1 + Version 0.3.0 Source on GitHub CI status MIT license Part of eshkra

-MLbundle packages a trained model with its manifest, locally inferred input schema -and extractable structure in one compressed `.mlbundle` file. The same library +MLbundle packages a trained model with its manifest, locally inferred input schema, +extractable structure and a lock of its runtime environment in one compressed +`.mlbundle` file. The same library writes the bundle and validates it when loaded, preserving feature order, class labels and output meaning across the training/runtime boundary. @@ -39,24 +40,27 @@ model they are supposed to describe. MLbundle keeps them together and checks model-derived claims against the loaded model. Schema inference runs locally through [MLschema](https://github.com/UlloaSP/mlschema); real training rows are included only when explicitly requested. Native formats -preserve the supported model without conversion. +preserve the supported model without conversion, and a PEP 751 `pylock.toml` +pins the exact wheels a Linux or Windows runtime needs to serve it. ## Installation -MLbundle **0.2.1** requires Python **3.14** for export with the schema extra. +MLbundle **0.3.0** 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]==0.2.1" +python -m pip install "mlbundle[sklearn,schema,lock]==0.3.0" ``` -To use a local checkout, run `python -m pip install -e ".[sklearn,schema]"` +To use a local checkout, run `python -m pip install -e ".[sklearn,schema,lock]"` from its root. The base library requires Python >=3.14; schema inference uses mlschema `>=0.3.0,<0.4` on Python 3.14 only. Choose `xgboost`, `catboost` or `onnx` instead of `sklearn`, or install `[all]`. -Export always needs `schema`. Metadata-only inspection needs only the base -package; load and CLI verification need the matching model extra. +Export always needs `schema`; `lock` provides uv, which resolves the runtime lock +through your package index unless you pass `environment_lock=`. Metadata-only +inspection needs only the base package; load and CLI verification need the +matching model extra. ## Quick start @@ -116,6 +120,7 @@ accept paths, bytes or streams. The native model remains available as | `bundle.predict(data)` | Regressor predictions as plain lists. | | `bundle.predict_record(record)` | Map one record through the schema and return frozen output-major results. | | `bundle.row_from_record(record)` | Validate and order record values for native inference or explanations. | +| `check_environment(view)` | In the serving process, require exactly the bundle's lock plus mlbundle. | The CLI exposes metadata inspection and full verification: @@ -129,6 +134,18 @@ Inspection does not prove that metadata describes the model. Full verification loads the model and compares its claims. Neither operation establishes authorship 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 +`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 +environment, for example `uv pip install -r pylock.toml`, and calls +`check_environment` before loading. Installing a lock runs its packages' code: +the runtime decides which packages and indexes it trusts. See +[the lock contract](https://docs.mlbundle.eshkra.dev/format/environment/). + ## Supported models | Library | Storage | Support boundary | @@ -147,7 +164,7 @@ 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 require re-export. The security design has not had an +incompatible schema shapes and bundles without `pylock.toml` 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. @@ -156,8 +173,8 @@ still need process isolation and application-owned resource limits. Read [SECURITY.md](https://docs.mlbundle.eshkra.dev/security/) for guarantees, limits and private reporting. Training rows stay local by default, but feature names, categories, labels and -learned structure can reveal information. Schemas and environment records remain -author declarations. Model training, hosting, signing and conversion are outside +learned structure can reveal information. Schemas, environment records and locks +remain author declarations. Model training, hosting, signing and conversion are outside the library's scope. ## Documentation @@ -171,6 +188,7 @@ repository unchanged: - [Supported adapters and structure](https://docs.mlbundle.eshkra.dev/format/adapters/) - [Sklearn state and trusted types](https://docs.mlbundle.eshkra.dev/format/state/) - [Composite pipelines](https://docs.mlbundle.eshkra.dev/format/pipeline/) +- [Runtime environment lock](https://docs.mlbundle.eshkra.dev/format/environment/) - [ONNX layouts and bounds](https://docs.mlbundle.eshkra.dev/format/onnx/) The [playground](https://playground.mlbundle.eshkra.dev) provides editable examples and inspection of the diff --git a/SECURITY.md b/SECURITY.md index f52044a..91fe2ed 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,16 +1,16 @@ # Security policy -MLbundle 0.2.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, -explicit samples, prediction-state verification and the inspect/verify CLI. -The container validates ZIP/ZIP64 layout, bounds sources and actual decompression, -checks CRC and member integrity, and rejects unsafe members and polyglot wrappers. -The writer publishes complete validated files atomically where hard links work; -the exclusive-creation fallback cleans up on failure but exposes the destination -while copying and cannot guarantee crash-atomic publication. The version 1 contract -is defined in [docs/format.md](docs/format.md). +MLbundle 0.3.0 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, +explicit samples, prediction-state verification, the runtime environment lock and +the inspect/verify CLI. The container validates ZIP/ZIP64 layout, bounds sources and +actual decompression, checks CRC and member integrity, and rejects unsafe members +and polyglot wrappers. The writer publishes complete validated files atomically +where hard links work; the exclusive-creation fallback cleans up on failure but +exposes the destination while copying and cannot guarantee crash-atomic publication. +The version 1 contract is defined in [docs/format.md](docs/format.md). ## Threat model @@ -44,7 +44,8 @@ make a received file trustworthy. outside the contiguous ZIP layout. ZIP64 and validated streaming descriptors are accepted within the same resource ceilings. - Verify each member's SHA-256 against the manifest and validate member sizes. -- Validate the manifest strictly and reject unknown format versions. +- Validate the manifest and canonical `pylock.toml` strictly, reject unknown format + versions and never install, import or execute anything a lock names. - Provide a metadata-only `inspect` operation that does not deserialize a model. It must not present model-derived claims as verified against the model. - Treat every model-derived value as a claim. Recompute it from the loaded model @@ -108,10 +109,9 @@ wrapper split transformer skops bytes from UBJSON/CBM, retaining each adapter's preflight, trust, state/claims and structure checks; no booster type enters skops. Closed fitted-state width proofs never use data. Shared bounded names/parameters/ commitments and inner tree coordinates are recomputed before closed Pipeline -reconstruction is returned. Cache/metadata routing/unknown outer state fail; -step names and outer options are declarations, not authenticated training history. -See [the composite contract](docs/format-pipeline.md). -HistGradientBoosting's separate +reconstruction is returned. Cache/metadata routing/unknown outer state fail; step +names and outer options are declarations, not authenticated training history. See +[the composite contract](docs/format-pipeline.md). HistGradientBoosting's separate `TreePredictor` storage is also excluded. Broadening the supplemental list requires source review and hostile-payload tests, never author approval or bundle metadata. @@ -141,20 +141,19 @@ native tree/routing/category/dropout state alongside dumps/importances. Label agreement proves consistency with the native file, not the historical truth of a user-supplied label mapping. -The adapter rejects oversized bytes and non-UBJSON before XGBoost sees them. -A bounded Python preflight checks document layout, feature/class/target counts, -tree counts, node arrays, output groups, iteration pointers, indices, reachability -and dump-compatible depth, keeping -numeric arrays as byte views. Native errors are translated to bounded mlbundle -errors without third-party exception text. These checks reduce cheap malformed -inputs; they are not a complete validation of XGBoost's internal model schema. -XGBoost's native parser and native inference remain a dependency boundary: -mlbundle cannot guarantee their memory safety or bound their internal memory/CPU -use. Native tree dump generation also allocates inside XGBoost before mlbundle -can inspect its returned byte size. Server consumers must isolate loading and -prediction and enforce process resource limits. All predictors reject invalid inputs and wrap remaining native failures -without echoing data cells. See the exact support and -resource boundaries in [docs/format.md](docs/format.md). +The adapter rejects oversized bytes and non-UBJSON before XGBoost sees them. A +bounded Python preflight checks document layout, feature/class/target counts, tree +counts, node arrays, output groups, iteration pointers, indices, reachability and +dump-compatible depth, keeping numeric arrays as byte views. Native errors are +translated to bounded mlbundle errors without third-party exception text. These +checks reduce cheap malformed inputs; they are not a complete validation of +XGBoost's internal model schema. XGBoost's native parser and native inference remain +a dependency boundary: mlbundle cannot guarantee their memory safety or bound their +internal memory/CPU use. Native tree dump generation also allocates inside XGBoost +before mlbundle can inspect its returned byte size. Server consumers must isolate +loading and prediction and enforce process resource limits. All predictors reject +invalid inputs and wrap remaining native failures without echoing data cells. See +the exact support and resource boundaries in [docs/format.md](docs/format.md). ## Implemented CatBoost dependency boundary @@ -231,19 +230,25 @@ boundary: importing mlbundle or inspecting any bundle imports no model library. The native result contains the exact bytes and CPU session needed for inference; mutating a session invalidates its verified relationship with metadata. +## Runtime environment lock + +`pylock.toml` is an author claim that mlbundle validates and never installs. +Installing it executes the named packages' code: runtimes own the allowlist over +the whole locked set, trusted indexes, isolated builds and networkless loading +after `check_environment`, as described in [the lock contract](docs/format-environment.md#consumers). + ## Limits of these guarantees SHA-256 hashes detect corruption, not deliberate tampering: an attacker can replace a member and update its hash in the manifest. They do not prove who trained the model or authenticate its provenance. Bundle signing is out of -scope. Training-environment records and free-form user metadata are assertions -by the author; checking model-derived claims does not authenticate those records. - -Validation does not prove model quality, fairness, training history or the -truth of user metadata. Pickle-free formats do not sandbox model execution or -eliminate vulnerabilities in native parsers and dependencies. A consuming -runtime still owns authentication, authorization, process isolation and -execution resource limits. +scope. Training-environment records, the runtime lock and free-form user metadata +are assertions by the author; checking model-derived claims does not authenticate those records. + +Validation does not prove model quality, fairness, training history or the truth of +user metadata. Pickle-free formats do not sandbox model execution or eliminate +vulnerabilities in native parsers and dependencies. A consuming runtime still owns +authentication, authorization, process isolation and execution resource limits. Training frames are never serialized. Schema inference runs locally and includes column names, dtype strings, inferred kinds, nullability, categorical values diff --git a/docs/format-container.md b/docs/format-container.md index 6a1b05d..c1a9068 100644 --- a/docs/format-container.md +++ b/docs/format-container.md @@ -56,7 +56,7 @@ One MiB is 1,048,576 bytes. `ArchiveLimits` defines these defaults and ceilings: | Limit | Maximum | | --- | ---: | -| Member count, including manifest | 6 (minimum configured value 2) | +| Member count, including manifest | 7 (minimum configured value 2) | | Entire archive, including headers | 512 MiB | | Sum of compressed member sizes | 512 MiB | | Any uncompressed member | 512 MiB | @@ -66,6 +66,7 @@ One MiB is 1,048,576 bytes. `ArchiveLimits` defines these defaults and ceilings: | `structure.json` | 256 MiB | | `schema.json` | 16 MiB | | `samples.json` | 16 MiB | +| `pylock.toml` | 1 MiB | | JSON container nesting depth | 32 | The effective member cap is the smaller of its specific cap and the general @@ -83,8 +84,10 @@ Before manifest parsing, admit one model member or the two candidates `model.skops` + `model.ubj`/`model.cbm`. Other combinations fail. After strict manifest parsing, the declared standalone/composite recipe and actual members must agree exactly; undeclared pairs fail. [Pipeline rules](format-pipeline.md) -own the one-step exception and required structure. Six members accommodate -manifest, two models, structure, schema and explicit samples. +own the one-step exception and required structure. Every bundle also requires +`pylock.toml`; a valid model set without it predates the lock and must be +re-exported. Seven members accommodate manifest, two models, structure, +schema, explicit samples and the lock. ### Container functions and inspection @@ -110,7 +113,7 @@ proves canonical identity; other wire spellings encode the retained value once. There is no global cache or bundle-supplied validation record. Public export reuses the writer's complete container validation when returning metadata. -The writer emits manifest, model, schema, structure, samples in that fixed order, +The writer emits manifest, model, schema, structure, samples, lock in that fixed order, omitting absent members. ZIP timestamps are 1980-01-01 00:00:00, the creating platform is Unix, permissions are regular-file 0600, compression is deflate level 6 with the RLE strategy, memory level 8 and 64 KiB input chunks, and diff --git a/docs/format-environment.md b/docs/format-environment.md new file mode 100644 index 0000000..ebbdb22 --- /dev/null +++ b/docs/format-environment.md @@ -0,0 +1,149 @@ +# Version 1 runtime environment lock + +Normative section of [the format contract](format.md). Version 1 is not frozen. + +Every bundle contains `pylock.toml`, a [PEP 751](https://peps.python.org/pep-0751/) +lock of the distributions its model needs at prediction time, other than mlbundle +itself. The manifest's `writer_version` pins mlbundle: a runtime installs exactly +the lock plus `mlbundle==writer_version`. The lock is an author claim. mlbundle +parses and validates it, but never installs, imports or executes anything it +names; a runtime that installs it executes the named packages' code. + +## Targets + +Locks target CPython with the GIL on three platforms, named as +`sysconfig.get_platform()` reports them: `linux-x86_64` and `linux-aarch64` for +hosts with glibc 2.28 or newer (`manylinux_2_28`), and `win-amd64` (64-bit +Windows on x86). macOS, musl and Windows on ARM are not targets. The Python version is the exact +training version (`environment.python_version`), and the training +implementation must be CPython. Free-threaded wheels (`cp3Nt` ABI tags) never +match a target, and `environment.free_threaded` records only how training ran. +Other targets require a new format revision. + +## Canonical file + +The member is ASCII TOML in exactly the spelling the writer emits; readers +re-encode the parsed lock and require identical bytes. This closes parser +differentials between TOML implementations. The file is: + +```toml +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.7" + +[[packages]] +name = "numpy" +version = "2.5.4" +wheels = [ + { name = "numpy-2.5.4-cp314-...-manylinux_2_28_aarch64.whl", url = "https://.../numpy-2.5.4-cp314-...-manylinux_2_28_aarch64.whl", size = 15342001, hashes = { sha256 = "..." } }, + { name = "numpy-2.5.4-cp314-...-manylinux_2_28_x86_64.whl", url = "https://.../numpy-2.5.4-cp314-...-manylinux_2_28_x86_64.whl", size = 16710432, hashes = { sha256 = "..." } }, + { name = "numpy-2.5.4-cp314-cp314-win_amd64.whl", url = "https://.../numpy-2.5.4-cp314-cp314-win_amd64.whl", size = 12902112, hashes = { sha256 = "..." } }, +] + +[[packages]] +name = "nvidia-nccl-cu13" +version = "2.32.3" +marker = "(sys_platform == 'linux' and platform_machine == 'x86_64') or (sys_platform == 'linux' and platform_machine == 'aarch64')" +wheels = [ ... ] +``` + +Lines end with LF, the file ends with one LF, packages are separated by one +blank line and there are no comments. The only top-level keys are those shown; +each package has `name`, `version`, optional `marker` and `wheels`, in that +order. `marker` appears only for a package locked for some targets: it is that +target's `environments` entry, or for several targets each entry in parentheses, +in target order, joined by ` or `. Each wheel inline table has `name`, +`url`, `size` and `hashes` with only `sha256`, in that order. Index, sdist, VCS, +directory, archive, path, upload-time, extras, dependency groups, attestation +identities and tool tables are rejected. + +## Validation + +The same code validates the lock in the writer, `inspect` and `load`: + +- Packages: 1–512, sorted and unique by PEP 503 normalized name (at most 128 + characters, `[a-z0-9]` runs joined by single hyphens). `mlbundle` is absent. +- Versions: public PEP 440 releases, optional `a`/`b`/`rc`, `.post` and `.dev` + segments, at most 64 characters. Local versions such as `+cpu` are rejected, + as no index serves them. +- Wheels: one to three per package, sorted and unique by filename. A filename + names the package and version. URLs are HTTPS, end with `/` and the filename, + contain no quotes, backslashes, spaces or controls and are at most 2,048 + characters. Sizes are 1–2^40 bytes; digests are lowercase hexadecimal SHA-256. +- Selection: on each of a package's targets, installers' tag order chooses one + wheel: platform wheels before pure ones, then the `cp3N` ABI, `abi3` and + `none`. Linux platform tags are `manylinux_X_Y` up to 2.28 (or the equivalent + `manylinux1`, `manylinux2010`, `manylinux2014` aliases), Windows uses + `win_amd64`, and `any` fits every target. The best + wheel per target must be unique, and every listed wheel must be some target's + choice. A lock therefore determines the exact file each target installs. +- Binding: `requires-python` is `==` plus the manifest's Python version. The + 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. +- 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. + +Validation proves structure and consistency only. Hashes identify files the +author named; they do not show that the packages are safe or that the author +trained with them. + +## Generation + +`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 + 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 + `uv pip compile --python-version --only-binary :all:` and + `--python-platform` `x86_64-manylinux_2_28`, `aarch64-manylinux_2_28` or + `x86_64-pc-windows-msvc`, then keep each package's preferred wheel. Versions + must agree across targets; a package missing from some targets gets a marker. +4. Require every locked distribution installed on the training machine to have + the installed version. Distributions needed only on other targets, such as + NCCL for XGBoost on Linux, take uv's resolution. + +Generation uses the index configured for uv on the training machine and fails +with `LockGenerationError` when a target lacks a wheel, a package publishes only +an sdist or the index is unreachable. There is no fallback to other versions. +`export(environment_lock=...)` instead accepts canonical lock bytes or a path, +such as another bundle's `EnvironmentLock.to_bytes()`; the same fidelity check +applies. Locks fix versions and files, not training binaries: a conda or macOS +build that trained a model can differ from the wheels that serve it. + +## Consumers + +`inspect(path).environment_lock` exposes the validated `EnvironmentLock` without +model libraries: `python_version`, `platforms`, `glibc`, `packages` (name, +version, targets and wheels) and `environment_id`, the SHA-256 of the Python +version and every package's name, version, targets, wheel filenames and digests. +URLs do not change the identity, so a mirror yields the same environment. +`to_bytes()` returns the canonical file for installers such as +`uv pip install -r pylock.toml`. + +Installing a lock runs code from every package in it: import-time code, `.pth` +files and native extensions. mlbundle does not decide which packages, versions or +indexes a runtime trusts. Before installing, a runtime applies its own policy to +the complete package set (for example names, version ranges or reviewed wheel +digests), downloads only from indexes it trusts by name, version and digest, and +installs in an isolated environment separate from the process that loads models. + +`check_environment(bundle)` runs in that loading process. It requires CPython +with the GIL at the lock's Python version on a target platform (glibc 2.28 or +newer on Linux), +and installed distributions equal to the target's locked packages plus mlbundle +at `writer_version`, with nothing else and no duplicate, editable, directory or +VCS installs. It reads distribution metadata only, imports no model library and +raises `EnvironmentMismatchError` with bounded differences. `load` does not run +this check, so a matching environment remains the caller's decision. diff --git a/docs/format-schema.md b/docs/format-schema.md index dae7067..b1a1339 100644 --- a/docs/format-schema.md +++ b/docs/format-schema.md @@ -102,7 +102,8 @@ a top-level ordinary label must equal the feature name at that index. In 0.2.0 the `series` shape changed from `field1`/`field2` to MLForm's `columns` while format 1 is not frozen. Schema version stays `"2"`: no bundle written before this change contains a series field, so a version bump would -invalidate every 0.1.0a2 bundle for a shape none uses. Readers reject the old shape. +have invalidated every 0.1.0a2 bundle for a shape none used. Readers reject the old shape. +Since 0.3.0, bundles without `pylock.toml` require re-export regardless. MLschema emits this shape directly. Parent `label`, `required` and `mappedTo` remain unchanged: diff --git a/docs/format-state.md b/docs/format-state.md index 3675dca..857dff7 100644 --- a/docs/format-state.md +++ b/docs/format-state.md @@ -24,10 +24,12 @@ There is no version whitelist. Other versions can introduce unknown classes or state fields and fail export/load. `_sklearn_version` also participates in the commitment: a different installed sklearn version changes reserialized state, so loading may reject it as `InvalidModelError`. After a sklearn/skops -`InvalidModelError`, safe differing declared/installed versions produce -`EnvironmentMismatchError` +`InvalidModelError`, a differing installed version and the scikit-learn version +declared by the bundle's validated lock produce `EnvironmentMismatchError` with both versions and re-export/load guidance. Declarations must match a strict version pattern of at most 64 characters; otherwise the original error remains. +The lock records the exact versions to install: see +[the runtime environment lock](format-environment.md) and `check_environment`. Successful loads remain successful: this is diagnosis, not a compatibility gate. It also covers a composite's skops prefix, without relabeling native leaf failures. Export and load should use diff --git a/docs/format.md b/docs/format.md index 0bd99bc..46c8305 100644 --- a/docs/format.md +++ b/docs/format.md @@ -5,7 +5,7 @@ This document defines the wire contract for `format_name = "mlbundle"` and "Must" denotes a compatibility or security requirement. This contract is implemented by the manifest, secure container, inspect/export/load, sklearn/XGBoost/CatBoost/ONNX adapters, local schema, samples and prediction-state checks. -Version 1 is not frozen. MLbundle 0.2.0 requires schema v2; incompatible manifest/schema shapes require re-export. Valid 0.1.0a2 bundles without series remain compatible. The inspect/verify CLI uses these public APIs. +Version 1 is not frozen. MLbundle 0.2.0 requires schema v2 and 0.3.0 requires `pylock.toml`; incompatible manifest/schema shapes and bundles without a lock require re-export. The inspect/verify CLI uses these public APIs. The normative container rules are in [Container and resource limits](format-container.md). The normative structure, adapter and result rules are in [Adapters and structure](format-adapters.md). @@ -13,7 +13,7 @@ The implemented ONNX mapping and validation rules are in [ONNX](format-onnx.md). The implemented CBM mapping and validation rules are in [CatBoost](format-catboost.md). The normative schema/declaration rules are in [Schema and samples](format-schema.md). [Prediction state and bounded work](format-state.md) is also normative. -[Composite pipelines](format-pipeline.md) is normative for the split representation. +[Composite pipelines](format-pipeline.md) (the split representation) and [Runtime environment lock](format-environment.md) are normative too. ## Members @@ -27,6 +27,7 @@ The normative schema/declaration rules are in [Schema and samples](format-schema | `schema.json` | Required; exact object with `schema_version: "2"`, `source`, `onehot_separator`, `fields` and `reports` from local/default inference. See [Schema and samples](format-schema.md). No training DataFrame. | | `structure.json` | Optional only for families without extractable structure; object as defined below. | | `samples.json` | Optional; array of row objects keyed by feature name, in declared feature order when consumed. Only explicit user intent may enable it. Values use the canonical JSON value rules. Samples are real user data. | +| `pylock.toml` | Required; canonical PEP 751 lock of the model's runtime distributions except mlbundle, for CPython with the GIL on Linux `x86_64`/`aarch64` and Windows `amd64`. See [Runtime environment lock](format-environment.md). | Model members are one standalone member, or the declared skops/UBJSON or skops/CBM composite pair; single-step composites use only the leaf. See [pipelines](format-pipeline.md). @@ -62,7 +63,7 @@ Optional fields can be omitted/null; writers emit defaults. `user_metadata` defa | `format_version` | literal string `"1"` | Wire version; unknown strings raise `UnsupportedFormatVersionError`. Wrong types are invalid manifests. | | `bundle_id` | UUID string | Author-assigned bundle identity; writers use lowercase, hyphenated UUIDs. Readers accept UUID spellings supported by UUID parsing and normalize on output. | | `created_at` | ISO 8601 UTC timestamp string | Creation declaration, spelled `YYYY-MM-DDTHH:MM:SS[.ffffff]Z` or with `+00:00` instead of `Z`; fractions have 1–6 digits. Writers emit `Z`. Reject epoch strings/numbers, naive timestamps, nonzero offsets and extra fractional precision. | -| `writer_version` | nonempty string, at most 256 characters | mlbundle package version that wrote the bundle. Must equal `environment.packages.mlbundle`. | +| `writer_version` | nonempty string, at most 256 characters | mlbundle package version that wrote the bundle. The lock omits mlbundle; runtimes install this version with it. | Identity fields are declarations, not proof of provenance. ### `model` @@ -178,20 +179,18 @@ See [ONNX kind and labels](format-onnx.md#kind-and-labels). | Field | Type | Meaning / verification | | --- | --- | --- | -| `python_version` | nonempty string, max 256 | Training Python version. | -| `python_implementation` | nonempty string, max 256 | Implementation, e.g. `CPython`. | +| `python_version` | nonempty string, max 256 | Training Python version; the lock's `requires-python` must be `==` this version. | +| `python_implementation` | nonempty string, max 256 | Implementation; the lock requires `CPython`. | +| `free_threaded` | boolean | Whether training ran on a free-threaded build. Locks always target the GIL build. | | `os` | nonempty string, max 256 | OS name. | | `os_version` | nonempty string, max 256 | OS release. | | `architecture` | nonempty string, max 256 | Machine architecture, e.g. `AMD64`. | -| `packages` | object with only the keys listed below | Installed distribution versions, nonempty strings max 256. Uninstalled distributions are omitted. | | `onnx` | optional ONNX record | Required for ONNX, null/absent otherwise; verified from the graph. | -Allowed package keys are `mlbundle`, `mlschema`, `numpy`, `pandas`, `scipy`, -`scikit-learn`, `xgboost`, `catboost`, `onnx`, `onnxruntime` and `skops` (maximum eleven). -Capture versions using distribution metadata, without importing the libraries. -`mlbundle` is required by the writer-version consistency rule. Other environment -fields are unverifiable declarations about the training machine, including the -ONNX/ONNX Runtime package versions; they are not evidence of compatibility. +Package versions are not manifest fields: `pylock.toml` records the model's +runtime distributions. Environment fields and the lock are unverifiable +declarations about the training machine, including ONNX Runtime versions; +they are not evidence of compatibility. The ONNX record contains required fields: `opsets` (1–128 objects with `domain`, a string of 0–256 characters, and `version`, an integer 1–2^31−1), `ir_version` @@ -205,11 +204,11 @@ file, not who produced or trained it. `integrity` is an object mapping **every other present member** to exactly `{"sha256":HEX,"size":BYTES}`. The digest is 64 lowercase hexadecimal characters; size is an integer 0–512 MiB, further bounded by the specific member cap. -It has 2–5 keys: exactly the selected model member(s), schema and referenced optional members. +It has 3–6 keys: exactly the selected model member(s), schema, lock and referenced optional members. There is no manifest hash, since the manifest cannot contain its own digest. Declared sizes must equal both actual uncompressed sizes and ZIP metadata. -`references` requires `schema: "schema.json"`; optional `structure` and `samples` +`references` requires `schema: "schema.json"` and `lock: "pylock.toml"`; optional `structure` and `samples` are null/absent or respectively `"structure.json"`, `"samples.json"`. There are no URLs or arbitrary paths. @@ -274,7 +273,7 @@ metadata and the optional fitted-state commitment. Classifier extraction may lea carries none; the shared pipeline resolves the declaration as specified above. Library/serialization/member pairing is validated by the closed registry. Structure is compared separately using the same canonical encoding. -Schema, training dtypes, frame/declared-origin names, target names, training environment, +Schema, training dtypes, frame/declared-origin names, target names, training environment, lock, user metadata, identity and samples are not verified against the model; they must still pass their own validation and integrity checks. Inspection verifies format and integrity only, and must never attest that model claims match the model. @@ -287,11 +286,12 @@ encoding or mandatory structure shapes requires a new format version and an explicit reader implementation. Before freeze, incompatible v1 revisions require re-export. Tightening caller-selected resource limits does not change the format. Corrections to documentation that preserve wire behavior and implementation changes behind these contracts do not require a version bump. -The unfrozen version 1 includes required schema v2, positional mappings, `declared` origin, +The unfrozen version 1 includes the required runtime lock, required schema v2, positional mappings, `declared` origin, prediction-state records, missing tree routing, native XGBoost routing/dropout and closed state/work rules, scalar dtype/type/function records and composition -references. It remains subject to change before format freeze; schema v1/absent schemas and older sklearn -pipeline parameter projections require re-export under this revised v1 contract. +references. It remains subject to change before format freeze; schema v1/absent schemas, absent locks, +`environment.packages` and older sklearn pipeline parameter projections require +re-export under this revised v1 contract. Hashes detect corruption, not deliberate tampering: an attacker can replace a model and update every record. Claim recomputation prevents a bundle from showing diff --git a/docs/publishing.md b/docs/publishing.md index 5c8ad6c..23f64e2 100644 --- a/docs/publishing.md +++ b/docs/publishing.md @@ -1,10 +1,10 @@ # Publishing to PyPI -Version `0.2.1` is prepared by this checkout. Merging a version change into +Version `0.3.0` 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. Valid a2 bundles remain compatible, as documented in -[the schema contract](format-schema.md). The security design has not had an +shapes require re-export; 0.3.0 requires every bundle to carry `pylock.toml`, as +documented in [the environment lock contract](format-environment.md). The security design has not had an independent review; do not accept bundles from untrusted parties. ## Release flow @@ -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]==0.2.1"` on + Install with `python -m pip install "mlbundle[sklearn,schema,lock]==0.3.0"` 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/adapters/catboost.md b/docs/src/content/docs/adapters/catboost.md index 49bf4a8..93a5753 100644 --- a/docs/src/content/docs/adapters/catboost.md +++ b/docs/src/content/docs/adapters/catboost.md @@ -3,7 +3,7 @@ title: CatBoost description: Bundle numeric, single-target symmetric CatBoost models as native CBM with complete, verified tree structure. --- -Install `mlbundle[catboost,schema]` (CatBoost 1.2.10 or newer; it brings matplotlib and plotly). +Install `mlbundle[catboost,schema,lock]` (CatBoost 1.2.10 or newer; it brings matplotlib and plotly). Models are stored as native CBM and loaded in memory. ```python diff --git a/docs/src/content/docs/adapters/onnx.md b/docs/src/content/docs/adapters/onnx.md index c442c19..f746950 100644 --- a/docs/src/content/docs/adapters/onnx.md +++ b/docs/src/content/docs/adapters/onnx.md @@ -3,7 +3,7 @@ title: ONNX description: Bundle an existing self-contained tabular ONNX file unchanged, with verified signatures, labels and a CPU session on load. --- -Install `mlbundle[onnx,schema]`. mlbundle does not convert models to ONNX. It bundles an ONNX file +Install `mlbundle[onnx,schema,lock]`. mlbundle does not convert models to ONNX. It bundles an ONNX file you already have, byte for byte, after validating that it is a self-contained tabular model. This example assumes `trained.onnx` is a classifier with two numeric features and two probability diff --git a/docs/src/content/docs/adapters/overview.md b/docs/src/content/docs/adapters/overview.md index 8c9d80b..f761343 100644 --- a/docs/src/content/docs/adapters/overview.md +++ b/docs/src/content/docs/adapters/overview.md @@ -31,7 +31,7 @@ mlbundle does not support: - other libraries, including LightGBM and PyTorch; - converting scikit-learn models to ONNX, or any other format conversion; -- per-model environments and bundle signing; +- provisioning per-model environments (bundles describe them in `pylock.toml`) and bundle signing; - pickle, joblib or cloudpickle, even as an option. The normative mappings are in [Adapters and structure](/format/adapters/), diff --git a/docs/src/content/docs/adapters/pipelines.md b/docs/src/content/docs/adapters/pipelines.md index 3140d73..f480bea 100644 --- a/docs/src/content/docs/adapters/pipelines.md +++ b/docs/src/content/docs/adapters/pipelines.md @@ -6,7 +6,7 @@ description: Bundle a fitted scikit-learn Pipeline that ends in XGBoost or CatBo A fitted `sklearn.pipeline.Pipeline` whose final step is an exact XGBoost or CatBoost wrapper is exported as it is. The transformer prefix is stored with skops, the final estimator with its native adapter, and load rebuilds a real `Pipeline` after verifying both parts. Install -`mlbundle[sklearn,xgboost,schema]` or `mlbundle[sklearn,catboost,schema]`. +`mlbundle[sklearn,xgboost,schema,lock]` or `mlbundle[sklearn,catboost,schema,lock]`. ```python from sklearn.pipeline import make_pipeline @@ -24,7 +24,7 @@ bundle = load("pipeline.mlbundle") assert bundle.predict_proba(rows) == model.predict_proba(rows).tolist() assert bundle.native_model.predict(rows).tolist() == model.predict(rows).tolist() print([member.value for member in bundle.members]) -# ['manifest.json', 'model.skops', 'model.ubj', 'schema.json', 'structure.json'] +# ['manifest.json', 'model.skops', 'model.ubj', 'schema.json', 'structure.json', 'pylock.toml'] ``` ## How it is stored @@ -47,7 +47,8 @@ they use one skops member and have no structure. - Manifest features, schema, training dtypes and samples describe the **original inputs**. - Trees address the **transformed features**, without attribution back to the original columns. `mlbundle inspect` prints the boundary's width and names. -- Six members are enough for manifest, prefix, leaf, structure, schema and explicit samples. +- Seven members are enough for manifest, prefix, leaf, structure, schema, explicit samples and the + lock, which pins both the sklearn prefix's and the leaf library's runtimes. ## Supported prefixes diff --git a/docs/src/content/docs/adapters/sklearn.md b/docs/src/content/docs/adapters/sklearn.md index 44cf8f6..dc46b44 100644 --- a/docs/src/content/docs/adapters/sklearn.md +++ b/docs/src/content/docs/adapters/sklearn.md @@ -3,7 +3,7 @@ title: scikit-learn description: Which scikit-learn estimators and transformers mlbundle can bundle with skops, what structure they carry and what is rejected. --- -Install `mlbundle[sklearn,schema]`. Models are stored with `skops.io.dumps` and loaded with +Install `mlbundle[sklearn,schema,lock]`. Models are stored with `skops.io.dumps` and loaded with `skops.io.loads` against a trusted-types allowlist that lives inside mlbundle. The allowlist is never read from a bundle, and you cannot extend it. diff --git a/docs/src/content/docs/adapters/xgboost.md b/docs/src/content/docs/adapters/xgboost.md index 81ed4ab..ebf48cd 100644 --- a/docs/src/content/docs/adapters/xgboost.md +++ b/docs/src/content/docs/adapters/xgboost.md @@ -3,9 +3,13 @@ title: XGBoost description: Bundle XGBClassifier and XGBRegressor as native UBJSON, bind original class labels and know which settings survive. --- -Install `mlbundle[xgboost,schema]`. Models are stored as native in-memory UBJSON and loaded with +Install `mlbundle[xgboost,schema,lock]`. Models are stored as native in-memory UBJSON and loaded with `load_model`, never pickled. +On Linux, the `xgboost` distribution depends on NVIDIA NCCL, about 300 MB per architecture, so a +bundle's runtime lock includes it. Training with the CPU-only `xgboost-cpu` distribution locks that +distribution instead. + ```python from xgboost import XGBClassifier diff --git a/docs/src/content/docs/getting-started/installation.md b/docs/src/content/docs/getting-started/installation.md index 854a464..1188fcf 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.2.1 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.0 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.2.1. +These pages document mlbundle 0.3.0. ```bash -python -m pip install "mlbundle[sklearn,schema]==0.2.1" +python -m pip install "mlbundle[sklearn,schema,lock]==0.3.0" ``` Replace `sklearn` with the extra for your model library; the extras are listed @@ -17,20 +17,20 @@ Replace `sklearn` with the extra for your model library; the extras are listed ## From a local checkout -To work from source, or before 0.2.1 is available from your package index, install a checkout of +To work from source, or before 0.3.0 is available from your package index, install a checkout of the repository: ```bash git clone https://github.com/UlloaSP/mlbundle.git cd mlbundle -python -m pip install ".[sklearn,schema]" +python -m pip install ".[sklearn,schema,lock]" ``` Inside a uv project, add the checkout as a path dependency instead (adjust the path to where you cloned it): ```bash -uv add ../mlbundle --extra sklearn --extra schema +uv add ../mlbundle --extra sklearn --extra schema --extra lock ``` ## Choose the extras @@ -42,14 +42,17 @@ uv add ../mlbundle --extra sklearn --extra schema | `catboost` | `catboost>=1.2.10` | CatBoost classifiers and regressors. CatBoost brings matplotlib and plotly. | | `onnx` | `onnx>=1.23.0`, `onnxruntime>=1.30.0` | Existing ONNX files. | | `schema` | `mlschema>=0.3.0,<0.4` on Python 3.14 only | **Every export.** Also installs pandas. | +| `lock` | `uv>=0.13.5` | **Every export** that generates its runtime lock; not needed with `environment_lock=`. | | `all` | All of the above | Development and mixed workloads. | Pick by what each machine does: -- **Training machine:** the model extra plus `schema`, for example `mlbundle[xgboost,schema]`. - Export always infers a schema, even without training data. +- **Training machine:** the model extra plus `schema` and `lock`, for example + `mlbundle[xgboost,schema,lock]`. Export always infers a schema, even without training data, and + resolves `pylock.toml` through your package index. - **Serving or verifying machine:** only the matching model extra, for example `mlbundle[xgboost]`. - Loading validates the schema without pandas or mlschema. + Loading validates the schema without pandas or mlschema. A runtime that serves bundles installs + each bundle's `pylock.toml` plus mlbundle at its `writer_version` instead. - **Metadata only:** no extra. `inspect` and `mlbundle inspect` never import a model library. Composite pipelines need both parts: `[sklearn,xgboost]` or `[sklearn,catboost]`. @@ -66,7 +69,7 @@ from importlib.metadata import version import mlbundle -print(version("mlbundle")) # 0.2.1 +print(version("mlbundle")) # 0.3.0 print(mlbundle.FORMAT_NAME, mlbundle.FORMAT_VERSION) # mlbundle 1 ``` @@ -81,7 +84,10 @@ mlbundle --help | Symptom | Cause | Resolution | | --- | --- | --- | | `MissingOptionalDependencyError` naming `schema` | Export runs without pandas or mlschema. | Install `mlbundle[schema]` on Python 3.14. | +| `MissingOptionalDependencyError` naming `lock` | Export cannot find uv to generate the lock. | Install `mlbundle[lock]`, or pass `environment_lock=`. | +| `LockGenerationError` | uv found no single wheel for a Linux or Windows target, only an sdist, or could not reach the index. | Install versions with wheels for every target, check index access, or pass a lock generated elsewhere. | +| `InvalidEnvironmentLockError` on export | A supplied lock disagrees with the installed versions or Python. | Use a lock generated from this environment. | | `MissingOptionalDependencyError` naming a library | Load or `verify` needs the model's extra. | Install the extra named in the message. | | `mlbundle: missing optional dependency; install mlbundle[xgboost].` | Same, from the CLI. | Install that extra; `inspect` works without it. | -| `EnvironmentMismatchError` on load | A skops load failed and the bundle was written with a different scikit-learn version. | Match the training scikit-learn version. | +| `EnvironmentMismatchError` on load | A skops load failed and the bundle locks a different scikit-learn version. | Install the bundle's `pylock.toml`. | | `No matching distribution found` | Python is older than 3.14. | Check `python --version`. | diff --git a/docs/src/content/docs/getting-started/quick-start.md b/docs/src/content/docs/getting-started/quick-start.md index f407d63..34af039 100644 --- a/docs/src/content/docs/getting-started/quick-start.md +++ b/docs/src/content/docs/getting-started/quick-start.md @@ -3,7 +3,7 @@ title: Quick start description: Export a scikit-learn classifier to a .mlbundle file, inspect its metadata, load the verified model and predict. --- -This walkthrough uses scikit-learn. Install `mlbundle[sklearn,schema]` on Python 3.14 as described +This walkthrough uses scikit-learn. Install `mlbundle[sklearn,schema,lock]` on Python 3.14 as described in [Installation](/getting-started/installation/). ## 1. Export on the training machine @@ -18,12 +18,13 @@ model = DecisionTreeClassifier(random_state=7).fit(rows, ["cold", "warm"] * 2) view = export(model, "trained.mlbundle", feature_names=["temperature", "humidity"]) print([member.value for member in view.members]) -# ['manifest.json', 'model.skops', 'schema.json', 'structure.json'] +# ['manifest.json', 'model.skops', 'schema.json', 'structure.json', 'pylock.toml'] ``` `export` serializes the model with skops, loads it back, recomputes its claims and structure, and -only then publishes the file. A model with types outside mlbundle's allowlist fails here, on the -training machine, not after upload. An existing destination needs `overwrite=True`. +only then publishes the file. It also locks the installed scikit-learn runtime as `pylock.toml` for +Linux and Windows serving, through uv and your package index. A model with types outside mlbundle's allowlist +fails here, on the training machine, not after upload. An existing destination needs `overwrite=True`. The model was fitted on plain lists, so it has no native feature names: the names you pass are recorded as `declared`. No training data was given, so the schema comes from one synthetic row. @@ -41,7 +42,7 @@ print(view.manifest.features.names, view.manifest.features.origin) print(view.schema["reports"][0]["labels"]) # ['cold', 'warm'] ``` -`inspect` validates the archive, the manifest, every non-manifest member's hash and the schema, without importing +`inspect` validates the archive, the manifest, every non-manifest member's hash, the lock and the schema, without importing scikit-learn or deserializing anything. It therefore **cannot** tell you whether the metadata describes the model. The command line does the same: diff --git a/docs/src/content/docs/guides/cli.md b/docs/src/content/docs/guides/cli.md index 89d7bbe..368ddc2 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.2.1" +Writer: "0.3.0" Model: sklearn "DecisionTreeClassifier" (classifier) Counts: features=2, outputs=1, classes=[2] Features (declared): ["temperature", "humidity"] @@ -33,8 +33,11 @@ Members: model.skops: 13065 bytes sha256=24d7cbab1d775ab279dc8ebc3c762b551b397ebf9b4917ac3c4474ff611b8813 schema.json: 361 bytes sha256=ea62a6a7502ae8ea30b45b61bb18d8e31bd2ec55f026d9fbf0c05ef42d01ff25 structure.json: 526 bytes sha256=66204da26781a4e2a800a1f3ed246ab1a43e8c97ced73d06a2640f897eeda03c -Training: {"python": "3.14.7", "implementation": "CPython", "os": "Windows", "os_version": "11", "architecture": "AMD64"} -Packages: {"catboost": "1.2.10", "mlbundle": "0.2.1", "mlschema": "0.3.0", ...} + 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 id: b8a31c89e5ed683e2f214cc486b83dc49e5292175c57606b11b515d494e81b57 +Locked packages: {"annotated-types": "0.8.0", "cloudpickle": "3.1.2", "joblib": "1.6.0", "narwhals": "2.27.1", ...} ONNX environment: null Present: schema=yes, structure=yes, samples=no User metadata: {} diff --git a/docs/src/content/docs/guides/export.md b/docs/src/content/docs/guides/export.md index 47682e8..a3fcf55 100644 --- a/docs/src/content/docs/guides/export.md +++ b/docs/src/content/docs/guides/export.md @@ -18,12 +18,14 @@ 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 ``` -Export always needs the `schema` extra, even without `training_data`. +Export always needs the `schema` extra, even without `training_data`, and the `lock` extra unless +you pass `environment_lock=`. ## Arguments @@ -38,6 +40,7 @@ Export always needs the `schema` extra, even without `training_data`. | `sample_rows` | Positive integer: include the first N feature rows as `samples.json`. Requires a frame. See [samples](/guides/schema-and-samples/#explicit-samples). | | `onehot_separator` | Separator for one-hot groups, 1–16 characters, stored in the schema. | | `metadata` | Free JSON object recorded as `user_metadata`. | +| `environment_lock` | Canonical `pylock.toml` bytes or a path to use instead of generating one, such as another bundle's `environment_lock.to_bytes()`. See [the runtime lock](#the-runtime-lock). | | `overwrite` | Replace an existing destination. Without it, an existing file raises `FileExistsError`. | | `limits` | Lower [`ArchiveLimits`](/reference/limits/) for this bundle. Ceilings cannot be raised. | @@ -100,13 +103,13 @@ and with a training frame tells mlbundle which columns to exclude from inference - model: library, class, kind, hyperparameters, feature/output/class counts and serialization; - features: ordered names, origin, training dtypes and verified model dtypes; - target: output-major class labels and target names; -- environment: Python version and implementation, OS and version, architecture and installed - package versions; +- environment: Python version, implementation and free-threading, OS and version, and + architecture; - integrity: the SHA-256 and size of every other member; - `user_metadata`: your `metadata=`, at most 1,024 top-level keys, 64 KiB and depth 8. Model-derived values, including model-exposed `model_dtypes`, are claims that `load` recomputes. -The environment, training `dtypes` and user metadata are declarations: recorded, never authenticated. The exact fields are in the +The environment, the lock, training `dtypes` and user metadata are declarations: recorded, never authenticated. The exact fields are in the [format 1 manifest](/format/#manifest). ```python @@ -120,6 +123,30 @@ view = export( 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` +(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 +distribution to its installed version and asks uv for one wheel per package and target. Every +locked package installed on the training machine must keep its installed version; packages needed +on other targets, such as NCCL for XGBoost on Linux, come from uv's resolution. Export therefore needs uv (the +`lock` extra) and access to the package index uv is configured to use. + +```python +view = export(model, "locked.mlbundle", training_data=frame, overwrite=True) +lock = view.environment_lock +print(lock.python_version, lock.version("scikit-learn")) +print(lock.environment_id) # SHA-256 identity of Python and every wheel +``` + +Offline machines, or machines whose interpreter cannot run uv, can pass a lock generated for the same +installed versions elsewhere: `export(..., environment_lock="pylock.toml")`. The lock fixes versions +and wheel files, not the binaries that trained the model. The rules are in +[the lock contract](/format/environment/). + ## Publication The writer builds a deterministic ZIP in memory, validates it with the reader, then publishes it @@ -137,7 +164,9 @@ failed copy is removed but was briefly visible): | `UnsupportedModelError` | The model class, objective, layout or a contained type is outside the adapter's closed boundary. For scikit-learn the message lists the untrusted types. | | `InvalidSchemaError` | Frame columns do not match native names, a target column is missing, or report labels collide. | | `InvalidSamplesError` | `sample_rows` is zero, too large, not an integer, or a cell cannot be converted. | -| `MissingOptionalDependencyError` | The `schema` extra or the model's extra is not installed. | +| `MissingOptionalDependencyError` | The `schema` or `lock` extra, or the model's extra, is not installed. | +| `LockGenerationError` | uv found no single wheel for a target and locked version, only an sdist, or could not reach the index. | +| `InvalidEnvironmentLockError` | A supplied lock is not canonical or disagrees with the installed versions or Python. | | `LimitExceededError` | A member or the archive exceeds the selected limits. | | `FileExistsError` | The destination exists and `overwrite` is false. | diff --git a/docs/src/content/docs/guides/inspect-and-load.md b/docs/src/content/docs/guides/inspect-and-load.md index 0d7d53c..2bb54aa 100644 --- a/docs/src/content/docs/guides/inspect-and-load.md +++ b/docs/src/content/docs/guides/inspect-and-load.md @@ -11,6 +11,7 @@ mlbundle has two readers with different guarantees. Choose by what you need to t | Strict manifest and format version | Validated | Validated | | SHA-256 and size of every non-manifest member | Verified | Verified | | Schema and samples against manifest claims | Validated | Validated | +| `pylock.toml` canonical form and manifest binding | Validated | Validated | | Imports a model library | **Never** | The matching adapter only | | Deserializes the model | **Never** | Through the closed adapter | | Hyperparameters, counts, labels, dtypes, structure | Read as claims | **Recomputed and compared** | @@ -27,15 +28,15 @@ from mlbundle import inspect view = inspect("trained.mlbundle") manifest = view.manifest -print(manifest.format_version, manifest.writer_version) # 1 0.2.1 +print(manifest.format_version, manifest.writer_version) # 1 0.3.0 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'] +# ['manifest.json', 'model.skops', 'schema.json', 'structure.json', 'pylock.toml'] print(view.samples) # None ``` -`MetadataView` has `manifest`, `members`, `schema` and `samples`. Use it to list, index or review -bundles on a machine without model libraries. +`MetadataView` has `manifest`, `members`, `environment_lock`, `schema` and `samples`. Use it to +list, index or review bundles on a machine without model libraries. :::caution[Inspection does not verify the model] A bundle's author can write any manifest and recompute its hashes. `inspect` checks that the file is @@ -72,7 +73,7 @@ print(bundle.structure["family"]) # decision_tree | Member | Contents | | --- | --- | -| `manifest`, `members`, `schema`, `samples` | As in `MetadataView`, validated. | +| `manifest`, `members`, `environment_lock`, `schema`, `samples` | As in `MetadataView`, validated. | | `structure` | Decoded `structure.json`, or `None` for families without extractable structure. | | `native_model` | The native object: estimator, `Pipeline`, XGBoost or CatBoost wrapper, or an ONNX model holding `data` and `session`. | | `kind`, `library`, `class_name` | From the verified manifest. | @@ -94,16 +95,39 @@ required whenever the adapter can extract it and is compared on load, so a revie tree that differs from the model used for prediction. All-scikit-learn pipelines and ONNX have `None`. The families and fields are in [Adapters and structure](/format/adapters/#structurejson). +## Serve in the locked environment + +`environment_lock` is the validated `pylock.toml`: Python version, targets, packages with their +wheels, and an `environment_id` that ignores download URLs. A runtime builds one environment per +lock, installing the lock plus mlbundle at `writer_version`, then calls `check_environment` in the +process that loads the model: + +```python +from mlbundle import check_environment, inspect, load + +view = inspect("trained.mlbundle") +open("pylock.toml", "wb").write(view.environment_lock.to_bytes()) +# Elsewhere, in an isolated build step: uv pip install -r pylock.toml mlbundle== +check_environment(view) # EnvironmentMismatchError unless this interpreter matches +bundle = load("trained.mlbundle") +``` + +`check_environment` requires CPython with the GIL at the locked Python version on Linux `x86_64` or +`aarch64` (glibc 2.28 or newer) or Windows `amd64`, and exactly that target's locked distributions +plus mlbundle. `load` does not +call it. Installing a lock runs its packages' code, so the runtime applies its own allowlist and +trusted indexes first; see [the lock contract](/format/environment/#consumers). + ## Version diagnostics Some failures add a hint without adding a compatibility gate: -- `EnvironmentMismatchError` when a skops load fails and the bundle declares a different +- `EnvironmentMismatchError` when a skops load fails and the bundle's lock declares a different scikit-learn version than the one installed; - `InvalidManifestError` mentioning a different writer version when a manifest fails validation. -Format 1 is not frozen; incompatible changes may require re-export. Bundles written by 0.1.0a1, or -with schema version 1, must be re-exported. +Format 1 is not frozen; incompatible changes may require re-export. Bundles without `pylock.toml` +(written before 0.3.0), or with schema version 1, must be re-exported. ## Treat every bundle as untrusted diff --git a/docs/src/content/docs/guides/schema-and-samples.md b/docs/src/content/docs/guides/schema-and-samples.md index 577a816..5fb93c6 100644 --- a/docs/src/content/docs/guides/schema-and-samples.md +++ b/docs/src/content/docs/guides/schema-and-samples.md @@ -152,7 +152,8 @@ exactly once, mappings match the feature origin, and reports match the manifest' `load` additionally verifies those labels against the model. The schema's `source`, separator and nullability remain declarations; nothing can attest how the training data looked. -Bundles written by 0.1.0a1 without a schema, or with schema version `1`, must be re-exported. +Bundles written by 0.1.0a1 without a schema, with schema version `1` or, since 0.3.0, without +`pylock.toml` must be re-exported. The full rules, including series fields and cell conversions, are in [Schema and samples](/format/schema/). diff --git a/docs/src/content/docs/guides/trust.md b/docs/src/content/docs/guides/trust.md index 1418fcd..5309485 100644 --- a/docs/src/content/docs/guides/trust.md +++ b/docs/src/content/docs/guides/trust.md @@ -32,6 +32,7 @@ These checks need no model library: duplicates, encryption or bytes outside the archive layout; - member count, sizes, compression ratio and JSON depth within [limits](/reference/limits/); - a strict manifest with exact types and a known format version; +- a canonical `pylock.toml` whose targets, wheel choices and Python agree with the manifest; - SHA-256 and size of every member except the manifest, which cannot contain its own hash; - schema coverage, mappings by feature origin and report shape; sample keys. @@ -39,7 +40,7 @@ These checks need no model library: | Declaration | Why it cannot be checked | | --- | --- | -| Training environment and package versions | Recorded by the writer; any author can edit them. | +| Training environment and the runtime lock | Recorded by the writer; any author can edit them. Installing a lock runs its packages' code. | | Training dtypes | Describe a frame that is not in the bundle. | | Schema `source`, separator and nullability | Inference history is not reproducible from the bundle. | | Declared or frame feature names | Labels for a model without native names; count and alignment are checked. | diff --git a/docs/src/content/docs/index.md b/docs/src/content/docs/index.md index 0c7cc20..2f6c071 100644 --- a/docs/src/content/docs/index.md +++ b/docs/src/content/docs/index.md @@ -4,7 +4,7 @@ description: Package a trained model, its manifest, a locally inferred schema an tableOfContents: false hero: title: One verifiable file for a trained model. - tagline: mlbundle puts the model in its native format, a manifest of model and training-environment metadata, a locally inferred input schema and the model's structure into one .mlbundle file. Before it hands you the model, the reader recomputes every model-derived claim and rejects disagreement. + tagline: mlbundle puts the model in its native format, a manifest of model and training-environment metadata, a locally inferred input schema, the model's structure and a lock of its runtime into one .mlbundle file. Before it hands you the model, the reader recomputes every model-derived claim and rejects disagreement. actions: - text: Quick start link: /getting-started/quick-start/ diff --git a/docs/src/content/docs/reference/api.md b/docs/src/content/docs/reference/api.md index c46d611..0dbc232 100644 --- a/docs/src/content/docs/reference/api.md +++ b/docs/src/content/docs/reference/api.md @@ -11,10 +11,12 @@ from mlbundle import ( FORMAT_NAME, # "mlbundle" FORMAT_VERSION, # "1" ArchiveLimits, + EnvironmentLock, LoadedBundle, Manifest, MetadataView, OutputPrediction, + check_environment, export, inspect, load, @@ -39,13 +41,15 @@ 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 ``` Publishes a bundle only after its claims survive a native serialization round trip and the reader -validates it. Requires the `schema` extra. `Label` is a JSON scalar class label. Every argument is +validates it. Requires the `schema` extra, and the `lock` extra unless `environment_lock` supplies +the runtime lock. `Label` is a JSON scalar class label. Every argument is described in [Export a bundle](/guides/export/#arguments). ### `inspect` @@ -54,8 +58,8 @@ described in [Export a bundle](/guides/export/#arguments). def inspect(source: BundleSource, *, limits: ArchiveLimits | None = None) -> MetadataView ``` -Validates the container, manifest, JSON bounds, hashes, schema and samples without importing a -model library. It cannot attest model-derived claims. +Validates the container, manifest, JSON bounds, hashes, runtime lock, schema and samples without +importing a model library. It cannot attest model-derived claims. ### `load` @@ -66,6 +70,17 @@ def load(source: BundleSource, *, limits: ArchiveLimits | None = None) -> Loaded Everything `inspect` does, then deserializes through the closed adapter and verifies recomputed claims and structure. `BundleSource` is `str | PathLike[str] | bytes | BinaryIO`. +### `check_environment` + +```python +def check_environment(bundle: MetadataView | LoadedBundle) -> None +``` + +Raises `EnvironmentMismatchError` unless the running interpreter is CPython with the GIL at the +lock's Python version, on a locked target (Linux with glibc 2.28 or newer, or Windows), with exactly the target's +locked distributions plus mlbundle at `writer_version` installed. It reads distribution metadata +only. See [Inspect and load](/guides/inspect-and-load/#serve-in-the-locked-environment). + ## Results ### `MetadataView` @@ -76,6 +91,7 @@ Frozen dataclass returned by `export` and `inspect`. | --- | --- | | `manifest` | `Manifest` | | `members` | `tuple[MemberName, ...]`, in canonical order | +| `environment_lock` | `EnvironmentLock` | | `schema` | `dict[str, JsonValue] \| None` | | `samples` | `list[dict[str, JsonValue]] \| None` | @@ -85,7 +101,7 @@ Frozen dataclass returned by `load`, constructed only after verification. | Member | Type / behaviour | | --- | --- | -| `manifest`, `members`, `schema`, `samples` | As in `MetadataView`. | +| `manifest`, `members`, `environment_lock`, `schema`, `samples` | As in `MetadataView`. | | `structure` | `dict[str, JsonValue] \| None` | | `native_model` | The native model object. | | `predictor` | The adapter's uniform predictor. | @@ -100,6 +116,23 @@ Frozen dataclass returned by `load`, constructed only after verification. | `row_from_record(record)` | `list[float]` in feature order | | `predict_record(record)` | `tuple[OutputPrediction, ...]`, one per output | +### `EnvironmentLock` + +Frozen record of the validated `pylock.toml`. + +| Member | Type / behaviour | +| --- | --- | +| `python_version` | `str`, the exact CPython version | +| `packages` | `tuple[LockedPackage, ...]`, sorted by name; each has `name`, `version`, `platforms` and `wheels` | +| `platforms`, `glibc` | `("linux-x86_64", "linux-aarch64", "win-amd64")` and the Linux minimum `(2, 28)` | +| `environment_id` | `str`, SHA-256 of the Python version, packages, targets, wheel names and digests | +| `version(name)` | Locked version of a normalized distribution name, or `None` | +| `to_bytes()` | The canonical TOML file | +| `EnvironmentLock.from_bytes(data)` | Parse and validate canonical bytes | + +`LockedWheel` has `name`, `url`, `size` and `sha256`. The rules are in +[the lock contract](/format/environment/). + ### `OutputPrediction` Frozen dataclass with `output`, `kind`, `labels`, `probabilities`, `value` and `predicted_label`. @@ -113,10 +146,10 @@ See [Records and predictions](/guides/records/#outputprediction). | `ModelInfo` | `estimator_class`, `kind`, `hyperparameters`, `n_features`, `n_classes`, `n_outputs`, `library`, `serialization`, `pipeline` and state fields | | `FeatureInfo` | `names`, `dtypes` (training), `model_dtypes` (verified), `origin` | | `TargetInfo` | `class_labels`, `names` | -| `TrainingEnvironment` | `python_version`, `python_implementation`, `os`, `os_version`, `architecture`, `packages`, `onnx` | +| `TrainingEnvironment` | `python_version`, `python_implementation`, `free_threaded`, `os`, `os_version`, `architecture`, `onnx` | | `OnnxInfo`, `Opset` | ONNX opsets, IR version and producer | | `IntegrityRecord` | `sha256`, `size` | -| `MemberReferences` | `schema`, `structure`, `samples` | +| `MemberReferences` | `schema`, `lock`, `structure`, `samples` | | `ModelClaims` | The model-derived claims the reader recomputes | Field types and verification rules are normative in [Format 1](/format/#manifest). @@ -131,7 +164,7 @@ All are `StrEnum`s whose values appear in the manifest. | `ModelKind` | `classifier`, `regressor` | | `SerializationFormat` | `skops`, `ubjson`, `cbm`, `onnx`, `pipeline` | | `FeatureOrigin` | `model`, `dataframe`, `declared`, `generated` | -| `MemberName` | `manifest.json`, `model.skops`, `model.ubj`, `model.cbm`, `model.onnx`, `schema.json`, `structure.json`, `samples.json` | +| `MemberName` | `manifest.json`, `model.skops`, `model.ubj`, `model.cbm`, `model.onnx`, `schema.json`, `structure.json`, `samples.json`, `pylock.toml` | ## Limits and errors diff --git a/docs/src/content/docs/reference/errors.md b/docs/src/content/docs/reference/errors.md index 93aafbd..251c59f 100644 --- a/docs/src/content/docs/reference/errors.md +++ b/docs/src/content/docs/reference/errors.md @@ -34,6 +34,8 @@ MLBundleError │ └── PredictionInputError (also a ValueError) ├── InvalidSchemaError ├── InvalidSamplesError +├── InvalidEnvironmentLockError +├── LockGenerationError ├── MissingOptionalDependencyError └── AdapterNotImplementedError ``` @@ -42,7 +44,7 @@ MLBundleError | Error | Raised when | Attributes | | --- | --- | --- | -| `InvalidContainerError` | The ZIP violates the container rules: unknown, duplicate or missing members, unsafe names, bad records or CRCs, a missing schema in an old bundle. | | +| `InvalidContainerError` | The ZIP violates the container rules: unknown, duplicate or missing members, unsafe names, bad records or CRCs, a missing schema or `pylock.toml` in an old bundle. | | | `LimitExceededError` | An input exceeds an [archive or member limit](/reference/limits/). | | | `UnsupportedFormatVersionError` | The manifest declares a format version other than `1`. | | | `InvalidManifestError` | The manifest fails strict validation; may hint at a different writer version. | | @@ -51,10 +53,12 @@ MLBundleError | `ClaimMismatchError` | A recomputed model claim or the structure differs from the bundle. | `claim` | | `UnsupportedModelError` | Export of a model outside the adapter boundary. | `untrusted_types` | | `InvalidModelError` | Native model content is malformed or violates the adapter contract. | | -| `EnvironmentMismatchError` | A skops load failed and the bundle declares a different scikit-learn version. | | +| `EnvironmentMismatchError` | A skops load failed and the bundle locks a different scikit-learn version, or `check_environment` found the interpreter, platform or installed distributions differ from the lock. | | | `PredictionInputError` | Invalid prediction input or record. | | | `InvalidSchemaError` | Training inputs or `schema.json` violate the schema contract. | | | `InvalidSamplesError` | Invalid `sample_rows`, cell conversion or sample keys. | | +| `InvalidEnvironmentLockError` | `pylock.toml` is not canonical, violates the lock contract or disagrees with the manifest; on export, a lock disagrees with the installed versions or Python. | | +| `LockGenerationError` | Export could not lock the installed runtime: a required distribution is missing or local, uv failed, or a target has no single wheel. | | | `MissingOptionalDependencyError` | A needed extra is not installed. | `extra` | | `AdapterNotImplementedError` | A library has no implemented adapter. | `library` | diff --git a/docs/src/content/docs/reference/limits.md b/docs/src/content/docs/reference/limits.md index 3385f3d..057aa2d 100644 --- a/docs/src/content/docs/reference/limits.md +++ b/docs/src/content/docs/reference/limits.md @@ -10,7 +10,7 @@ safety maxima: you can lower them for a call, never raise them. | Field | Default and maximum | | --- | --- | -| `max_members` | 6 (minimum 2) | +| `max_members` | 7 (minimum 2) | | `max_archive_bytes` | 512 MiB | | `max_compressed_bytes` | 512 MiB | | `max_member_bytes` | 512 MiB | @@ -20,6 +20,7 @@ safety maxima: you can lower them for a call, never raise them. | `max_structure_bytes` | 256 MiB | | `max_schema_bytes` | 16 MiB | | `max_samples_bytes` | 16 MiB | +| `max_lock_bytes` | 1 MiB, the `pylock.toml` member and `environment_lock=` input | A specific member cap never exceeds `max_member_bytes`. diff --git a/docs/src/spec.ts b/docs/src/spec.ts index dbcd850..3826feb 100644 --- a/docs/src/spec.ts +++ b/docs/src/spec.ts @@ -11,6 +11,7 @@ export const specPages = [ { file: "docs/format-pipeline.md", route: "/format/pipeline/", label: "Composite pipelines" }, { file: "docs/format-catboost.md", route: "/format/catboost/", label: "CatBoost mapping" }, { file: "docs/format-onnx.md", route: "/format/onnx/", label: "ONNX mapping" }, + { file: "docs/format-environment.md", route: "/format/environment/", label: "Environment lock" }, { file: "SECURITY.md", route: "/security/", label: "Security policy" }, ] as const; diff --git a/landing/src/components/BundleCard.astro b/landing/src/components/BundleCard.astro index 02142bd..66860b3 100644 --- a/landing/src/components/BundleCard.astro +++ b/landing/src/components/BundleCard.astro @@ -7,6 +7,7 @@ const roles: Record = { "model.skops": "The fitted model, in skops format", "schema.json": "Inputs and outputs, inferred locally", "structure.json": "The decision tree, for review", + "pylock.toml": "The runtime it needs, for Linux and Windows", }; const [verdict] = example.verify.stdout.split(";"); --- diff --git a/landing/src/components/Inside.astro b/landing/src/components/Inside.astro index 74787f3..aaaf6ed 100644 --- a/landing/src/components/Inside.astro +++ b/landing/src/components/Inside.astro @@ -1,7 +1,7 @@ --- import { docs } from "../data/site"; -// Three things every bundle carries; samples are the one optional addition. +// Four things every bundle carries; samples are the one optional addition. const parts = [ { title: "The model, in its own format", @@ -9,19 +9,23 @@ const parts = [ }, { title: "A manifest of what it claims", - text: "Class, hyperparameters, feature names and order, class labels, the Python and package versions it was trained with, and a SHA-256 hash for each of the other files.", + text: "Class, hyperparameters, feature names and order, class labels, the Python it was trained with, and a SHA-256 hash for each of the other files.", }, { title: "A schema made on your machine", text: "MLschema describes each input from the training DataFrame locally. The DataFrame itself is not written to the bundle.", }, + { + title: "A lock of what serving needs", + text: "A pylock.toml with the exact Python and the Linux and Windows wheels for the versions you trained with. MLbundle records it and never installs it; your server decides what to trust.", + }, ]; ---
-

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"