From a10ef9998eb618083889de5d6ee1a1a67cec6932 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Patryk=20W=C3=B3jtowicz?= Date: Sat, 28 Nov 2026 18:47:40 +0100 Subject: [PATCH] feat(cli): train a model in its environment and record its run --- .github/workflows/ci.yml | 6 +- CHANGELOG.md | 5 +- src/miniops/adapters/local/executor.py | 49 ++ src/miniops/adapters/local/metadata.py | 11 + src/miniops/adapters/local/schema.py | 9 + src/miniops/cli/app.py | 2 + src/miniops/cli/registry.py | 5 +- src/miniops/cli/train.py | 38 ++ src/miniops/config/model.py | 15 +- src/miniops/core/entities.py | 23 + src/miniops/core/errors.py | 4 + src/miniops/core/registry.py | 38 +- src/miniops/core/snapshots.py | 48 ++ src/miniops/core/training.py | 268 +++++++++ src/miniops/ports/executor.py | 16 +- src/miniops/runner/jobs.py | 27 +- src/miniops/runner/protocol.py | 7 +- src/miniops/templates/sklearn/model.toml.tmpl | 10 + src/miniops/tools.py | 20 +- tests/adapters/local/test_executor.py | 90 +++ tests/adapters/local/test_metadata.py | 8 + tests/adapters/local/test_schema.py | 34 +- tests/cli/test_app.py | 11 +- tests/cli/test_registry.py | 5 +- tests/cli/test_train.py | 97 ++++ tests/config/test_model.py | 47 +- tests/core/test_entities.py | 21 + tests/core/test_environments.py | 1 + tests/core/test_registry.py | 22 +- tests/core/test_snapshots.py | 63 +++ tests/core/test_training.py | 520 ++++++++++++++++++ tests/runner/conftest.py | 1 + tests/runner/test_jobs.py | 48 +- tests/runner/test_protocol.py | 7 + tests/templates/test_templates.py | 14 +- tests/test_boundary.py | 13 + tests/test_tools.py | 22 +- 37 files changed, 1577 insertions(+), 48 deletions(-) create mode 100644 src/miniops/adapters/local/executor.py create mode 100644 src/miniops/cli/train.py create mode 100644 src/miniops/core/snapshots.py create mode 100644 src/miniops/core/training.py create mode 100644 tests/adapters/local/test_executor.py create mode 100644 tests/cli/test_train.py create mode 100644 tests/core/test_snapshots.py create mode 100644 tests/core/test_training.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 308dd34..a092ea6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -76,7 +76,7 @@ jobs: - run: uv build # Install the wheel the way a user gets it from PyPI: no lock file, newest dependencies. # A project and a model made with it outside the repository check the packaged templates, - # and model.py, which imports the flavor, checks the model environment. + # and a training checks the model environment, which has polars to write the data. - name: Use the built package run: | miniops() { uv run --isolated --no-project --with "$GITHUB_WORKSPACE"/dist/*.whl miniops "$@"; } @@ -86,7 +86,9 @@ jobs: miniops init miniops new churn --flavor sklearn --task binary_classification cat models/churn/.python-version - models/churn/.venv/bin/python models/churn/model.py + mkdir data + models/churn/.venv/bin/python -c "import polars as pl; pl.DataFrame({'age': [21, 35, 47, 52], 'target': [0, 1, 0, 1]}).write_parquet('data/train.parquet')" + miniops train churn all-checks: name: All checks diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fce47b..68220e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,7 +9,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Added - Core domain model: models, versions with semantic version numbers, runs and aliases, with the rules for releasing, renumbering and deleting a version. -- Interfaces (ports) for the metadata store and the artifact store, and provisional ones for the executor, the serving backend and the image registry. +- Interfaces (ports) for the metadata store, the artifact store and the executor, and provisional ones for the serving backend and the image registry. - Local metadata store in SQLite, the first implementation of the metadata port. Its schema is versioned and upgrades itself when a store is opened, after making a backup. - `miniops init` creates a project in the current directory: it writes `miniops.toml` and adds `.miniops/` to `.gitignore`. - `miniops config show` prints the configuration of the project that the current directory belongs to. @@ -17,6 +17,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - Local artifact store, the first implementation of the artifact port: files in `.miniops/artifacts/`. A stored file is never replaced, and its content is checked against its digest when it is read. - `miniops new --flavor sklearn --task ` creates a model in the project: the directory `models//` with `model.toml`, a `model.py` to fill in, `pyproject.toml` and `.python-version`, the model in the store with its first draft, `1.0.0`, and the environment of the model, which uv creates with `uv.lock`. When the environment fails, the model stays and `miniops env sync ` finishes it. - `miniops env sync ` creates or updates the environment of a model from its `pyproject.toml` and `uv.lock`. +- `miniops train ` trains the draft of a model in its environment and records the run. The Parquet file, the target column and the random seed come from the new `[train]` table of `model.toml`, the parameters of `build` from `[params]`, and `--data` and `--seed` replace them for one training. It first brings the environment in line with `pyproject.toml` and `uv.lock`, as `miniops env sync` does. The run keeps the author from git, the seed, the versions of miniOPs and Python, the system, a snapshot of the model directory, the commit, the training log and the trained model. A model directory that the store does not know yet, as in a fresh clone, is registered first. - `miniops registry list` shows the models of the project, `miniops registry list ` the versions of one model, and `miniops registry show --version ` one version. - `miniops doctor` checks that uv and git are installed and that git has a user name and email, and inside a project, its configuration and the schema version of its store. It changes nothing and ends with exit code 1 when it finds a problem. - The scikit-learn flavor, installed with `miniops-ml[sklearn]` (polars, scikit-learn and skops). A model class subclasses `SklearnModel` and returns its estimator from `build`. It trains on a polars DataFrame, checks that the target column fits the task, predicts a `prediction` column and saves the model with skops, which refuses to load types that were not trusted. @@ -30,7 +31,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), - On Windows, output redirected to a file or a pipe shows a character that its code page lacks as `?`, instead of stopping the command. - An unexpected error inside a project shows a short message with the path of the log instead of a traceback. Outside a project, where there is no log, the traceback is still shown. - pydantic is now a dependency. It validates the configuration files. -- Continuous integration also runs the tests with the lowest dependency versions that `pyproject.toml` allows, and creates a project and a model with the built package. +- Continuous integration also runs the tests with the lowest dependency versions that `pyproject.toml` allows, and creates a project and a model with the built package and trains the model. ## [0.1.0a1] - 2026-11-11 diff --git a/src/miniops/adapters/local/executor.py b/src/miniops/adapters/local/executor.py new file mode 100644 index 0000000..db4a409 --- /dev/null +++ b/src/miniops/adapters/local/executor.py @@ -0,0 +1,49 @@ +import os +import subprocess +import sys +from collections.abc import Callable +from pathlib import Path +from typing import Self, override + +from miniops.ports.executor import Executor +from miniops.tools import does_not_run + + +class LocalExecutor(Executor): + """The executor of the ``local`` target: the runner in the environment of a model.""" + + def __init__(self, python: Path) -> None: + """Run jobs with ``python``, the interpreter of the environment of a model.""" + self.python = python + + @classmethod + def for_model(cls, directory: Path) -> Self: + """Run jobs in the environment of the model in ``directory``, its ``.venv``.""" + python = "Scripts/python.exe" if sys.platform == "win32" else "bin/python" + return cls(directory / ".venv" / python) + + @override + def run(self, job: Path, log: Path, show: Callable[[str], None]) -> int: + env = {**os.environ, "PYTHONUNBUFFERED": "1"} + with log.open("w", encoding="utf-8", newline="\n") as file: + try: + process = subprocess.Popen( + [self.python, "-m", "miniops.runner", str(job)], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + cwd=job.parent, + env=env, + ) + except OSError as error: + raise does_not_run(self.python, error) from error + assert process.stdout is not None + try: + for raw in process.stdout: + line = raw.decode("utf-8", errors="replace").rstrip("\r\n") + file.write(f"{line}\n") + show(line) + return process.wait() + finally: + if process.poll() is None: + process.kill() + process.wait() diff --git a/src/miniops/adapters/local/metadata.py b/src/miniops/adapters/local/metadata.py index cf57a4e..e4e2a42 100644 --- a/src/miniops/adapters/local/metadata.py +++ b/src/miniops/adapters/local/metadata.py @@ -17,6 +17,7 @@ Model, ModelVersion, Run, + RunEnvironment, RunStatus, Signature, Task, @@ -348,8 +349,13 @@ def _run_row(run: Run) -> _Row: **_artifact_row("snapshot", run.snapshot), "lock_digest": run.lock_digest, "code_commit": run.code_commit, + "author": run.author, + "seed": run.seed, **_artifact_row("artifact", run.artifact), "signature": _maybe(run.signature, lambda signature: json.dumps(asdict(signature))), + "environment": _maybe(run.environment, lambda found: json.dumps(asdict(found))), + "trusted_types": json.dumps(list(run.trusted_types)), + **_artifact_row("log", run.log), "error": run.error, } @@ -372,8 +378,13 @@ def _run(row: sqlite3.Row) -> Run: snapshot=_artifact(row, "snapshot"), lock_digest=row["lock_digest"], code_commit=row["code_commit"], + author=row["author"], + seed=row["seed"], artifact=_artifact(row, "artifact"), signature=_maybe(row["signature"], _signature), + environment=_maybe(row["environment"], lambda text: RunEnvironment(**json.loads(text))), + trusted_types=tuple(json.loads(row["trusted_types"])), + log=_artifact(row, "log"), error=row["error"], ) diff --git a/src/miniops/adapters/local/schema.py b/src/miniops/adapters/local/schema.py index b59de62..fa38eae 100644 --- a/src/miniops/adapters/local/schema.py +++ b/src/miniops/adapters/local/schema.py @@ -68,6 +68,15 @@ FOREIGN KEY (model_id, version_id) REFERENCES versions (model_id, id) ); """, + """ + ALTER TABLE runs ADD COLUMN author TEXT; + ALTER TABLE runs ADD COLUMN seed INTEGER; + ALTER TABLE runs ADD COLUMN environment TEXT; + ALTER TABLE runs ADD COLUMN trusted_types TEXT NOT NULL DEFAULT '[]'; + ALTER TABLE runs ADD COLUMN log_key TEXT; + ALTER TABLE runs ADD COLUMN log_digest TEXT; + ALTER TABLE runs ADD COLUMN log_size INTEGER; + """, ) diff --git a/src/miniops/cli/app.py b/src/miniops/cli/app.py index 4f60c3e..951fd63 100644 --- a/src/miniops/cli/app.py +++ b/src/miniops/cli/app.py @@ -10,6 +10,7 @@ from miniops.cli.init import init from miniops.cli.new import new from miniops.cli.registry import registry_app +from miniops.cli.train import train app = typer.Typer( name="miniops", @@ -18,6 +19,7 @@ ) app.command("init")(init) app.command("new")(new) +app.command("train")(train) app.command("doctor")(doctor) app.add_typer(config_app, name="config") app.add_typer(env_app, name="env") diff --git a/src/miniops/cli/registry.py b/src/miniops/cli/registry.py index 9153951..e543e37 100644 --- a/src/miniops/cli/registry.py +++ b/src/miniops/cli/registry.py @@ -25,7 +25,10 @@ def list_models( elif entries := list_catalog(stores.metadata): typer.echo(_models(entries)) else: - typer.echo("No models yet. Create one with `miniops new`.") + typer.echo( + "No models yet. Create one with `miniops new`, or train one that is in models/ " + "with `miniops train`." + ) @registry_app.command("show") diff --git a/src/miniops/cli/train.py b/src/miniops/cli/train.py new file mode 100644 index 0000000..38c18b0 --- /dev/null +++ b/src/miniops/cli/train.py @@ -0,0 +1,38 @@ +from pathlib import Path +from typing import Annotated + +import typer + +from miniops.adapters.local.executor import LocalExecutor +from miniops.adapters.stores import open_stores +from miniops.cli.arguments import model_name +from miniops.cli.paths import current_directory +from miniops.config.project import MODELS_DIR, find_project +from miniops.core.training import train_model + + +def train( + model: Annotated[str, typer.Argument(callback=model_name, help="Name of the model.")], + data: Annotated[ + Path | None, typer.Option(help="Parquet file to train on, instead of data in model.toml.") + ] = None, + seed: Annotated[ + int | None, + typer.Option(min=0, max=2**32 - 1, help="Random seed, instead of seed in model.toml."), + ] = None, +) -> None: + """Train the draft of a model in its environment and record the run.""" + project = find_project(current_directory()) + executor = LocalExecutor.for_model(project.root / MODELS_DIR / model) + with open_stores(project) as stores: + training = train_model( + stores.metadata, + stores.artifacts, + executor, + project.root, + model, + data=data, + seed=seed, + show=typer.echo, + ) + typer.echo(f"Trained {model} {training.version.number} in run {training.run.id}.") diff --git a/src/miniops/config/model.py b/src/miniops/config/model.py index 748e72e..2eb712b 100644 --- a/src/miniops/config/model.py +++ b/src/miniops/config/model.py @@ -2,7 +2,7 @@ from pathlib import Path from typing import Annotated -from pydantic import AfterValidator, Field +from pydantic import AfterValidator, Field, JsonValue from miniops.config.toml import Table, load from miniops.core.entities import Task, require_name @@ -31,10 +31,23 @@ class ModelSection(Table): entrypoint: str = Field(pattern=r"^[A-Za-z_][A-Za-z0-9_]*\.py:[A-Za-z_][A-Za-z0-9_]*$") +class TrainSection(Table): + """The ``[train]`` table of ``model.toml``.""" + + # A Parquet file, relative to the project directory. + data: Annotated[str, Field(min_length=1)] | None = None + target: str = Field(min_length=1) + # The range of seeds that numpy takes. + seed: int = Field(default=42, ge=0, lt=2**32) + + class ModelConfig(Table): """The content of ``model.toml``.""" model: ModelSection + train: TrainSection | None = None + # Given to build() of the model class. + params: dict[str, JsonValue] = Field(default_factory=dict) def load_model_config(directory: Path) -> ModelConfig: diff --git a/src/miniops/core/entities.py b/src/miniops/core/entities.py index c6b2fcd..2d4345d 100644 --- a/src/miniops/core/entities.py +++ b/src/miniops/core/entities.py @@ -132,6 +132,16 @@ class Signature: outputs: tuple[Column, ...] +@dataclass(frozen=True) +class RunEnvironment: + """Where a run trained: the versions of miniOPs and Python, the system and the processor.""" + + miniops: str + python: str + platform: str + machine: str + + @dataclass(frozen=True) class VersionRef: """Points at a released version by number and content. @@ -177,8 +187,15 @@ class Run: snapshot: ArtifactRef | None = None lock_digest: str | None = None code_commit: str | None = None + # "Name ", as git shows it. + author: str | None = None + seed: int | None = None artifact: ArtifactRef | None = None signature: Signature | None = None + environment: RunEnvironment | None = None + # The types that loading the model has to trust. + trusted_types: tuple[str, ...] = () + log: ArtifactRef | None = None finished_at: datetime | None = None error: str | None = None @@ -202,6 +219,9 @@ def finish( metrics: Mapping[str, float] | None = None, artifact: ArtifactRef | None = None, signature: Signature | None = None, + environment: RunEnvironment | None = None, + trusted_types: tuple[str, ...] = (), + log: ArtifactRef | None = None, error: str | None = None, ) -> Self: """Record how the run ended. @@ -220,6 +240,9 @@ def finish( metrics=self.metrics if metrics is None else metrics, artifact=artifact, signature=signature, + environment=environment, + trusted_types=trusted_types, + log=log, error=error, ) diff --git a/src/miniops/core/errors.py b/src/miniops/core/errors.py index 068b609..602e6c1 100644 --- a/src/miniops/core/errors.py +++ b/src/miniops/core/errors.py @@ -55,3 +55,7 @@ class ProtocolError(MiniopsError): class ToolError(MiniopsError): """A program that miniOPs runs, like uv, is missing or failed.""" + + +class TrainingError(MiniopsError): + """A training failed. Its run in the store says why.""" diff --git a/src/miniops/core/registry.py b/src/miniops/core/registry.py index 81a8fb6..566cb56 100644 --- a/src/miniops/core/registry.py +++ b/src/miniops/core/registry.py @@ -65,21 +65,20 @@ def create_model( AlreadyExistsError: If there is a model with this name already, or the directory exists. NotFoundError: If miniOPs has no template for the flavor. """ - now = datetime.now(UTC) - model = Model(id=uuid4(), name=name, flavor=flavor, task=task, created_at=now) - draft = ModelVersion(id=uuid4(), model_id=model.id, number=FIRST_VERSION, created_at=now) + model, draft = _new_model(name, flavor, task) if metadata.get_model(name) is not None: raise AlreadyExistsError(f"There is already a model named {name!r}.") directory.parent.mkdir(parents=True, exist_ok=True) try: directory.mkdir() except FileExistsError as error: - raise AlreadyExistsError(f"{directory} already exists.") from error + raise AlreadyExistsError( + f"{directory} already exists. If it holds a model, `miniops train {name}` adds the " + "model to the store." + ) from error try: write_model_files(directory, name, flavor, task) - with metadata.transaction(): - metadata.add_model(model) - metadata.add_version(draft) + _store(metadata, model, draft) except BaseException: # An interrupt can arrive after the commit, and a stored model keeps its directory. stored = metadata.get_model(name) @@ -89,6 +88,31 @@ def create_model( return draft +def register_model(metadata: MetadataStore, name: str, flavor: str, task: Task) -> ModelVersion: + """Add a model whose directory exists already, as in a fresh clone, with its first draft. + + Returns the draft. + + Raises: + AlreadyExistsError: If there is a model with this name already. + """ + model, draft = _new_model(name, flavor, task) + _store(metadata, model, draft) + return draft + + +def _new_model(name: str, flavor: str, task: Task) -> tuple[Model, ModelVersion]: + now = datetime.now(UTC) + model = Model(id=uuid4(), name=name, flavor=flavor, task=task, created_at=now) + return model, ModelVersion(id=uuid4(), model_id=model.id, number=FIRST_VERSION, created_at=now) + + +def _store(metadata: MetadataStore, model: Model, draft: ModelVersion) -> None: + with metadata.transaction(): + metadata.add_model(model) + metadata.add_version(draft) + + def _entry(metadata: MetadataStore, model: Model) -> CatalogEntry: return CatalogEntry( model=model, diff --git a/src/miniops/core/snapshots.py b/src/miniops/core/snapshots.py new file mode 100644 index 0000000..3f5aa13 --- /dev/null +++ b/src/miniops/core/snapshots.py @@ -0,0 +1,48 @@ +import shutil +import zipfile +from pathlib import Path + +_SKIPPED = frozenset( + { + ".git", + ".ipynb_checkpoints", + ".mypy_cache", + ".pytest_cache", + ".ruff_cache", + ".venv", + "__pycache__", + } +) +# A fixed date and Unix attributes make the archive the same on every system. +_DATE = (1980, 1, 1, 0, 0, 0) +_UNIX = 3 + + +def pack(directory: Path, archive: Path) -> None: + """Write the files of ``directory`` into the zip file ``archive``. + + The same files always give the same archive, byte for byte, so its digest names its + content. The environment of a model, caches and version control are left out. + """ + files: list[tuple[str, Path]] = [] + for root, directories, names in directory.walk(): + directories[:] = [name for name in directories if name not in _SKIPPED] + files += [ + ((root / name).relative_to(directory).as_posix(), root / name) + for name in names + if name not in _SKIPPED and not name.endswith(".pyc") + ] + with zipfile.ZipFile(archive, "w") as zipped: + for name, path in sorted(files): + info = zipfile.ZipInfo(name, _DATE) + info.create_system = _UNIX + info.external_attr = 0o644 << 16 + info.file_size = path.stat().st_size + with path.open("rb") as source, zipped.open(info, "w") as target: + shutil.copyfileobj(source, target) + + +def unpack(archive: Path, directory: Path) -> None: + """Write the files of the zip file ``archive`` into ``directory``.""" + with zipfile.ZipFile(archive) as zipped: + zipped.extractall(directory) diff --git a/src/miniops/core/training.py b/src/miniops/core/training.py new file mode 100644 index 0000000..9ec2f61 --- /dev/null +++ b/src/miniops/core/training.py @@ -0,0 +1,268 @@ +import hashlib +import logging +import tempfile +from collections.abc import Callable +from contextlib import suppress +from dataclasses import dataclass +from datetime import UTC, datetime +from pathlib import Path +from uuid import uuid4 + +from miniops import __version__ +from miniops.config.model import MODEL_FILE, ModelConfig, TrainSection, load_model_config +from miniops.config.project import MODELS_DIR +from miniops.core.entities import ( + ArtifactRef, + DatasetRef, + ModelVersion, + Run, + RunEnvironment, + RunStatus, + VersionStatus, +) +from miniops.core.environments import sync_environment +from miniops.core.errors import ( + ConfigError, + InvalidStateError, + NotFoundError, + ProtocolError, + TrainingError, + describe, +) +from miniops.core.registry import CatalogEntry, find_model, register_model +from miniops.core.snapshots import pack, unpack +from miniops.ports.artifacts import ArtifactStore +from miniops.ports.executor import Executor +from miniops.ports.metadata import MetadataStore +from miniops.runner.protocol import MODEL_DIR, RESULT_FILE, TrainJob, read_result, write_job +from miniops.tools import find_tool, git_commit, git_config + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class Training: + """A training that succeeded: the draft it trained and its run.""" + + version: ModelVersion + run: Run + + +def train_model( + metadata: MetadataStore, + artifacts: ArtifactStore, + executor: Executor, + root: Path, + name: str, + *, + data: Path | None = None, + seed: int | None = None, + show: Callable[[str], None], +) -> Training: + """Train the draft of a model in its environment and record the run. + + ``root`` is the directory of the project. ``data`` and ``seed`` replace those of the + ``[train]`` table of ``model.toml``. A model directory that the store does not know yet, + as in a fresh clone, is registered first. The runner trains a copy of the snapshot of + the model directory, and ``show`` gets what the training reports, line by line. + + Raises: + ConfigError: If ``model.toml`` is missing, not valid or does not fit the model. + NotFoundError: If the model directory, its ``pyproject.toml`` or the data is missing. + InvalidStateError: If the model has no draft to train, or several. + ToolError: If uv cannot sync the environment of the model. + TrainingError: If the training failed. Its run says why. + OSError: If the runner does not start, or a file cannot be read or stored. + """ + directory = root / MODELS_DIR / name + if not directory.is_dir(): + raise NotFoundError(f"There is no model directory {directory}.") + config = load_model_config(directory) + _data_file(root, data, _settings(directory, name, config).data) + entry, draft = _draft(metadata, directory, name, config, show) + sync_environment(directory) + with tempfile.TemporaryDirectory(prefix="miniops-", ignore_cleanup_errors=True) as temporary: + work = Path(temporary) + code = work / "model" + snapshot = work / "snapshot.zip" + pack(directory, snapshot) + stored = artifacts.put(snapshot, f"snapshots/{_digest(snapshot)}.zip") + unpack(snapshot, code) + # The copy is what trains, even if model.toml changed while uv synced. + config = load_model_config(code) + settings = _settings(directory, name, config) + source = _data_file(root, data, settings.data) + chosen = settings.seed if seed is None else seed + job = work / "job.json" + write_job( + TrainJob( + model=code.name, + entrypoint=config.model.entrypoint, + task=entry.model.task, + params=config.params, + data=source.as_posix(), + target=settings.target, + output="output", + seed=chosen, + ), + job, + ) + dataset = DatasetRef(uri=_uri(root, source), fingerprint=_digest(source)) + author, commit = _git(root) + lock = code / "uv.lock" + run = Run( + id=uuid4(), + version_id=draft.id, + started_at=datetime.now(UTC), + miniops_version=__version__, + params=config.params, + dataset=dataset, + snapshot=stored, + lock_digest=_digest(lock) if lock.is_file() else None, + code_commit=commit, + author=author, + seed=chosen, + ) + metadata.add_run(run) + try: + show(f"Training {name} {draft.number} on {dataset.uri}, seed {chosen}, run {run.id}") + finished = _finish(run, artifacts, work, executor.run(job, work / "train.log", show)) + metadata.update_run(finished) + except BaseException as error: + interrupted = isinstance(error, KeyboardInterrupt) + log = None + with suppress(OSError): + log = _stored_log(artifacts, work, run) + metadata.update_run( + run.finish( + RunStatus.INTERRUPTED if interrupted else RunStatus.FAILED, + datetime.now(UTC), + log=log, + error="The training was interrupted." if interrupted else _message(error), + ) + ) + raise + if finished.status is not RunStatus.SUCCEEDED: + raise TrainingError( + f"The training of {name} {draft.number} failed in run {run.id}: {finished.error}" + ) + return Training(version=draft, run=finished) + + +def _settings(directory: Path, name: str, config: ModelConfig) -> TrainSection: + path = directory / MODEL_FILE + if config.model.name != name: + raise ConfigError( + f"{path} names the model {config.model.name!r}, but its directory is {name!r}." + ) + if config.train is None: + raise ConfigError(f"{path} has no [train] table, so the target column is not known.") + return config.train + + +def _data_file(root: Path, given: Path | None, configured: str | None) -> Path: + if given is not None: + path = given.resolve() + elif configured is not None: + path = (root / configured).resolve() + else: + raise ConfigError( + "There is no data to train on. Name a Parquet file with --data, or as data in the " + "[train] table of model.toml." + ) + if not path.is_file(): + raise NotFoundError(f"There is no data file {path}.") + return path + + +def _draft( + metadata: MetadataStore, + directory: Path, + name: str, + config: ModelConfig, + show: Callable[[str], None], +) -> tuple[CatalogEntry, ModelVersion]: + flavor, task = config.model.flavor, config.model.task + if metadata.get_model(name) is None: + draft = register_model(metadata, name, flavor, task) + show(f"Registered the model {name!r} from {directory} with the draft {draft.number}") + entry = find_model(metadata, name) + if (entry.model.flavor, entry.model.task) != (flavor, task): + raise ConfigError( + f"{directory / MODEL_FILE} has the flavor {flavor} and the task {task}, but the " + f"model {name!r} has the flavor {entry.model.flavor} and the task {entry.model.task}." + ) + drafts = [version for version in entry.versions if version.status is VersionStatus.DRAFT] + if not drafts: + raise InvalidStateError(f"The model {name!r} has no draft to train.") + if len(drafts) > 1: + numbers = ", ".join(str(version.number) for version in drafts) + raise InvalidStateError(f"The model {name!r} has several drafts: {numbers}.") + return entry, drafts[0] + + +def _finish(run: Run, artifacts: ArtifactStore, work: Path, code: int) -> Run: + log = _stored_log(artifacts, work, run) + output = work / "output" + try: + result = read_result(output / RESULT_FILE) + except FileNotFoundError: + error = f"The runner ended with exit code {code} and left no result." + return run.finish(RunStatus.FAILED, datetime.now(UTC), log=log, error=error) + except ProtocolError as problem: + return run.finish(RunStatus.FAILED, datetime.now(UTC), log=log, error=str(problem)) + environment = RunEnvironment(**result.environment.model_dump()) + if result.failure is not None: + failure = result.failure + error = failure.message if failure.reported else f"{failure.type}: {failure.message}" + return run.finish( + RunStatus.FAILED, datetime.now(UTC), environment=environment, log=log, error=error + ) + model = work / "model.zip" + pack(output / MODEL_DIR, model) + return run.finish( + RunStatus.SUCCEEDED, + datetime.now(UTC), + artifact=artifacts.put(model, f"runs/{run.id}/model.zip"), + signature=result.signature, + environment=environment, + trusted_types=result.untrusted_types, + log=log, + ) + + +def _stored_log(artifacts: ArtifactStore, work: Path, run: Run) -> ArtifactRef | None: + log = work / "train.log" + return artifacts.put(log, f"runs/{run.id}/train.log") if log.is_file() else None + + +def _git(root: Path) -> tuple[str | None, str | None]: + """Return the author of a run and the commit of the project.""" + git = find_tool("git") + if git is None: + return None, None + try: + name, email = git_config(git, "user.name"), git_config(git, "user.email") + commit = git_commit(git, root) + except OSError as error: + logger.warning("git did not tell the author and the commit of the run: %s", describe(error)) + return None, None + author = " ".join(part for part in (name, f"<{email}>" if email else None) if part) + return author or None, commit + + +def _uri(root: Path, path: Path) -> str: + # Relative to the project, the path is the same on every machine. + root = root.resolve() + return path.relative_to(root).as_posix() if path.is_relative_to(root) else path.as_posix() + + +def _digest(path: Path) -> str: + with path.open("rb") as file: + return hashlib.file_digest(file, "sha256").hexdigest() + + +def _message(error: BaseException) -> str: + if isinstance(error, OSError): + return describe(error) + return f"{type(error).__name__}: {error}" diff --git a/src/miniops/ports/executor.py b/src/miniops/ports/executor.py index dd1fea5..cd94b7e 100644 --- a/src/miniops/ports/executor.py +++ b/src/miniops/ports/executor.py @@ -1,13 +1,19 @@ +from collections.abc import Callable from pathlib import Path from typing import Protocol class Executor(Protocol): - """Runs a training or tuning job on a target: in a subprocess, a container or a cloud job.""" + """Runs a job of the runner on a target: in a subprocess, a container or a cloud job.""" - def run(self, job: Path, workdir: Path) -> Path: - """Run the job described in the ``job`` file and return the path of its result file. + def run(self, job: Path, log: Path, show: Callable[[str], None]) -> int: + """Run the job in the ``job`` file and return the exit code of the runner. - An executor never touches the metadata store. The host reads the result file and - records what it says. + The output of the runner goes to the file ``log`` and, line by line, to ``show``. The + result file is in the output directory of the job when the runner left one. An + executor never touches the metadata store: the host reads the result file and records + what it says. + + Raises: + OSError: If the runner cannot be started. """ diff --git a/src/miniops/runner/jobs.py b/src/miniops/runner/jobs.py index 08e3b4c..8dfe8c5 100644 --- a/src/miniops/runner/jobs.py +++ b/src/miniops/runner/jobs.py @@ -2,7 +2,9 @@ import inspect import logging import platform +import random import sys +from contextlib import suppress from pathlib import Path from types import ModuleType @@ -12,6 +14,7 @@ from miniops.core.errors import ConfigError, MiniopsError, describe from miniops.flavors.base import FlavorModel from miniops.runner.protocol import ( + MODEL_DIR, RESULT_FILE, Environment, Failure, @@ -23,8 +26,6 @@ logger = logging.getLogger(__name__) -MODEL_DIR = "model" - def run(job_file: Path) -> Result: """Run the job in ``job_file`` and write its result into the output directory of the job. @@ -45,7 +46,10 @@ def run(job_file: Path) -> Result: try: result = _train(job, base, output / MODEL_DIR) except (Exception, SystemExit) as error: - logger.exception("The training failed") + if isinstance(error, MiniopsError): + logger.error("The training failed: %s", error) + else: + logger.exception("The training failed") result = Result(environment=_environment(), failure=_failure(error)) write_result(result, output / RESULT_FILE) return result @@ -113,8 +117,14 @@ def _train(job: TrainJob, base: Path, directory: Path) -> Result: model_class = load_model_class((base / job.model).resolve(), job.entrypoint) data = pl.read_parquet((base / job.data).resolve()) logger.info( - "Training %s for %s on %d rows of %s", job.entrypoint, job.task, len(data), job.data + "Training %s for %s on %d rows of %s with the seed %d", + job.entrypoint, + job.task, + len(data), + job.data, + job.seed, ) + _seed(job.seed) model = model_class(job.task) signature = model.fit(data, job.target, job.params) directory.mkdir() @@ -131,6 +141,15 @@ def _train(job: TrainJob, base: Path, directory: Path) -> Result: ) +def _seed(value: int) -> None: + random.seed(value) + # An estimator without a random_state of its own draws from the global generator of numpy. + with suppress(ImportError): + import numpy + + numpy.random.seed(value) + + def _environment() -> Environment: return Environment( miniops=__version__, diff --git a/src/miniops/runner/protocol.py b/src/miniops/runner/protocol.py index 98c1e2a..e848890 100644 --- a/src/miniops/runner/protocol.py +++ b/src/miniops/runner/protocol.py @@ -10,6 +10,7 @@ PROTOCOL: Final = 1 RESULT_FILE = "result.json" +MODEL_DIR = "model" # A backslash would be part of a file name on Linux, where a job can run in a container. _PATH = r"^[^\\]+$" @@ -34,7 +35,11 @@ class TrainJob(_File): data: str = Field(pattern=_PATH, description="The Parquet file to train on.") target: str output: str = Field( - pattern=_PATH, description="The directory for the files of the model and the result." + pattern=_PATH, + description="The directory for the result and, in model/, the files of the trained model.", + ) + seed: int = Field( + ge=0, lt=2**32, description="Seeds the random generators of Python and numpy." ) diff --git a/src/miniops/templates/sklearn/model.toml.tmpl b/src/miniops/templates/sklearn/model.toml.tmpl index 63a9acc..8563a2e 100644 --- a/src/miniops/templates/sklearn/model.toml.tmpl +++ b/src/miniops/templates/sklearn/model.toml.tmpl @@ -3,3 +3,13 @@ name = "$name" flavor = "$flavor" task = "$task" entrypoint = "model.py:$class_name" + +[train] +# A Parquet file with the inputs and the target column, relative to the project directory. +data = "data/train.parquet" +target = "target" +seed = 42 + +[params] +# Given to build() in model.py. +n_estimators = 100 diff --git a/src/miniops/tools.py b/src/miniops/tools.py index 1dd3bdb..070596e 100644 --- a/src/miniops/tools.py +++ b/src/miniops/tools.py @@ -49,6 +49,19 @@ def git_config(git: Path, key: str) -> str | None: return _output(git, result).strip() or None +def git_commit(git: Path, directory: Path) -> str | None: + """Return the commit that the git repository of ``directory`` is at, or None without one. + + Raises: + OSError: If git does not run or does not answer. + """ + result = _run(git, "-C", str(directory), "rev-parse", "--verify", "--quiet", "HEAD") + # git exits with 128 outside a repository and with 1 in one without commits. + if result.returncode != 0: + return None + return result.stdout.strip() or None + + def run_tool(tool: Path, *arguments: str, env: Mapping[str, str] | None = None) -> None: """Run a program that prints to the terminal itself, and wait as long as it takes. @@ -61,7 +74,7 @@ def run_tool(tool: Path, *arguments: str, env: Mapping[str, str] | None = None) try: code = subprocess.run([tool, *arguments], env=env, check=False).returncode except OSError as error: - raise _does_not_run(tool, error) from error + raise does_not_run(tool, error) from error if code != 0: raise ToolError(f"{tool.stem} {' '.join(arguments)} exited with code {code}.") @@ -81,13 +94,14 @@ def _run(tool: Path, *arguments: str) -> subprocess.CompletedProcess[str]: except subprocess.TimeoutExpired as error: raise OSError(f"{tool} did not answer within {_TIMEOUT_SECONDS} seconds.") from error except OSError as error: - raise _does_not_run(tool, error) from error + raise does_not_run(tool, error) from error return subprocess.CompletedProcess( process.args, process.returncode, _text(stdout), _text(stderr) ) -def _does_not_run(tool: Path, error: OSError) -> OSError: +def does_not_run(tool: Path, error: OSError) -> OSError: + """Return the error for a program that could not be started, which names the program.""" # Windows puts %1 where the name of the program belongs. reason = (error.strerror or str(error)).replace("%1", tool.name) return OSError(f"{tool} does not run: {reason}") diff --git a/tests/adapters/local/test_executor.py b/tests/adapters/local/test_executor.py new file mode 100644 index 0000000..bb7a71f --- /dev/null +++ b/tests/adapters/local/test_executor.py @@ -0,0 +1,90 @@ +import sys +from pathlib import Path + +import polars as pl +import pytest + +from miniops.adapters.local.executor import LocalExecutor +from miniops.core.entities import Task +from miniops.runner.protocol import TrainJob, read_result, write_job +from miniops.templates import write_model_files + +DATA = pl.DataFrame({"age": [21, 35, 47, 52, 23, 61], "churned": [0, 1, 0, 1, 0, 1]}) +PYTHON = LocalExecutor(Path(sys.executable)) + + +def a_job(directory: Path, target: str = "churned") -> Path: + (directory / "model").mkdir() + write_model_files(directory / "model", "churn", "sklearn", Task.BINARY_CLASSIFICATION) + DATA.write_parquet(directory / "train.parquet") + job = TrainJob( + model="model", + entrypoint="model.py:Churn", + task=Task.BINARY_CLASSIFICATION, + params={"n_estimators": 5, "random_state": 0}, + data="train.parquet", + target=target, + output="output", + seed=0, + ) + write_job(job, directory / "job.json") + return directory / "job.json" + + +def test_the_runner_runs_and_what_it_reports_is_shown_and_logged(tmp_path: Path) -> None: + shown: list[str] = [] + + code = PYTHON.run(a_job(tmp_path), tmp_path / "train.log", shown.append) + + assert code == 0 + assert any("Training model.py:Churn" in line for line in shown) + assert (tmp_path / "train.log").read_text(encoding="utf-8").splitlines() == shown + assert read_result(tmp_path / "output" / "result.json").failure is None + + +def test_a_job_that_fails_ends_with_1_and_leaves_its_result(tmp_path: Path) -> None: + code = PYTHON.run(a_job(tmp_path, target="spend"), tmp_path / "train.log", lambda line: None) + + assert code == 1 + failure = read_result(tmp_path / "output" / "result.json").failure + assert failure is not None + assert failure.type == "DataError" + + +def test_what_the_model_code_prints_arrives_as_it_is(tmp_path: Path) -> None: + job = a_job(tmp_path) + model = tmp_path / "model" / "model.py" + model.write_text( + model.read_text(encoding="utf-8").replace( + "return Pipeline(", 'print("Mało danych 数据")\n return Pipeline(' + ), + encoding="utf-8", + ) + shown: list[str] = [] + + assert PYTHON.run(job, tmp_path / "train.log", shown.append) == 0 + + assert "Mało danych 数据" in shown + + +def test_a_python_that_does_not_run_is_reported(tmp_path: Path) -> None: + missing = LocalExecutor(tmp_path / "missing" / "python") + + with pytest.raises(OSError, match="does not run: "): + missing.run(a_job(tmp_path), tmp_path / "train.log", lambda line: None) + + +def test_an_interrupt_stops_the_runner(tmp_path: Path) -> None: + def interrupt(line: str) -> None: + raise KeyboardInterrupt + + with pytest.raises(KeyboardInterrupt): + PYTHON.run(a_job(tmp_path), tmp_path / "train.log", interrupt) + + assert len((tmp_path / "train.log").read_text(encoding="utf-8").splitlines()) == 1 + + +def test_a_model_is_trained_with_the_python_of_its_environment(tmp_path: Path) -> None: + python = "Scripts/python.exe" if sys.platform == "win32" else "bin/python" + + assert LocalExecutor.for_model(tmp_path).python == tmp_path / ".venv" / python diff --git a/tests/adapters/local/test_metadata.py b/tests/adapters/local/test_metadata.py index e671974..19f05d9 100644 --- a/tests/adapters/local/test_metadata.py +++ b/tests/adapters/local/test_metadata.py @@ -19,6 +19,7 @@ Model, ModelVersion, Run, + RunEnvironment, RunStatus, Signature, Task, @@ -260,11 +261,18 @@ def test_a_run_comes_back_as_it_was_stored(store: SqliteMetadataStore) -> None: snapshot=ArtifactRef(key="snapshots/ab/cdef.zip", digest="b" * 64, size=2048), lock_digest="c" * 64, code_commit="5d73e7c", + author="Ada Lovelace ", + seed=42, artifact=ARTIFACT, signature=Signature( inputs=(Column("age", "Int64"), Column("plan", "String", nullable=True)), outputs=(Column("churn", "Float64"),), ), + environment=RunEnvironment( + miniops="0.1.0", python="3.12.16", platform="Linux-6.8-x86_64", machine="x86_64" + ), + trusted_types=("sklearn.tree._tree.Tree",), + log=ArtifactRef(key="runs/7c1e/train.log", digest="d" * 64, size=512), finished_at=LATER, ) diff --git a/tests/adapters/local/test_schema.py b/tests/adapters/local/test_schema.py index f6d2cf7..c4f6179 100644 --- a/tests/adapters/local/test_schema.py +++ b/tests/adapters/local/test_schema.py @@ -9,15 +9,13 @@ from miniops.adapters.local import schema from miniops.adapters.local.metadata import SqliteMetadataStore -from miniops.core.entities import Model, Task +from miniops.core.entities import Model, ModelVersion, Run, Task from miniops.core.errors import IncompatibleStoreError +from miniops.core.versions import FIRST_VERSION +NOW = datetime(2026, 11, 11, 12, 0, tzinfo=UTC) MODEL = Model( - id=uuid4(), - name="churn", - flavor="sklearn", - task=Task.BINARY_CLASSIFICATION, - created_at=datetime(2026, 11, 11, 12, 0, tzinfo=UTC), + id=uuid4(), name="churn", flavor="sklearn", task=Task.BINARY_CLASSIFICATION, created_at=NOW ) @@ -79,6 +77,30 @@ def test_an_older_store_is_upgraded_after_a_backup( assert store.list_models() == [MODEL] +def test_a_run_from_the_first_schema_reads_back_after_the_upgrade( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + path = tmp_path / "metadata.db" + monkeypatch.setattr(schema, "MIGRATIONS", schema.MIGRATIONS[:1]) + version = ModelVersion(id=uuid4(), model_id=MODEL.id, number=FIRST_VERSION, created_at=NOW) + with SqliteMetadataStore(path) as store: + store.add_model(MODEL) + store.add_version(version) + run_id = uuid4() + with closing(sqlite3.connect(path, autocommit=True)) as connection: + connection.execute( + "INSERT INTO runs (id, version_id, status, started_at, miniops_version, params, " + "metrics) VALUES (?, ?, 'running', ?, '0.1.0a1', '{}', '{}')", + (str(run_id), str(version.id), NOW.isoformat(timespec="microseconds")), + ) + monkeypatch.undo() + + with SqliteMetadataStore(path) as store: + run = store.get_run(run_id) + + assert run == Run(id=run_id, version_id=version.id, started_at=NOW, miniops_version="0.1.0a1") + + def test_a_failed_upgrade_changes_nothing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: path = tmp_path / "metadata.db" with SqliteMetadataStore(path) as store: diff --git a/tests/cli/test_app.py b/tests/cli/test_app.py index 945eba2..592eeab 100644 --- a/tests/cli/test_app.py +++ b/tests/cli/test_app.py @@ -25,7 +25,16 @@ def test_help_shows_usage() -> None: @pytest.mark.parametrize( "command", - [["init"], ["config"], ["config", "show"], ["doctor"], ["env"], ["env", "sync"], ["version"]], + [ + ["init"], + ["config"], + ["config", "show"], + ["doctor"], + ["env"], + ["env", "sync"], + ["train"], + ["version"], + ], ) def test_every_command_exists_and_has_help(command: list[str]) -> None: result = runner.invoke(app, [*command, "--help"]) diff --git a/tests/cli/test_registry.py b/tests/cli/test_registry.py index dcf1296..6927d6b 100644 --- a/tests/cli/test_registry.py +++ b/tests/cli/test_registry.py @@ -87,7 +87,10 @@ def test_registry_list_says_when_there_are_no_models( result = runner.invoke(app, ["registry", "list"]) assert result.exit_code == 0 - assert result.stdout == "No models yet. Create one with `miniops new`.\n" + assert result.stdout == ( + "No models yet. Create one with `miniops new`, or train one that is in models/ with " + "`miniops train`.\n" + ) @pytest.mark.usefixtures("project") diff --git a/tests/cli/test_train.py b/tests/cli/test_train.py new file mode 100644 index 0000000..9201568 --- /dev/null +++ b/tests/cli/test_train.py @@ -0,0 +1,97 @@ +import sys +import zipfile +from pathlib import Path + +import polars as pl +import pytest +from typer.testing import CliRunner + +from miniops.adapters.local.executor import LocalExecutor +from miniops.adapters.stores import open_stores +from miniops.cli import app, new +from miniops.config.project import find_project, init_project +from miniops.core import training +from miniops.core.entities import RunStatus +from miniops.core.errors import ConfigError, TrainingError +from miniops.core.registry import find_model + +runner = CliRunner() + + +@pytest.fixture +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + init_project(tmp_path) + monkeypatch.chdir(tmp_path) + for module in (new, training): + monkeypatch.setattr(module, "sync_environment", lambda directory: None) + monkeypatch.setattr(training, "find_tool", lambda name: None) + # The Python of the tests has miniOPs with the flavor, as the environment of a model does. + monkeypatch.setattr( + LocalExecutor, "for_model", classmethod(lambda cls, directory: cls(Path(sys.executable))) + ) + created = runner.invoke( + app, ["new", "churn", "--flavor", "sklearn", "--task", "binary_classification"] + ) + assert created.exit_code == 0, created.output + (tmp_path / "data").mkdir() + pl.DataFrame({"age": [21, 35, 47, 52, 23, 61], "target": [0, 1, 0, 1, 0, 1]}).write_parquet( + tmp_path / "data" / "train.parquet" + ) + return tmp_path + + +def test_train_trains_the_model_in_its_environment_and_records_the_run(project: Path) -> None: + result = runner.invoke(app, ["train", "churn"]) + + assert result.exit_code == 0, result.output + with open_stores(find_project(project)) as stores: + [draft] = find_model(stores.metadata, "churn").versions + [run] = stores.metadata.list_runs(draft.id) + assert run.artifact is not None + stores.artifacts.get(run.artifact, project / "model.zip") + assert run.status is RunStatus.SUCCEEDED + assert "Training churn 1.0.0 on data/train.parquet, seed 42, run" in result.stdout + assert "INFO miniops.runner.jobs: Training model.py:Churn" in result.stdout + assert result.stdout.splitlines()[-1] == f"Trained churn 1.0.0 in run {run.id}." + with zipfile.ZipFile(project / "model.zip") as zipped: + assert zipped.namelist() == ["model.skops"] + + +def test_a_failed_training_ends_with_its_reason(project: Path) -> None: + model_toml = project / "models" / "churn" / "model.toml" + model_toml.write_text( + model_toml.read_text(encoding="utf-8").replace('target = "target"', 'target = "spend"'), + encoding="utf-8", + ) + + result = runner.invoke(app, ["train", "churn"]) + + assert result.exit_code == 1 + assert isinstance(result.exception, TrainingError) + assert str(result.exception).endswith(": The data has no target column 'spend'.") + assert "Traceback" not in result.stdout + + +@pytest.mark.parametrize( + "arguments", + [ + ["train", "Churn"], + ["train", "churn", "--seed", "-1"], + ["train", "churn", "--seed", "4294967296"], + ], +) +def test_train_refuses_arguments_that_are_not_valid( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, arguments: list[str] +) -> None: + monkeypatch.chdir(tmp_path) + + assert runner.invoke(app, arguments).exit_code == 2 + + +def test_train_needs_a_project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.chdir(tmp_path) + + result = runner.invoke(app, ["train", "churn"]) + + assert result.exit_code == 1 + assert isinstance(result.exception, ConfigError) diff --git a/tests/config/test_model.py b/tests/config/test_model.py index 908c4b0..9d449f1 100644 --- a/tests/config/test_model.py +++ b/tests/config/test_model.py @@ -2,7 +2,7 @@ import pytest -from miniops.config.model import Flavor, load_model_config +from miniops.config.model import Flavor, TrainSection, load_model_config from miniops.core.entities import Task from miniops.core.errors import ConfigError @@ -50,3 +50,48 @@ def test_a_model_config_that_is_not_valid_names_the_problem( with pytest.raises(ConfigError, match=problem): load_model_config(tmp_path) + + +def test_the_train_table_and_the_params_are_read(tmp_path: Path) -> None: + write_config( + tmp_path, + VALID + '\n[train]\ndata = "data/train.parquet"\ntarget = "churned"\nseed = 7\n' + '\n[params]\nn_estimators = 300\nclass_weight = { "0" = 1.0, "1" = 2.5 }\n', + ) + + config = load_model_config(tmp_path) + + assert config.train == TrainSection(data="data/train.parquet", target="churned", seed=7) + assert config.params == {"n_estimators": 300, "class_weight": {"0": 1.0, "1": 2.5}} + + +def test_the_train_table_and_the_params_can_be_left_out(tmp_path: Path) -> None: + write_config(tmp_path, VALID + '\n[train]\ntarget = "churned"\n') + + config = load_model_config(tmp_path) + + assert config.train == TrainSection(data=None, target="churned", seed=42) + assert config.params == {} + write_config(tmp_path, VALID) + assert load_model_config(tmp_path).train is None + + +@pytest.mark.parametrize( + ("tables", "problem"), + [ + ('[train]\ntarget = "churned"\nseed = -1', "train.seed: "), + ('[train]\ntarget = "churned"\nseed = 4294967296', "train.seed: "), + ('[train]\ndata = "train.parquet"', "train.target: "), + ('[train]\ntarget = ""', "train.target: "), + ('[train]\ntarget = "churned"\ndata = ""', "train.data: "), + ('[train]\ntarget = "churned"\nsplit = 0.2', "train.split: "), + ("[params]\nfrom = 2026-11-22T10:00:00", "params.from"), + ], +) +def test_a_train_table_or_params_that_are_not_valid_name_the_problem( + tmp_path: Path, tables: str, problem: str +) -> None: + write_config(tmp_path, f"{VALID}\n{tables}\n") + + with pytest.raises(ConfigError, match=problem): + load_model_config(tmp_path) diff --git a/tests/core/test_entities.py b/tests/core/test_entities.py index 4f26030..6f9dab5 100644 --- a/tests/core/test_entities.py +++ b/tests/core/test_entities.py @@ -11,6 +11,7 @@ Model, ModelVersion, Run, + RunEnvironment, RunStatus, Task, VersionRef, @@ -213,6 +214,26 @@ def test_a_run_starts_as_running_and_records_how_it_ended() -> None: assert run.artifact == ARTIFACT +def test_a_run_records_where_it_trained_what_to_trust_and_its_log() -> None: + environment = RunEnvironment( + miniops="0.1.0", python="3.12.16", platform="Linux-6.8-x86_64", machine="x86_64" + ) + log = ArtifactRef(key="runs/7c1e/train.log", digest=DIGEST, size=512) + + run = running_run(draft()).finish( + RunStatus.SUCCEEDED, + LATER, + artifact=ARTIFACT, + environment=environment, + trusted_types=("sklearn.tree._tree.Tree",), + log=log, + ) + + assert run.environment == environment + assert run.trusted_types == ("sklearn.tree._tree.Tree",) + assert run.log == log + + def test_a_run_ends_only_once() -> None: with pytest.raises(InvalidStateError, match="already ended"): successful_run(draft()).finish(RunStatus.FAILED, LATER) diff --git a/tests/core/test_environments.py b/tests/core/test_environments.py index 44a9856..88f0b2d 100644 --- a/tests/core/test_environments.py +++ b/tests/core/test_environments.py @@ -110,6 +110,7 @@ def test_a_new_model_gets_an_environment_that_trains_it(tmp_path: Path) -> None: data="train.parquet", target="churned", output="output", + seed=0, ) write_job(job, tmp_path / "job.json") finished = subprocess.run( diff --git a/tests/core/test_registry.py b/tests/core/test_registry.py index 61b5ae5..8c58921 100644 --- a/tests/core/test_registry.py +++ b/tests/core/test_registry.py @@ -18,7 +18,7 @@ VersionStatus, ) from miniops.core.errors import AlreadyExistsError, NotFoundError -from miniops.core.registry import create_model, find_model, list_catalog +from miniops.core.registry import create_model, find_model, list_catalog, register_model from miniops.core.versions import FIRST_VERSION, SemVer NOW = datetime(2026, 11, 16, 12, 0, tzinfo=UTC) @@ -167,6 +167,26 @@ def test_a_name_that_is_not_valid_creates_nothing( assert not (tmp_path / "models").exists() +def test_a_model_whose_directory_exists_is_registered_with_a_first_draft( + metadata: SqliteMetadataStore, directory: Path +) -> None: + draft = register_model(metadata, "churn", "sklearn", Task.REGRESSION) + + model = metadata.get_model("churn") + assert model is not None + assert model.task is Task.REGRESSION + assert metadata.list_versions(model.id) == [draft] + assert draft.number == FIRST_VERSION + assert not directory.exists() + + +def test_a_registered_name_is_used_once(metadata: SqliteMetadataStore) -> None: + register_model(metadata, "churn", "sklearn", Task.REGRESSION) + + with pytest.raises(AlreadyExistsError, match="already in the store"): + register_model(metadata, "churn", "sklearn", Task.REGRESSION) + + def test_the_catalog_has_every_model_with_its_versions_and_aliases( metadata: SqliteMetadataStore, directory: Path, tmp_path: Path ) -> None: diff --git a/tests/core/test_snapshots.py b/tests/core/test_snapshots.py new file mode 100644 index 0000000..8dd547f --- /dev/null +++ b/tests/core/test_snapshots.py @@ -0,0 +1,63 @@ +import os +import zipfile +from pathlib import Path + +from miniops.core.snapshots import pack, unpack + +CODE = { + ".python-version": "3.12\n", + "model.py": "class Churn: ...\n", + "steps/scale.py": "SCALE = 2\n", +} +NOT_CODE = [ + ".venv/Lib/site.py", + "__pycache__/model.cpython-312.pyc", + "steps/__pycache__/scale.cpython-312.pyc", + "steps/old.pyc", + ".git/HEAD", + ".pytest_cache/README.md", + ".ipynb_checkpoints/notes.ipynb", +] + + +def a_model(directory: Path) -> Path: + for name, text in CODE.items(): + (directory / name).parent.mkdir(parents=True, exist_ok=True) + (directory / name).write_text(text, encoding="utf-8") + for name in NOT_CODE: + (directory / name).parent.mkdir(parents=True, exist_ok=True) + (directory / name).write_text("not code", encoding="utf-8") + return directory + + +def test_a_snapshot_holds_the_code_without_the_environment_and_the_caches(tmp_path: Path) -> None: + pack(a_model(tmp_path / "churn"), tmp_path / "snapshot.zip") + + with zipfile.ZipFile(tmp_path / "snapshot.zip") as zipped: + assert zipped.namelist() == sorted(CODE) + + +def test_the_same_files_give_the_same_archive(tmp_path: Path) -> None: + model = a_model(tmp_path / "churn") + pack(model, tmp_path / "first.zip") + os.utime(model / "model.py", (0, 0)) + + pack(model, tmp_path / "second.zip") + + assert (tmp_path / "first.zip").read_bytes() == (tmp_path / "second.zip").read_bytes() + with zipfile.ZipFile(tmp_path / "second.zip") as zipped: + info = zipped.getinfo("model.py") + assert (info.date_time, info.create_system) == ((1980, 1, 1, 0, 0, 0), 3) + + +def test_a_snapshot_unpacks_into_the_same_files(tmp_path: Path) -> None: + pack(a_model(tmp_path / "churn"), tmp_path / "snapshot.zip") + + unpack(tmp_path / "snapshot.zip", tmp_path / "copy") + + files = { + path.relative_to(tmp_path / "copy").as_posix(): path.read_text(encoding="utf-8") + for path in (tmp_path / "copy").rglob("*") + if path.is_file() + } + assert files == CODE diff --git a/tests/core/test_training.py b/tests/core/test_training.py new file mode 100644 index 0000000..2b4b14c --- /dev/null +++ b/tests/core/test_training.py @@ -0,0 +1,520 @@ +import hashlib +import logging +import re +import zipfile +from collections.abc import Callable, Iterator +from pathlib import Path +from uuid import uuid4 + +import polars as pl +import pytest + +from miniops import __version__ +from miniops.adapters.stores import Stores, open_stores +from miniops.config.project import Project, init_project +from miniops.core import training +from miniops.core.entities import ( + ArtifactRef, + Column, + DatasetRef, + ModelVersion, + Run, + RunEnvironment, + RunStatus, + Signature, + Task, +) +from miniops.core.errors import ( + ConfigError, + InvalidStateError, + NotFoundError, + ToolError, + TrainingError, +) +from miniops.core.registry import create_model, find_model +from miniops.core.training import Training, train_model +from miniops.core.versions import FIRST_VERSION, SemVer +from miniops.runner.protocol import Environment, Failure, Result, TrainJob, read_job, write_result +from miniops.templates import write_model_files + +DATA = pl.DataFrame({"age": [21, 35, 47, 52], "target": [0, 1, 0, 1]}) +ENVIRONMENT = Environment( + miniops="0.1.0a1", python="3.12.16", platform="Linux-6.8-x86_64", machine="x86_64" +) +RESULT = Result( + environment=ENVIRONMENT, + signature=Signature(inputs=(Column("age", "Int64"),), outputs=(Column("prediction", "Int64"),)), + files=("model.skops",), + untrusted_types=("sklearn.tree._tree.Tree",), +) + + +class FakeRunner: + def __init__(self, result: Result | None = RESULT, error: BaseException | None = None) -> None: + self.result = result + self.error = error + self.jobs: list[TrainJob] = [] + self.code: list[str] = [] + + def run(self, job: Path, log: Path, show: Callable[[str], None]) -> int: + found = read_job(job) + self.jobs.append(found) + model = job.parent / found.model + self.code = sorted( + path.relative_to(model).as_posix() for path in model.rglob("*") if path.is_file() + ) + log.write_text("Training\n", encoding="utf-8") + show("Training") + if self.error is not None: + raise self.error + if self.result is None: + return 3 + output = job.parent / found.output + (output / "model").mkdir(parents=True) + (output / "model" / "model.skops").write_bytes(b"a model") + write_result(self.result, output / "result.json") + return 0 if self.result.failure is None else 1 + + +@pytest.fixture +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Project: + (tmp_path / "project" / "data").mkdir(parents=True) + DATA.write_parquet(tmp_path / "project" / "data" / "train.parquet") + monkeypatch.setattr(training, "sync_environment", lambda directory: None) + monkeypatch.setattr(training, "find_tool", lambda name: None) + return init_project(tmp_path / "project") + + +@pytest.fixture +def stores(project: Project) -> Iterator[Stores]: + with open_stores(project) as opened: + directory = project.root / "models" / "churn" + create_model(opened.metadata, directory, "churn", "sklearn", Task.BINARY_CLASSIFICATION) + yield opened + + +def train( + project: Project, + stores: Stores, + runner: FakeRunner, + *, + data: Path | None = None, + seed: int | None = None, + show: Callable[[str], None] = lambda line: None, +) -> Training: + return train_model( + stores.metadata, + stores.artifacts, + runner, + project.root, + "churn", + data=data, + seed=seed, + show=show, + ) + + +def runs_of(stores: Stores) -> list[Run]: + [draft] = find_model(stores.metadata, "churn").versions + return list(stores.metadata.list_runs(draft.id)) + + +def digest(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def stored(stores: Stores, ref: ArtifactRef | None, path: Path) -> Path: + assert ref is not None + stores.artifacts.get(ref, path) + return path + + +def edit(path: Path, old: str, new: str) -> None: + path.write_text(path.read_text(encoding="utf-8").replace(old, new), encoding="utf-8") + + +def test_a_training_records_its_run_with_what_it_takes_to_repeat_it( + project: Project, stores: Stores, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + identity = {"user.name": "Ada Lovelace", "user.email": "ada@example.com"} + monkeypatch.setattr(training, "find_tool", lambda name: Path("/tools/git")) + monkeypatch.setattr(training, "git_config", lambda git, key: identity[key]) + monkeypatch.setattr(training, "git_commit", lambda git, directory: "5d73e7c") + directory = project.root / "models" / "churn" + (directory / "uv.lock").write_text("version = 1\n", encoding="utf-8") + data = project.root / "data" / "train.parquet" + runner = FakeRunner() + shown: list[str] = [] + + done = train(project, stores, runner, show=shown.append) + + run = done.run + assert done.version.number == FIRST_VERSION + assert stores.metadata.get_run(run.id) == run + assert (run.status, run.version_id, run.error) == (RunStatus.SUCCEEDED, done.version.id, None) + assert (run.miniops_version, run.seed, run.params) == (__version__, 42, {"n_estimators": 100}) + assert (run.author, run.code_commit) == ("Ada Lovelace ", "5d73e7c") + assert run.dataset == DatasetRef(uri="data/train.parquet", fingerprint=digest(data)) + assert run.lock_digest == digest(directory / "uv.lock") + assert run.environment == RunEnvironment(**ENVIRONMENT.model_dump()) + assert run.signature == RESULT.signature + assert run.trusted_types == ("sklearn.tree._tree.Tree",) + assert run.snapshot is not None + assert run.snapshot.key == f"snapshots/{run.snapshot.digest}.zip" + with zipfile.ZipFile(stored(stores, run.artifact, tmp_path / "model.zip")) as zipped: + assert zipped.read("model.skops") == b"a model" + log = stored(stores, run.log, tmp_path / "train.log") + assert log.read_text(encoding="utf-8") == "Training\n" + assert runner.jobs == [ + TrainJob( + model="model", + entrypoint="model.py:Churn", + task=Task.BINARY_CLASSIFICATION, + params={"n_estimators": 100}, + data=data.as_posix(), + target="target", + output="output", + seed=42, + ) + ] + assert shown == [ + f"Training churn 1.0.0 on data/train.parquet, seed 42, run {run.id}", + "Training", + ] + + +def test_the_runner_trains_a_copy_of_the_code_without_the_environment( + project: Project, stores: Stores +) -> None: + directory = project.root / "models" / "churn" + (directory / ".venv").mkdir() + (directory / ".venv" / "pyvenv.cfg").write_text("home = /usr/bin\n", encoding="utf-8") + before = sorted(directory.rglob("*")) + runner = FakeRunner() + + train(project, stores, runner) + + assert runner.code == [".python-version", "model.py", "model.toml", "pyproject.toml"] + assert sorted(directory.rglob("*")) == before + + +def test_data_and_a_seed_given_for_one_training_replace_those_of_model_toml( + project: Project, stores: Stores, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + (tmp_path / "elsewhere").mkdir() + DATA.write_parquet(tmp_path / "elsewhere" / "december.parquet") + monkeypatch.chdir(tmp_path / "elsewhere") + runner = FakeRunner() + + run = train(project, stores, runner, data=Path("december.parquet"), seed=7).run + + december = (tmp_path / "elsewhere" / "december.parquet").as_posix() + assert run.seed == runner.jobs[0].seed == 7 + assert run.dataset == DatasetRef(uri=december, fingerprint=digest(Path(december))) + assert runner.jobs[0].data == december + + +def test_a_model_directory_that_the_store_does_not_know_is_registered_first( + project: Project, +) -> None: + directory = project.root / "models" / "churn" + directory.mkdir(parents=True) + write_model_files(directory, "churn", "sklearn", Task.REGRESSION) + shown: list[str] = [] + + with open_stores(project) as stores: + done = train(project, stores, FakeRunner(), show=shown.append) + entry = find_model(stores.metadata, "churn") + + assert entry.model.task is Task.REGRESSION + assert entry.versions == [done.version] + assert shown[0] == f"Registered the model 'churn' from {directory} with the draft 1.0.0" + + +@pytest.mark.parametrize( + ("old", "new", "problem"), + [ + ( + "binary_classification", + "regression", + "has the flavor sklearn and the task regression, but the model 'churn' has the " + "flavor sklearn and the task binary_classification", + ), + ('name = "churn"', 'name = "fraud"', "names the model 'fraud', but its directory is"), + ("[train]", "[ignored]", "ignored: Extra inputs are not permitted"), + ('data = "data/train.parquet"\n', "", "There is no data to train on"), + ], +) +def test_a_model_toml_that_does_not_fit_is_refused_before_anything_is_recorded( + project: Project, stores: Stores, old: str, new: str, problem: str +) -> None: + edit(project.root / "models" / "churn" / "model.toml", old, new) + + with pytest.raises(ConfigError, match=problem): + train(project, stores, FakeRunner()) + + assert runs_of(stores) == [] + + +def test_a_model_toml_without_a_train_table_does_not_name_the_target( + project: Project, stores: Stores +) -> None: + model_toml = project.root / "models" / "churn" / "model.toml" + model_toml.write_text( + model_toml.read_text(encoding="utf-8").split("[train]")[0], encoding="utf-8" + ) + + with pytest.raises(ConfigError, match=r"has no \[train\] table"): + train(project, stores, FakeRunner()) + + +def test_data_that_is_not_there_is_not_found(project: Project, stores: Stores) -> None: + (project.root / "data" / "train.parquet").unlink() + + with pytest.raises(NotFoundError, match="There is no data file"): + train(project, stores, FakeRunner()) + with pytest.raises(NotFoundError, match="There is no data file"): + train(project, stores, FakeRunner(), data=project.root / "missing.parquet") + + assert runs_of(stores) == [] + + +def test_a_model_directory_that_is_not_there_is_not_found(project: Project, stores: Stores) -> None: + with pytest.raises(NotFoundError, match="There is no model directory"): + train_model( + stores.metadata, + stores.artifacts, + FakeRunner(), + project.root, + "fraud", + show=lambda line: None, + ) + + +@pytest.mark.parametrize( + ("failure", "error"), + [ + ( + Failure(type="DataError", message="The data has no rows.", reported=True), + "The data has no rows.", + ), + ( + Failure(type="ValueError", message="Input contains NaN.", reported=False), + "ValueError: Input contains NaN.", + ), + ], +) +def test_a_failed_training_is_recorded_with_its_reason( + project: Project, stores: Stores, failure: Failure, error: str +) -> None: + runner = FakeRunner(Result(environment=ENVIRONMENT, failure=failure)) + + with pytest.raises(TrainingError, match=rf"failed in run .+: {re.escape(error)}$"): + train(project, stores, runner) + + [run] = runs_of(stores) + assert (run.status, run.error) == (RunStatus.FAILED, error) + assert run.environment == RunEnvironment(**ENVIRONMENT.model_dump()) + assert (run.artifact, run.signature) == (None, None) + assert run.log is not None + + +class DamagingRunner(FakeRunner): + def run(self, job: Path, log: Path, show: Callable[[str], None]) -> int: + code = super().run(job, log, show) + (job.parent / "output" / "result.json").write_text("{", encoding="utf-8") + return code + + +@pytest.mark.parametrize( + ("runner", "problem"), + [ + (FakeRunner(result=None), "The runner ended with exit code 3 and left no result."), + (DamagingRunner(), "is not a result file of miniOPs"), + ], +) +def test_a_runner_that_leaves_no_result_that_can_be_read_has_failed( + project: Project, stores: Stores, runner: FakeRunner, problem: str +) -> None: + with pytest.raises(TrainingError, match=problem): + train(project, stores, runner) + + [run] = runs_of(stores) + assert run.status is RunStatus.FAILED + assert run.error is not None + assert problem in run.error + assert run.log is not None + + +def test_an_interrupted_training_is_recorded_as_interrupted( + project: Project, stores: Stores +) -> None: + with pytest.raises(KeyboardInterrupt): + train(project, stores, FakeRunner(error=KeyboardInterrupt())) + + [run] = runs_of(stores) + assert (run.status, run.error) == (RunStatus.INTERRUPTED, "The training was interrupted.") + assert run.finished_at is not None + assert run.log is not None + + +@pytest.mark.parametrize( + ("error", "message"), + [ + (OSError("python does not run: not found"), "python does not run: not found"), + (RuntimeError("the pipe broke"), "RuntimeError: the pipe broke"), + ], +) +def test_a_runner_that_breaks_fails_its_run( + project: Project, stores: Stores, error: Exception, message: str +) -> None: + with pytest.raises(type(error)): + train(project, stores, FakeRunner(error=error)) + + [run] = runs_of(stores) + assert (run.status, run.error) == (RunStatus.FAILED, message) + + +def test_a_model_that_cannot_be_stored_fails_its_run( + project: Project, stores: Stores, monkeypatch: pytest.MonkeyPatch +) -> None: + put = stores.artifacts.put + + def full(source: Path, key: str) -> ArtifactRef: + if key.endswith("model.zip"): + raise OSError(28, "No space left on device", str(source)) + return put(source, key) + + monkeypatch.setattr(stores.artifacts, "put", full) + + with pytest.raises(OSError, match="No space left on device"): + train(project, stores, FakeRunner()) + + [run] = runs_of(stores) + assert run.status is RunStatus.FAILED + assert run.error is not None + assert run.error.startswith("No space left on device: ") + assert run.log is not None + + +def test_the_same_code_is_stored_once(project: Project, stores: Stores) -> None: + first = train(project, stores, FakeRunner()).run + second = train(project, stores, FakeRunner()).run + + assert first.id != second.id + assert first.snapshot == second.snapshot + assert len(list((project.root / ".miniops" / "artifacts" / "snapshots").iterdir())) == 1 + + +@pytest.mark.parametrize( + ("name", "email", "author"), + [ + ("Ada", None, "Ada"), + (None, "ada@example.com", ""), + (None, None, None), + ], +) +def test_the_author_is_what_git_knows_of_one( + project: Project, + stores: Stores, + monkeypatch: pytest.MonkeyPatch, + name: str | None, + email: str | None, + author: str | None, +) -> None: + identity = {"user.name": name, "user.email": email} + monkeypatch.setattr(training, "find_tool", lambda tool: Path("/tools/git")) + monkeypatch.setattr(training, "git_config", lambda git, key: identity[key]) + monkeypatch.setattr(training, "git_commit", lambda git, directory: None) + + assert train(project, stores, FakeRunner()).run.author == author + + +def test_git_that_fails_leaves_the_run_without_an_author_and_a_commit( + project: Project, + stores: Stores, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + def broken(git: Path, key: str) -> str: + raise OSError("/tools/git did not answer within 10 seconds.") + + monkeypatch.setattr(training, "find_tool", lambda name: Path("/tools/git")) + monkeypatch.setattr(training, "git_config", broken) + + with caplog.at_level(logging.WARNING, logger="miniops"): + run = train(project, stores, FakeRunner()).run + + assert (run.author, run.code_commit) == (None, None) + assert "git did not tell the author and the commit of the run" in caplog.text + + +def test_a_model_without_exactly_one_draft_is_not_trained(project: Project, stores: Stores) -> None: + entry = find_model(stores.metadata, "churn") + second = ModelVersion( + id=uuid4(), + model_id=entry.model.id, + number=SemVer(2, 0, 0), + created_at=entry.model.created_at, + ) + stores.metadata.add_version(second) + + with pytest.raises(InvalidStateError, match=r"several drafts: 2\.0\.0, 1\.0\.0"): + train(project, stores, FakeRunner()) + + stores.metadata.delete_version(second.id) + stores.metadata.delete_version(entry.versions[0].id) + with pytest.raises(InvalidStateError, match="has no draft to train"): + train(project, stores, FakeRunner()) + + +def test_the_environment_is_synced_before_the_training( + project: Project, stores: Stores, monkeypatch: pytest.MonkeyPatch +) -> None: + events: list[str] = [] + + class Recording(FakeRunner): + def run(self, job: Path, log: Path, show: Callable[[str], None]) -> int: + events.append("train") + return super().run(job, log, show) + + def sync(directory: Path) -> None: + events.append(f"sync {directory.name}") + + monkeypatch.setattr(training, "sync_environment", sync) + + train(project, stores, Recording()) + + assert events == ["sync churn", "train"] + + +def test_what_trains_is_the_code_and_the_lock_as_they_are_after_the_sync( + project: Project, stores: Stores, monkeypatch: pytest.MonkeyPatch +) -> None: + directory = project.root / "models" / "churn" + + def sync(synced: Path) -> None: + edit(synced / "model.toml", "n_estimators = 100", "n_estimators = 7") + (synced / "uv.lock").write_text("version = 1\n", encoding="utf-8") + + monkeypatch.setattr(training, "sync_environment", sync) + runner = FakeRunner() + + run = train(project, stores, runner).run + + assert run.params == runner.jobs[0].params == {"n_estimators": 7} + assert run.lock_digest == digest(directory / "uv.lock") + + +def test_a_model_whose_environment_cannot_be_synced_is_not_trained( + project: Project, stores: Stores, monkeypatch: pytest.MonkeyPatch +) -> None: + def fail(directory: Path) -> None: + raise ToolError("uv was not found.") + + monkeypatch.setattr(training, "sync_environment", fail) + + with pytest.raises(ToolError, match="uv was not found"): + train(project, stores, FakeRunner()) + + assert runs_of(stores) == [] diff --git a/tests/runner/conftest.py b/tests/runner/conftest.py index a1373c1..4e5e68c 100644 --- a/tests/runner/conftest.py +++ b/tests/runner/conftest.py @@ -47,6 +47,7 @@ def make(**changes: object) -> Path: "data": "train.parquet", "target": "churned", "output": "output", + "seed": 0, } path = workdir / "job.json" write_job(TrainJob.model_validate(fields | changes), path) diff --git a/tests/runner/test_jobs.py b/tests/runner/test_jobs.py index 0e65a90..73a77a0 100644 --- a/tests/runner/test_jobs.py +++ b/tests/runner/test_jobs.py @@ -1,5 +1,6 @@ import logging import platform +import shutil from collections.abc import Callable from pathlib import Path @@ -143,15 +144,30 @@ def test_model_code_that_exits_has_failed(workdir: Path, make_job: Callable[..., ) -def test_the_traceback_of_a_failure_goes_to_the_log( - make_job: Callable[..., Path], caplog: pytest.LogCaptureFixture +@pytest.mark.parametrize( + ("changes", "message", "traceback"), + [ + ( + {"target": "spend"}, + "The training failed: The data has no target column 'spend'.", + False, + ), + ({"params": {"n_estimators": "many"}}, "The training failed", True), + ], +) +def test_only_an_unexpected_failure_leaves_its_traceback_in_the_log( + make_job: Callable[..., Path], + caplog: pytest.LogCaptureFixture, + changes: dict[str, object], + message: str, + traceback: bool, ) -> None: with caplog.at_level(logging.INFO, logger="miniops"): - run(make_job(target="spend")) + run(make_job(**changes)) [failure] = [record for record in caplog.records if record.levelno == logging.ERROR] - assert failure.getMessage() == "The training failed" - assert failure.exc_info is not None + assert failure.getMessage() == message + assert (failure.exc_info is not None) is traceback def test_the_model_can_import_its_own_modules(workdir: Path, make_job: Callable[..., Path]) -> None: @@ -166,6 +182,28 @@ def test_the_model_can_import_its_own_modules(workdir: Path, make_job: Callable[ assert run(make_job(params={})).failure is None +def test_the_seed_of_the_job_seeds_python_and_numpy( + workdir: Path, make_job: Callable[..., Path] +) -> None: + model = (workdir / "model.py").read_text(encoding="utf-8") + draw = ( + 'Path(__file__).with_name("drawn.txt").write_text(f"{random.random()} ' + '{numpy.random.random()}")\n return Pipeline(' + ) + (workdir / "model.py").write_text( + "import random\nfrom pathlib import Path\n\nimport numpy\n" + + model.replace("return Pipeline(", draw), + encoding="utf-8", + ) + + def drawn(seed: int) -> str: + shutil.rmtree(workdir / "output", ignore_errors=True) + assert run(make_job(seed=seed)).failure is None + return (workdir / "drawn.txt").read_text(encoding="utf-8") + + assert drawn(7) == drawn(7) != drawn(8) + + def test_the_output_of_an_earlier_job_is_left_alone( workdir: Path, make_job: Callable[..., Path] ) -> None: diff --git a/tests/runner/test_protocol.py b/tests/runner/test_protocol.py index f31eba8..4e64356 100644 --- a/tests/runner/test_protocol.py +++ b/tests/runner/test_protocol.py @@ -27,6 +27,7 @@ data="data/train.parquet", target="revenue", output="output", + seed=42, ) ENVIRONMENT = Environment(miniops="0.1.0", python="3.12.16", platform="Linux", machine="x86_64") @@ -56,6 +57,12 @@ def test_a_path_with_a_backslash_is_refused() -> None: TrainJob.model_validate(JOB.model_dump() | {"data": "data\\train.parquet"}) +@pytest.mark.parametrize("seed", [-1, 2**32]) +def test_a_seed_that_numpy_cannot_take_is_refused(seed: int) -> None: + with pytest.raises(ValidationError, match="seed"): + TrainJob.model_validate(JOB.model_dump() | {"seed": seed}) + + @pytest.mark.parametrize( "result", [ diff --git a/tests/templates/test_templates.py b/tests/templates/test_templates.py index 7321cbf..8eca6e0 100644 --- a/tests/templates/test_templates.py +++ b/tests/templates/test_templates.py @@ -11,7 +11,7 @@ from sklearn.preprocessing import StandardScaler from miniops import __version__, templates -from miniops.config.model import Flavor, load_model_config +from miniops.config.model import Flavor, TrainSection, load_model_config from miniops.core.entities import Task from miniops.core.errors import NotFoundError from miniops.flavors.sklearn import SklearnModel @@ -33,12 +33,14 @@ def model_class(directory: Path) -> type[SklearnModel]: def test_the_template_gives_a_model_config_that_is_valid(tmp_path: Path) -> None: write_model_files(tmp_path, "churn", "sklearn", Task.BINARY_CLASSIFICATION) - model = load_model_config(tmp_path).model + config = load_model_config(tmp_path) - assert model.name == "churn" - assert model.flavor is Flavor.SKLEARN - assert model.task is Task.BINARY_CLASSIFICATION - assert model.entrypoint == "model.py:Churn" + assert config.model.name == "churn" + assert config.model.flavor is Flavor.SKLEARN + assert config.model.task is Task.BINARY_CLASSIFICATION + assert config.model.entrypoint == "model.py:Churn" + assert config.train == TrainSection(data="data/train.parquet", target="target", seed=42) + assert config.params == {"n_estimators": 100} @pytest.mark.parametrize( diff --git a/tests/test_boundary.py b/tests/test_boundary.py index d9ce412..e83d551 100644 --- a/tests/test_boundary.py +++ b/tests/test_boundary.py @@ -31,3 +31,16 @@ def test_the_code_of_a_model_environment_imports_nothing_from_the_host() -> None assert {"miniops.flavors.sklearn", "miniops.runner.__main__"} <= imported assert imported - MODEL_SIDE == set() + + +def test_the_command_line_imports_no_library_for_data() -> None: + # The host is installed without the extras: data and models stay in the model environment. + script = ( + "import sys, miniops.cli; " + "print(*(name for name in ('numpy', 'polars', 'sklearn', 'skops') if name in sys.modules))" + ) + result = subprocess.run( + [sys.executable, "-c", script], capture_output=True, text=True, check=True + ) + + assert result.stdout.split() == [] diff --git a/tests/test_tools.py b/tests/test_tools.py index 76b4228..21eea23 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -1,5 +1,6 @@ import os import shutil +import subprocess import sys import time from pathlib import Path @@ -8,7 +9,7 @@ from miniops import tools from miniops.core.errors import ToolError -from miniops.tools import find_tool, git_config, run_tool, tool_version +from miniops.tools import find_tool, git_commit, git_config, run_tool, tool_version WINDOWS = sys.platform == "win32" @@ -181,3 +182,22 @@ def test_a_git_configuration_that_cannot_be_read_is_reported(git: Path, tmp_path with pytest.raises(OSError, match="exited with code"): git_config(git, "user.name") + + +def test_the_commit_of_a_repository_is_read( + git: Path, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("GIT_CEILING_DIRECTORIES", str(tmp_path)) + project = tmp_path / "project" + project.mkdir() + assert git_commit(git, project) is None + + subprocess.run([git, "-C", project, "init", "--quiet"], check=True) + assert git_commit(git, project) is None + + identity = ["-c", "user.name=Ada", "-c", "user.email=ada@example.com"] + commit: list[str | Path] = [git, "-C", project, *identity, "commit", "--allow-empty", "-m", "1"] + subprocess.run(commit, check=True, capture_output=True) + found = git_commit(git, project) + assert found is not None + assert len(found) == 40