Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 "$@"; }
Expand All @@ -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
Expand Down
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@ 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.
- A command that has a problem inside a project leaves its log in `.miniops/logs/miniops.log`: what it did and the error, with the full traceback when the error is a problem of the system or unexpected. A command without warnings or errors writes nothing there.
- 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 <name> --flavor sklearn --task <task>` creates a model in the project: the directory `models/<name>/` 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 <name>` finishes it.
- `miniops env sync <name>` creates or updates the environment of a model from its `pyproject.toml` and `uv.lock`.
- `miniops train <name>` 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 <model>` the versions of one model, and `miniops registry show <model> --version <number or alias>` 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.
Expand All @@ -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

Expand Down
49 changes: 49 additions & 0 deletions src/miniops/adapters/local/executor.py
Original file line number Diff line number Diff line change
@@ -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()
11 changes: 11 additions & 0 deletions src/miniops/adapters/local/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
Model,
ModelVersion,
Run,
RunEnvironment,
RunStatus,
Signature,
Task,
Expand Down Expand Up @@ -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,
}

Expand All @@ -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"],
)

Expand Down
9 changes: 9 additions & 0 deletions src/miniops/adapters/local/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -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;
""",
)


Expand Down
2 changes: 2 additions & 0 deletions src/miniops/cli/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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")
Expand Down
5 changes: 4 additions & 1 deletion src/miniops/cli/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
38 changes: 38 additions & 0 deletions src/miniops/cli/train.py
Original file line number Diff line number Diff line change
@@ -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}.")
15 changes: 14 additions & 1 deletion src/miniops/config/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
23 changes: 23 additions & 0 deletions src/miniops/core/entities.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -177,8 +187,15 @@ class Run:
snapshot: ArtifactRef | None = None
lock_digest: str | None = None
code_commit: str | None = None
# "Name <email>", 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

Expand All @@ -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.
Expand All @@ -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,
)

Expand Down
4 changes: 4 additions & 0 deletions src/miniops/core/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
38 changes: 31 additions & 7 deletions src/miniops/core/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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,
Expand Down
Loading
Loading