We are to design a model registry policy that enforces:
- Lineage: Tracking the entire lifecycle of a model from creation to deployment, including all stages (training, validation, etc.) and the artifacts used.
- Artifact immutability: Once an artifact (model, dataset, etc.) is registered, it cannot be changed. Any update must be a new version.
- Environment parity checks: Ensure that the environment (dependencies, configuration) in which the model was trained is the same (or compatible) with the environment in which it is deployed.
We assume we are building a policy for a model registry that is part of an MLOps platform (like MLflow, Kubeflow, etc.). The policy will be enforced by the registry when models are registered and when they are moved between stages (e.g., from staging to production).
We'll break down the policy into rules and then discuss how to implement them.
Proposed Policy:
-
Lineage:
- Every model artifact must be associated with a unique run ID (or experiment ID) that generated it.
- The model registry must record the entire DAG (Directed Acyclic Graph) of the run, including:
- Input datasets (with versions)
- Code version (git commit hash, or source code snapshot)
- Parameters used
- Metrics evaluated
- Artifacts produced (model, plots, etc.)
- When a model is registered, the registry must store the run ID and the DAG as part of the model's metadata.
-
Artifact Immutability:
- Once an artifact (model file, dataset, etc.) is registered in the model registry, it becomes read-only.
- The artifact is stored in a storage system (like S3, GCS, Azure Blob) with a content-addressable key (e.g., hash of the artifact) and the registry points to that key.
- If a new version of the model is to be registered, it must be treated as a new artifact. The old version remains unchanged.
- The model registry must not allow overwriting an existing artifact. Instead, it should create a new version (or a new registered model if the model is significantly different) and link the new artifact.
-
Environment Parity:
- The training environment (including OS, Python version, dependencies, and configuration) must be captured at training time.
- This can be done by:
- Recording the Docker image used for training.
- Recording the conda environment (or requirements.txt) and its hash.
- Recording any environment variables that might affect the model.
- When deploying the model, the deployment environment must be checked against the training environment (or a compatible environment) to avoid issues due to version mismatches.
- The registry should enforce that the deployment environment (or the environment specified in the deployment request) is either:
a) Exactly the same as the training environment (same image, same dependency versions), or
b) A compatible version (as defined by a policy, e.g., same major version of key libraries, same Python version) and the compatibility must be explicitly stated and approved (maybe by a human or an automated test).
Implementation:
We assume we have a model registry that supports:
- RegisteredModel: A named entity that groups model versions.
- ModelVersion: A version of a model, which points to an artifact (the model file) and has metadata.
Steps for registering a model:
- The training script (or pipeline) logs the model and all associated artifacts (datasets, code, etc.) to a tracking server (like MLflow).
- The tracking server records the run, including:
- Run ID
- Start/end time
- Source (git commit, script path)
- Parameters
- Metrics
- Tags
- Artifacts (with paths and possibly hashes)
- The user (or automated process) registers the model from the run to the model registry.
At registration time:
a) Lineage:
- The registry must store the run ID and the DAG (which can be reconstructed from the tracking server). Alternatively, the registry can store the entire run data (or a pointer to it) as part of the model version's description.
b) Artifact Immutability:
- The model artifact (and any other artifacts that are considered part of the model) must be stored in an immutable storage (like an S3 bucket with versioning and no delete, or a content-addressable store). The registry should verify that the artifact's hash matches what is recorded in the run.
- The registry should not allow two model versions to point to the same artifact (unless it's the same version of the same model). But note: two different runs might produce the same artifact (by hash) and that's acceptable.
c) Environment Parity:
- The run must have recorded the environment. In MLflow, this is done via mlflow.log_param or mlflow.log_artifact for environment files, or via the mlflow.projects run's conda_env or docker_image.
- The registry must check that the environment information (e.g., conda.yaml, requirements.txt, Docker image) is present and valid.
- When a model version is created, the environment information is stored as part of the model version's metadata.
Then, when moving the model version to a stage (e.g., "staging", "production"):
- The deployment system (or the registry) must verify that the target environment matches the training environment (or is compatible). This might be done by:
* The deployment system specifying the environment it will use (e.g., Docker image for the serving container).
* The registry comparing the training environment (from the model version) with the deployment environment (from the deployment request). If they are not exactly the same, the registry may require an approval step (via a webhook or manual approval) or an automated test (like a canary deployment) to ensure compatibility.
Additional considerations:
-
The policy should be enforced by the registry's API. For example:
- POST /registered-models -> creates a new registered model (if not exists) and then creates a model version from a run.
- PUT /model-versions/{version}/stage -> transitions the model version to a stage, and at that point, it checks environment parity if moving to a stage that requires production readiness.
-
We might want to have different levels of strictness for different stages. For example, moving to "staging" might only require that the environment is recorded, but moving to "production" requires exact match or approved compatibility.
-
The policy should be configurable per project or per model.
-
We must also consider that the environment might be captured in different ways (Docker, conda, etc.). The registry should support multiple environment types and have a way to compare them.
Example of environment comparison:
Training environment: Docker image `myimage:training-v1.2.3`
Deployment environment: Docker image `myimage:serving-v1.2.3`
These are not the same, but they might be built from the same base and have the same dependencies. How do we know? We might have a policy that says:
- The training and serving images must have the same `base_image` and the same version of the `mlflow` and `model_serving` packages.
But this is complex. Alternatively, we can require that the training and serving use the same Docker image (if we use Docker) or the same conda environment (if we use conda). This is simpler and more robust.
However, in practice, the serving environment might be optimized (e.g., with a different web server) and we might have a separate serving image. So we might have a policy that the serving image must be built FROM the training image, and then we can check that the training image is an ancestor of the serving image.
Alternatively, we can have a concept of "environment compatibility" that is defined by a separate service that can analyze two environments and determine if they are compatible (by comparing package versions). This is out of scope for the registry, but the registry can call such a service.
Given the complexity, a practical approach might be:
- For exact match: compare the environment specification (e.g., the conda.yaml file or the Docker image digest) for exact equality.
- For compatible match: we allow a specified tolerance (e.g., same major version for key packages) and we store the compatibility rule in the registry's configuration.
However, note that the registry should not be responsible for determining compatibility. Instead, we can have:
Option 1: The model version has a field `training_environment` and the deployment request has a field `deployment_environment`. The registry has a policy that says:
If stage == "production", then:
if `training_environment` != `deployment_environment`:
reject unless there is an approved compatibility record for these two environments.
Option 2: The model version has a field `compatible_environments` (a list of environment specifications that are known to be compatible). Then when deploying, we check if the deployment environment is in that list.
How do we get the compatible_environments list? It could be:
- Automatically generated by testing the model in the deployment environment (if it's the same as the training environment, then it's trivially compatible).
- Manually approved by an engineer who has tested the model in a different environment.
This is similar to how some MLOps platforms handle it (e.g., Seldon Core has a concept of "model graph" and "explainer" but not exactly this).
Given the scope, let's stick to a simpler version:
- The model version must store the exact training environment (as a string, e.g., the Docker image digest or the conda environment YAML string).
- When transitioning to a stage that requires production (like "production"), the deployment must specify the exact environment it will use (same format). The registry will check for exact match.
If the organization wants to allow compatible environments, they can have a policy that the deployment environment must be a specific image that is known to be compatible (and that image is built from the training image). Then the registry can be configured to allow that specific image for a given model version (maybe via a whitelist). But that whitelist would be per model version? That might be too manual.
Alternatively, we can have a global policy that says: for any model, the deployment environment must be the same as the training environment, unless there is an approved exception. The exception could be stored as part of the model version's metadata (a list of allowed deployment environments). Then when deploying, we check if the deployment environment is in that list.
How to approve an exception? We can have an API endpoint to add an allowed environment for a model version, and that endpoint requires a human approval (via a webhook or a manual step in the UI).
Given the complexity, let's break the policy into two parts:
Mandatory for all stages:
- Lineage and immutability.
For production stage:
- The deployment environment must exactly match the training environment, unless an exception has been registered for that model version.
The exception registration could be:
POST /model-versions/{version}/compatible-environments
Body: { "environment": "docker_image_digest" }
And then when moving to production, we check:
if deployment_environment == training_environment or deployment_environment in model_version.compatible_environments:
allow
else:
reject
But note: the compatible_environments are for a specific model version. And we might want to have a global policy that overrides per model? We can leave that as a configuration.
Alternatively, we can have a policy engine that is configurable. But for simplicity, we'll assume the above.
Implementation Steps:
-
When registering a model version from a run:
- Get the run from the tracking server.
- Extract the run's DAG (if available) or at least the run ID and the parent run IDs (if any) to reconstruct lineage.
- Get the model artifact (the actual model file) and compute its hash (if not already computed by the tracking server). Store the artifact in an immutable storage (with the hash as the key, for example).
- Record the run ID, the artifact hash, and the environment (from the run's
tags or params or artifacts).
Example of environment in MLflow:
- If using `mlflow.projects`, the run might have a tag `mlflow.project.entry_point` and `mlflow.project.uri` and `mlflow.project.git_commit` and `mlflow.docker_image` if using a Docker image.
- We can also log the conda environment as an artifact (conda.yaml) and then record the hash of that conda.yaml.
We decide to store:
- `training_environment_type`: e.g., "docker", "conda", "requirements"
- `training_environment_spec`: the exact specification (e.g., the Docker image digest, or the conda.yaml content string, or the requirements.txt content string)
We'll store the environment spec as a string and compute its hash for easy comparison? Or store the entire string and compare? We can store the string and then compare the strings for exact match.
However, note that the conda.yaml might have non-deterministic order? We should sort the keys? But conda environment files usually have a fixed order. To be safe, we can compute a hash of the sorted YAML (if it's YAML) and store the hash. But then we lose the ability to display the original. Alternatively, we store the original and the hash.
Let's store:
- `training_environment_hash`: the hash of the environment specification (normalized, e.g., sorted for YAML/JSON).
- `training_environment_spec`: the original specification (for display).
-
When moving a model version to a stage:
-
If the stage is one that requires production (configurable, but let's say "production" and "staging" are the ones that require environment check? Actually, we might only want to check for production. But let's say we have a set of stages that require environment check: production_stages = ["production"])
-
If the target stage is in production_stages:
a) Check that the model version has a training_environment_hash and training_environment_spec.
b) The deployment request must include a deployment_environment_spec (and maybe deployment_environment_hash). We compute the hash of the provided spec (normalized) and compare with the stored . If they match, allow.
Summary of the model version schema:
ModelVersion:
- version: string
- run_id: string (the run that produced this model)
- artifact_path: string (path in the registry's storage to the model artifact)
- artifact_hash: string (hash of the model artifact)
- training_environment_type: string (e.g., "docker", "conda")
- training_environment_hash: string (hash of the environment specification)
- training_environment_spec: string (the original environment specification)
- compatible_environments: list of {
environment_hash: string,
environment_spec: string,
approved_by: string,
approved_at: datetime
}
- lineage: we can store the run's DAG as a JSON string? Or we can store the run_id and then the registry can fetch the DAG from the tracking server when needed. But the registry should be independent of the tracking server? Not necessarily. In many systems, the model registry and the tracking server are the same (like MLflow). So we can assume we can fetch the run's data from the tracking server.
However, to be independent, we might want to store the minimal lineage in the registry:
- run_id
- parent_run_ids (if any)
- input_datasets: list of { dataset_name, version, hash }
- code_version: git commit hash
But note: the tracking server might have the full DAG. We can store the run_id and then when someone queries the model version, we can provide a link to the run in the tracking server. That might be acceptable.
Alternatively, we can store the entire DAG as a JSON in the model version's `description` or a dedicated field. But that might be too big.
Let's assume we store:
- run_id
- and then we have a separate service (or the same tracking server) that can reconstruct the DAG given the run_id.
So the lineage is enforced by requiring a run_id and by the fact that the run_id is immutable and points to a specific run in the tracking server.
Steps for the policy:
-
When creating a model version (from a run):
a) Check that the run exists and has a model artifact logged (typically in the run's artifacts, there is a model folder with a MLmodel file, or a specific model file).
b) Get the model artifact and compute its hash (if not already computed by the tracking server). The tracking server might already compute the hash when logging the artifact? In MLflow, when you log an artifact, it stores the file and you can get the artifact's URI, but not the hash by default. We might need to compute the hash ourselves or rely on the storage's content-addressable key.
c) Store the model artifact in the registry's immutable storage (if not already there) and record the artifact_hash.
d) Store the run_id.
e) Extract the environment from the run. In MLflow, we can look for:
- Tag: `mlflow.docker_image` if it's a Docker run.
- Artifact: `conda.yaml` if it's a conda environment.
- Param: `mlflow.project.conda_env` if using projects.
We can have a standard way: the training script must log the environment in a known way. For example:
mlflow.log_param("environment_type", "docker")
mlflow.log_param("environment_spec", "myimage:training-v1.2.3")
or
mlflow.log_artifact("conda.yaml", "environment")
Then we can define a convention: if there's an artifact named "environment/conda.yaml", then the environment type is "conda" and the spec is the content of conda.yaml.
We can also support multiple environment logs? But we need one primary environment for the training.
Let's decide: the run must have exactly one of the following:
- A tag `training_environment` with a JSON string that has `type` and `spec`? Or two tags: `training_environment_type` and `training_environment_spec`.
But that's error-prone.
Alternatively, we can have a standard artifact path: `environment/training_env.yaml` that contains:
type: docker
spec: myimage:training-v1.2.3
Then we can read that artifact and parse it.
Given the variety, we might leave it to the user to log the environment in a way we can parse, and we define a convention. Then we can write an extractor that tries multiple methods.
For simplicity, let's assume the run has a tag training_environment that is a JSON string with:
{
"type": "docker" | "conda" | "requirements",
"spec": <string> # the Docker image, or the conda.yaml content, or the requirements.txt content
}
Then we compute the hash of the spec string (after normalizing: for conda and requirements, we might sort the lines? For Docker, the spec is the image name and tag, but note that the same image can have multiple tags. We should use the image digest if possible?).
Actually, for Docker, the image digest is the content hash. So we should use the image digest. But when building the image, we might tag it. How do we get the digest? We can have the training script pass the image digest as the spec.
Let's go with that.
Steps for model version creation:
Given a run_id:
1. Get the run from the tracking server.
2. Check for environment:
if run has artifact "environment/conda.yaml":
type = "conda"
spec = read the artifact content (as string)
elif run has artifact "environment/requirements.txt":
type = "requirements"
spec = read the artifact content (as string)
elif run has tag "mlflow.docker_image":
type = "docker"
spec = tag value (string)
else:
raise Error("Training environment not found")
3. Compute hash = sha256(spec.encode()).hexdigest()
4. Get the model artifact (we assume the run has a model logged in a known way, e.g., in MLflow, the model is logged as an artifact in a folder named "model". We can look for an artifact that is a model? Actually, in MLflow, when you log a model with `mlflow.<flavor>.log_model`, it creates a folder with a MLmodel file. We can require that the run has an artifact that is a model. We can have a convention: the model artifact is logged at path "model". Then we get the artifact URI for "model".
5. We then store the model artifact in the registry's storage. We can:
- If the registry's storage is the same as the tracking server's artifact storage, we can just copy the artifact? But we want immutability. We can store the artifact in a content-addressable way: the key is the artifact_hash. But we just computed the environment_hash, not the artifact_hash.
We need to compute the hash of the model artifact. We can:
- Download the model artifact (the entire folder? or a specific file?) and compute a hash of the entire model (maybe by hashing the entire folder as a tarball?).
But note: the model might be a directory (with multiple files). We can:
- Create a tarball of the model directory and hash that? Or we can hash each file and then combine? But then two different sets of files that produce the same hash? We want to uniquely identify the model.
Alternatively, we can rely on the tracking server to provide the artifact's hash? MLflow doesn't provide that by default.
We can:
- When the model is logged, we compute the hash of the model directory (by creating a tarball and hashing it) and store that hash as a tag in the run? Then we can read it.
But we are in the registry now. We have the artifact URI (which might be a local path or an S3 path). We can compute the hash by reading all the files and hashing their contents in a deterministic order (by file path). But that might be expensive for large models.
Alternatively, we can store the model artifact without hashing it, and then use the storage's content-addressable key? For example, if we store the model in S3, we can use the ETag (which is the MD5 of the file) for each file? But for a directory, we don't have a single ETag.
Given the complexity, let's assume:
- The model is stored as a single file (like a .pkl, .onnx, .h5, etc.). Then we can compute the hash of that file.
But what if it's a directory? We can require that the model is a single file? Or we can compute the hash of the entire directory by:
1. List all files in the directory (recursively).
2. Sort the file paths.
3. For each file, read its content and hash it? Then combine the hashes? That's not standard.
Alternatively, we can create a tarball of the directory and hash the tarball. That gives a single hash for the entire model.
We can do:
If the model artifact is a directory:
tar -czf - model_dir | sha256sum
If it's a file:
sha256sum model_file
But note: the tarball might include metadata (like timestamps) that change. We must create a reproducible tarball (without timestamps, etc.). We can use `tar --sort=name --mtime='1970-01-01' --owner=0 --group=0 -czf - model_dir` to create a deterministic tarball.
This is complex.
Given the time, let's assume the model artifact is a single file. Then we can compute the hash of that file.
Steps:
- Get the artifact URI (from the run's artifacts, we look for the model artifact by a known path, e.g., "model" and then if it's a directory, we look for a specific file inside? That's not general.
Alternatively, we can rely on the MLmodel file (if using MLflow) to specify the model's flavor and the path to the model file. Then we can get the model file path from the MLmodel file.
But again, we are tying to MLflow.
Given the complexity, let's change the requirement:
The model artifact must be a single file. Then we can compute the hash of that file.
How do we get the model file?
- The run must have logged a model using `mlflow.<flavor>.log_model`. This creates an artifact directory with an MLmodel file and the model file(s). We can require that the model is logged in a way that the main model file is at a fixed path? Not necessarily.
We can have:
- The run must have an artifact that is a model (we can check by looking for an MLmodel file). Then the model files are in the same directory. We can compute the hash of the entire directory (by tarballing) but that's heavy.
Given the trade-offs, let's assume we are using MLflow and the model is stored in a directory. We'll compute the hash of the entire model directory by:
- Listing all files in the directory (relative to the model directory) and sorting by path.
- For each file, read its content and compute a hash (e.g., SHA256) of the content.
- Then combine the file hashes in order (by concatenating the hashes) and hash that? That's not standard.
Alternatively, we can compute the hash of the tarball of the model directory (with deterministic tarball as above). We'll do that.
Steps for computing the model artifact hash:
Let model_artifact_uri = the URI of the model directory (from the run's artifacts, we get the URI for the artifact path "model").
Then:
if model_artifact_uri is a local directory:
create a deterministic tarball and compute its SHA256.
if it's on S3:
download the entire directory (or list the files and download each) and then do the same? That's expensive.
Given the complexity, we might want to avoid hashing the model artifact at registration time. Instead, we can rely on the storage's content-addressable key. For example, if we store the model artifact in S3, we can use the S3 object's ETag (which for a single file is the MD5). But for a directory, we don't have a single ETag.
Another idea: we can compute the hash when the model is logged (during training) and store that hash as a tag in the run. Then we just read that tag.
So we change the training script to:
# after logging the model
model_uri = mlflow.get_artifact_uri("model")
# compute the hash of the model directory (or file) and log it as a tag
hash = compute_hash(model_uri)
mlflow.set_tag("model_hash", hash)
Then in the registry, we read the tag "model_hash". That's easy.
But what if the user doesn't set that tag? We can require it.
So we require that the run has a tag "model_hash" that is the SHA256 hash of the model artifact (computed in a deterministic way, as above). Then we use that as the artifact_hash.
And we also require that the model artifact is stored in an immutable storage (so that the hash cannot change). But the hash is of the content, so if the content changes, the hash changes. And we are storing the model artifact in the tracking server's artifact store, which might be mutable. We want the registry to store the artifact in an immutable store? Or we can rely on the tracking server to keep the artifact immutable? In MLflow, artifacts are immutable once logged (you cannot overwrite, you can only delete and log again, but then the run is fixed). So the artifact for a given run is immutable.
So we can:
- Use the run's artifact store as the source of truth for the model artifact.
- The registry stores the run_id and the model_hash (from the tag) and the model artifact URI (from the run's artifact path).
Then when we need the model artifact, we can get it from the tracking server.
But note: the model registry might be separate from the tracking server. Then we need to copy the artifact to the registry's storage? Or we can just reference the tracking server's artifact.
We can do:
The model version stores:
run_id: string
model_artifact_uri: string (from the run's artifact URI for the model)
model_hash: string (from the run's tag)
Then when deploying, we can fetch the model from the model_artifact_uri.
But then we are not enforcing immutability at the registry level? The artifact is stored in the tracking server, which might have retention policies and might delete runs. So we want the registry to have its own copy? That's a design decision.
In MLflow, the model registry and tracking server are the same, so the artifact is stored in the same place.
If we are building a separate registry, we might want to copy the artifact to the registry's own storage to ensure immutability and independence.
Given the complexity, let's assume the registry and tracking server are integrated (like MLflow). Then we don't need to copy the artifact. We just store the run_id and the model artifact path.
Then the artifact immutability is enforced by the tracking server (which does not allow modifying artifacts of a run).
So we change:
We don't store the artifact_hash? We store the model_artifact_uri and the run_id. Then we can compute the hash of the artifact from the run? But we don't want to compute it every time.
Alternatively, we store the model_hash (from the tag) and we verify that the artifact at the model_artifact_uri has that hash when we register. Then we know it's correct.
Steps:
- When registering, we read the model_artifact_uri and the model_hash (from the tag). We compute the hash of the artifact at that URI and compare with the tag. If they match, we store the model_hash and the model_artifact_uri.
Then we have:
model_version:
run_id: ...
model_artifact_uri: ...
model_hash: ...
training_environment_type: ...
training_environment_hash: ...
And we enforce:
- The model_artifact_uri must point to an artifact that exists and has the hash equal to model_hash.
Then, when moving to production, we don't need the model_hash for the environment check? We need the training_environment_hash.
So the model_hash is for verifying the model artifact integrity at registration time.
We can skip storing the model_hash if we trust the tracking server. But we want to enforce that the artifact is immutable. The tracking server ensures that the artifact for a run doesn't change. So we don't need to store the hash? We can just store the run_id and the model_artifact_uri, and then when we need the model, we get it from the run.
But then if the tracking server deletes the run, the model is gone. So we might want to have a copy in the registry.
Given the time, let's stick to:
The registry stores:
run_id
model_artifact_uri (relative to the tracking server's artifact root? or absolute?)
training_environment_type
training_environment_hash
And we trust the tracking server to keep the artifact immutable and available.
Then the artifact immutability is enforced by the tracking server (which doesn't allow modifying artifacts of a run) and by the fact that we never change the model_artifact_uri for a given model version.
And the lineage is enforced by the run_id and the tracking server's DAG.
And the environment parity is enforced by the training_environment_hash and the compatible_environments.
This is simpler.
Final Design:
ModelVersion:
version: string
run_id: string
model_artifact_uri: string # e.g., "s3://bucket/path/to/model"
training_environment_type: string
training_environment_hash: string
compatible_environments: list of {
environment_hash: string,
environment_spec: string,
environment_type: string,
approved_by: string,
approved_at: datetime
}
Steps for creating a model version:
1. Given a run_id, get the run from the tracking server.
2. Verify the run has a model artifact (by looking for an artifact with a path that contains an MLmodel file? Or by a tag?).
We can assume the run has logged a model with `mlflow.log_model` and the artifact path is "model".
Then the model_artifact_uri = run.info.artifact_uri + "/model"
3. Determine the training environment:
a) Check for artifact "environment/conda.yaml": if exists, type="conda", spec=content of that artifact.
b) Else, check for artifact "environment/requirements.txt": type="requirements", spec=content.
c) Else, check for tag "mlflow.docker_image": type="docker", spec=tag value.
d) Else, error.
Then compute training_environment_hash = sha256(spec.encode()).hexdigest()
4. Store the model version with:
run_id = run_id
model_artifact_uri = model_artifact_uri (from step 2)
training_environment_type = type
training_environment_hash = hash
5. The model version is created in the registry.
Steps for transitioning a model version to a stage (with environment check for production):
1. The transition request includes:
{
"stage": "production",
"deployment_environment": {
"type": "docker",
"spec": "myimage:serving-v1.2.3"
}
}
2. If the stage is in the list of stages that require environment check (we'll assume only "production" for now), then:
a) Compute the hash of the deployment_environment_spec (the raw string) as:
deployment_environment_hash = sha256(deployment_environment_spec.encode()).hexdigest()
b) Check if:
deployment_environment_hash == model_version.training_environment_hash
OR
deployment_environment_hash in [env.environment_hash for env in model_version.compatible_environments]
c) If yes, allow the transition. If not, reject.
3. If the stage is not in the list, allow without check.
Steps for adding a compatible environment:
POST /model-versions/{version}/compatible-environments
Body:
{
"environment_type": "docker",
"environment_spec": "myimage:serving-v1.2.3"
}
Then:
Compute hash of the environment_spec.
Check that the hash is not already in the model_version.compatible_environments (to avoid duplicates).
Add a new compatible environment record with:
environment_hash: hash
environment_spec: spec
environment_type: type
approved_by: current user (from authentication)
approved_at: now
This endpoint should be accessible only to users with approval permission.
This design:
- Enforces lineage by requiring a run_id and storing the model_artifact_uri (which is tied to the run). The full DAG can be retrieved from the tracking server using the run_id.
- Enforces artifact immutability by not allowing changes to the model_artifact_uri for a model version. The model artifact itself is stored in the tracking server's artifact store, which is immutable for a given run.
- Enforces environment parity by checking the training environment against the deployment environment (exact match or approved compatible).
Note: We are not storing the entire environment spec for the training environment? We are storing the training_environment_hash and training_environment_type, but not the spec? We might want to store the spec for display. Let's store:
training_environment_spec: string
Similarly for compatible environments, we store the spec.
So:
ModelVersion:
...
training_environment_type: string
training_environment_spec: string
training_environment_hash: string
compatible_environments: list of { environment_type, environment_spec, environment_hash, approved_by, approved_at }
Then when we check, we use the hash for comparison, but we store the spec for display.
We compute the hash from the spec.
Implementation:
We'll assume we have a function:
def compute_hash(spec: str) -> str:
return hashlib.sha256(spec.encode()).hexdigest()
And we store the spec and the hash.
Edge Cases:
- What if the training environment is not found? We reject the model version creation.
- What if the deployment environment is not provided? We reject the transition to production (if it requires environment check).
- What if the model version doesn't have a training environment? That should not happen because we required it at creation.
- What if the compatible_environments list is huge? We can store it in a separate table and just reference by model_version_id.
This is a basic design. We can extend it with:
- More environment types.
- Normalization of the spec (so that two semantically equivalent specs produce the same hash). But that's complex.
Given the time, we'll leave it as exact string match.
Let's write the policy in a formal way:
Policy:
Rule 1 (Lineage): Every model version must be associated with a run in the tracking server. The run_id must be provided and must exist. The model artifact must be stored in the tracking server's artifact store at a fixed path (e.g., "model") relative to the run's artifact URI.
Rule 2 (Artifact Immutability): The model artifact (the content at the model_artifact_uri) must remain unchanged for the lifetime of the model version. The registry does not allow updating the model_artifact_uri for an existing model version. Any update must create a new model version.
Rule 3 (Environment Parity): When transitioning a model version to a stage that requires production (as configured), the deployment environment must be provided. The deployment environment must be exactly the same as the training environment (same type and same spec, meaning same hash) or be one of the approved compatible environments for that model version.
Configuration:
- stages_requiring_environment_check: list of stages (default: ["production"])
Implementation:
We'll implement two main functions:
create_model_version(run_id: str) -> ModelVersion:
# Check run exists and has model artifact at "model"
# Determine training environment from run
# Compute hash of training_environment_spec
# Create and return ModelVersion
transition_model_version(model_version_id: str, stage: str, deployment_environment: Optional[dict]) -> None:
# If stage in stages_requiring_environment_check:
# If deployment_environment is None: error
# Compute hash of deployment_environment_spec
# Check if hash matches training_environment_hash or is in compatible_environments hashes
# If not, error
# Update the stage of the model version
add_compatible_environment(model_version_id: str, environment_type: str, environment_spec: str) -> None:
# Compute hash of environment_spec
# Check if hash already exists in compatible_environments for this model version
# If not, add a new compatible environment record
We assume the ModelVersion and compatible_environments are stored in a database.
This is a solid design that meets the requirements.
However, note: the training environment might be stored in a different way (not as an artifact or tag). We are making assumptions about MLflow. If we are designing a generic policy, we might need to support other tracking systems. But since the policy is for a specific registry (which might be built on top of a tracking system), we can adapt.
We can make the environment detection pluggable? But that's over-engineering.
Given the instructions, we are engineering a policy for a model registry. We can assume the registry is built on top of a tracking system that can run arbitrary code to extract the environment. We have defined a convention (artifacts or tags). We can extend the convention by configuration.
But for now, we'll stick to the convention.
Let's write the policy in a markdown format for documentation.
Note: This is a design document. The actual implementation will depend on the existing system.
We'll also consider:
- The training environment might be stored in multiple ways (e.g., both a conda.yaml and a Docker image). We take the first one we find? Or we require exactly one? We should require exactly one to avoid ambiguity.
So we check for one and only one of the three. If more than one is found, error.
Final steps for environment detection:
has_conda = run has artifact "environment/conda.yaml"
has_requirements = run has artifact "environment/requirements.txt"
has_docker = run has tag "mlflow.docker_image"
if sum([has_conda, has_requirements, has_docker]) != 1:
error("Exactly one of conda.yaml, requirements.txt, or mlflow.docker_image must be present")
then set type and spec accordingly.
This is the policy.
I'll design a comprehensive model registry policy that enforces lineage tracking, artifact immutability, and environment parity checks. Here's a complete implementation strategy:
Model Registry Policy Specification
1. Core Principles
- Lineage: Complete traceability from model creation to deployment
- Immutability: All artifacts are write-once, read-many
- Parity: Training and serving environments must be compatible
2. Policy Implementation
from datetime import datetime
from typing import Dict, List, Optional, Any
from dataclasses import dataclass, field
from enum import Enum
import hashlib
import json
class Stage(Enum):
STAGING = "staging"
PRODUCTION = "production"
ARCHIVED = "archived"
class EnvironmentType(Enum):
DOCKER = "docker"
CONDA = "conda"
PYTHON = "python"
VIRTUALENV = "virtualenv"
@dataclass
class Environment:
"""Immutable environment specification"""
type: EnvironmentType
spec_hash: str # SHA256 of environment specification
spec_content: str # Actual environment file content (dockerfile/conda.yml/requirements.txt)
base_image: Optional[str] = None
python_version: Optional[str] = None
dependencies: Dict[str, str] = field(default_factory=dict)
@classmethod
def from_spec(cls, env_type: EnvironmentType, spec_content: str) -> 'Environment':
"""Create environment from specification"""
spec_hash = hashlib.sha256(spec_content.encode()).hexdigest()
# Parse dependencies based on type
if env_type == EnvironmentType.CONDA:
# Parse conda.yml
dependencies = parse_conda_deps(spec_content)
elif env_type == EnvironmentType.PYTHON:
# Parse requirements.txt
dependencies = parse_requirements(spec_content)
else:
dependencies = {}
return cls(
type=env_type,
spec_hash=spec_hash,
spec_content=spec_content,
dependencies=dependencies
)
def is_compatible_with(self, other: 'Environment') -> bool:
"""Check environment compatibility"""
if self.type != other.type:
return False
# Exact match
if self.spec_hash == other.spec_hash:
return True
# Semantic version compatibility check
if self.type == EnvironmentType.PYTHON:
return self._check_python_compatibility(other)
elif self.type == EnvironmentType.CONDA:
return self._check_conda_compatibility(other)
return False
def _check_python_compatibility(self, other: 'Environment') -> bool:
"""Check Python package compatibility"""
for pkg, version in self.dependencies.items():
other_version = other.dependencies.get(pkg)
if other_version and not versions_compatible(version, other_version):
return False
return True
@dataclass
class LineageNode:
"""Node in lineage DAG"""
id: str
type: str # "dataset", "model", "code", "parameter"
uri: str
hash: str
metadata: Dict[str, Any] = field(default_factory=dict)
parent_ids: List[str] = field(default_factory=list)
created_at: datetime = field(default_factory=datetime.utcnow)
@dataclass
class ModelVersion:
"""Immutable model version"""
id: str
name: str
version: int
artifact_uri: str # Immutable storage location
artifact_hash: str # Content-addressable hash
stage: Stage
environment: Environment
lineage: List[LineageNode] = field(default_factory=list)
created_by: str
created_at: datetime = field(default_factory=datetime.utcnow)
tags: Dict[str, str] = field(default_factory=dict)
def validate_stage_transition(self, target_stage: Stage,
deployment_environment: Optional[Environment] = None) -> List[str]:
"""Validate stage transition against policy"""
errors = []
# 1. Lineage completeness check
if not self._has_complete_lineage():
errors.append("Incomplete lineage: missing training dataset or code reference")
# 2. Environment parity check for production
if target_stage == Stage.PRODUCTION:
if not deployment_environment:
errors.append("Deployment environment required for production promotion")
elif not self.environment.is_compatible_with(deployment_environment):
errors.append(
f"Environment mismatch: training={self.environment.spec_hash[:8]} "
f"deployment={deployment_environment.spec_hash[:8]}"
)
# 3. Artifact integrity check
current_hash = self._compute_artifact_hash()
if current_hash != self.artifact_hash:
errors.append("Artifact integrity check failed - content modified")
return errors
def _has_complete_lineage(self) -> bool:
"""Verify we have training dataset and code"""
node_types = {node.type for node in self.lineage}
return "dataset" in node_types and "code" in node_types
def _compute_artifact_hash(self) -> str:
"""Compute current artifact hash (for integrity check)"""
# Implementation would read from storage
return "" # Placeholder
class ModelRegistry:
"""Model registry enforcing policy"""
def __init__(self, storage_backend: 'ImmutableStorage'):
self.storage = storage_backend
self.models: Dict[str, ModelVersion] = {}
self.lineage_graph: Dict[str, LineageNode] = {}
self.stage_transition_approvers = ["ml-engineer", "mleads"]
def register_model(self,
name: str,
artifact_path: str,
environment: Environment,
lineage_nodes: List[LineageNode],
created_by: str,
tags: Dict[str, str] = None) -> ModelVersion:
"""Register new model version (immutable operation)"""
# 1. Verify artifact exists in immutable storage
if not self.storage.verify_immutable(artifact_path):
raise ValueError("Artifact not in immutable storage")
# 2. Compute artifact hash
artifact_hash = self.storage.compute_hash(artifact_path)
# 3. Check for duplicate artifact (same content)
existing = self._find_by_artifact_hash(artifact_hash)
if existing:
raise ValueError(f"Artifact already registered as {existing.name} v{existing.version}")
# 4. Validate lineage completeness
self._validate_lineage(lineage_nodes)
# 5. Store lineage nodes
for node in lineage_nodes:
self.lineage_graph[node.id] = node
# 6. Create model version
version_num = self._next_version(name)
model_version = ModelVersion(
id=f"{name}:{version_num}",
name=name,
version=version_num,
artifact_uri=artifact_path,
artifact_hash=artifact_hash,
stage=Stage.STAGING,
environment=environment,
lineage=lineage_nodes,
created_by=created_by,
tags=tags or {}
)
self.models[model_version.id] = model_version
return model_version
def transition_stage(self,
model_version_id: str,
target_stage: Stage,
approver: str,
deployment_environment: Optional[Environment] = None,
justification: str = None) -> bool:
"""Transition model to new stage with policy checks"""
model = self.models.get(model_version_id)
if not model:
raise ValueError(f"Model {model_version_id} not found")
# 1. Check approval permissions
if approver not in self.stage_transition_approvers:
raise PermissionError(f"{approver} not authorized for stage transitions")
# 2. Run policy validation
errors = model.validate_stage_transition(target_stage, deployment_environment)
if errors:
raise PolicyViolationError(
f"Policy violation for {model_version_id} -> {target_stage}: {', '.join(errors)}"
)
# 3. Record transition with audit log
self._log_transition(model_version_id, target_stage, approver, justification)
# 4. Update stage
model.stage = target_stage
return True
def add_compatible_environment(self,
model_version_id: str,
compatible_env: Environment,
approver: str,
reason: str) -> None:
"""Register a compatible environment for a model"""
model = self.models.get(model_version_id)
if not model:
raise ValueError(f"Model {model_version_id} not found")
# Check if environment is truly compatible by testing
if not self._test_environment_compatibility(model, compatible_env):
raise ValueError("Environment compatibility test failed")
# Add to model's compatible environments
model.tags[f"compatible_env_{compatible_env.spec_hash[:8]}"] = json.dumps({
"type": compatible_env.type.value,
"hash": compatible_env.spec_hash,
"approved_by": approver,
"reason": reason,
"approved_at": datetime.utcnow().isoformat()
})
def _validate_lineage(self, lineage_nodes: List[LineageNode]) -> None:
"""Ensure lineage is complete and valid"""
node_map = {node.id: node for node in lineage_nodes}
# Check for cycles
visited = set()
def has_cycle(node_id: str, path: List[str]) -> bool:
if node_id in path:
return True
if node_id in visited:
return False
visited.add(node_id)
node = node_map.get(node_id)
if not node:
return False
for parent_id in node.parent_ids:
if has_cycle(parent_id, path + [node_id]):
return True
return False
for node in lineage_nodes:
if has_cycle(node.id, []):
raise ValueError("Lineage contains cycle")
# ... additional helper methods ...
class ImmutableStorage:
"""Abstract immutable storage backend"""
def verify_immutable(self, uri: str) -> bool:
"""Verify artifact is in immutable storage"""
raise NotImplementedError
def compute_hash(self, uri: str) -> str:
"""Compute SHA256 hash of artifact"""
raise NotImplementedError
def prevent_modification(self, uri: str) -> None:
"""Ensure artifact cannot be modified"""
raise NotImplementedError
# Example implementation for S3 with Object Lock
class S3ImmutableStorage(ImmutableStorage):
def __init__(self, bucket: str):
self.bucket = bucket
def verify_immutable(self, uri: str) -> bool:
# Check S3 object lock configuration
# Verify object hasn't been modified since creation
return True
def compute_hash(self, uri: str) -> str:
# Read object and compute SHA256
return "abc123..."
# Policy Enforcement Decorator
def enforce_policy(func):
"""Decorator to enforce registry policy on operations"""
def wrapper(self, *args, **kwargs):
# Pre-checks
self._check_operation_allowed(func.__name__, *args, **kwargs)
result = func(self, *args, **kwargs)
# Post-checks
self._audit_log(func.__name__, *args, **kwargs)
return result
return wrapper
# Usage Example
if __name__ == "__main__":
# Initialize registry
storage = S3ImmutableStorage("ml-artifacts-bucket")
registry = ModelRegistry(storage)
# Create environment
training_env = Environment.from_spec(
EnvironmentType.CONDA,
"""name: my_model
channels:
- conda-forge
dependencies:
- python=3.9
- numpy=1.21.0
- pandas=1.3.0
- scikit-learn=0.24.2
"""
)
# Create lineage
lineage = [
LineageNode(
id="dataset-123",
type="dataset",
uri="s3://ml-datasets/training/v1/data.parquet",
hash="sha256:dataset_hash",
metadata={"version": "v1", "rows": 10000}
),
LineageNode(
id="code-456",
type="code",
uri="github://myorg/ml-pipeline/train.py@abc123",
hash="sha256:code_hash",
parent_ids=["dataset-123"]
)
]
# Register model
model = registry.register_model(
name="churn-predictor",
artifact_path="s3://ml-artifacts-bucket/models/churn/v1/model.pkl",
environment=training_env,
lineage_nodes=lineage,
created_by="data-scientist-1",
tags={"team": "customer-success", "algorithm": "xgboost"}
)
print(f"Registered: {model.id} (stage: {model.stage.value})")
# Try to move to production
try:
deployment_env = Environment.from_spec(
EnvironmentType.CONDA,
"""name: serving
channels:
- conda-forge
dependencies:
- python=3.9
- numpy=1.21.0
- pandas=1.3.0
- scikit-learn=0.24.2
- fastapi=0.70.0
"""
)
registry.transition_stage(
model_version_id=model.id,
target_stage=Stage.PRODUCTION,
approver="ml-engineer",
deployment_environment=deployment_env,
justification="Passed all staging tests"
)
print(f"Promoted {model.id} to production")
except PolicyViolationError as e:
print(f"Policy violation: {e}")
3. Policy Rules Summary
| Rule | Enforcement Point | Description |
|---|
| Lineage Completeness | Registration | Must include training dataset and code references |
| Artifact Immutability | Storage layer | Write-once storage, content-addressable hashing |
| Environment Parity | Stage transition (Production) | Exact match or semantic compatibility check |
| No Overwrites | Registration | Duplicate artifact hash rejected |
| Audit Trail | All operations | Who/when/why recorded |
| Approval Workflow | Production promotion | Requires authorized approver |
4. Deployment Considerations
Storage Configuration
immutable_storage:
type: s3 # or gcs, azure
bucket: ml-registry-artifacts
object_lock: true
retention_days: 365 # Compliance retention
lineage_storage:
type: neo4j # Graph database for lineage DAG
or:
type: relational # With recursive CTEs
audit_log:
type: elasticsearch
retention: 7_years
CI/CD Integration
# .mlci/policy-enforcer.yml
policies:
- name: environment_parity
trigger: stage_transition
stages: [production]
check: environment_compatibility
allowed_mismatch: 0 # 0% version drift allowed
- name: lineage_completeness
trigger: registration
required_nodes: [dataset, code, parameters]
- name: artifact_immutability
trigger: all
storage_type: content_addressable
reject_on_hash_mismatch: true
5. Monitoring & Alerts
class PolicyMonitor:
def __init__(self, registry: ModelRegistry):
self.registry = registry
def check_production_drift(self) -> Dict[str, Any]:
"""Check for environment drift in production models"""
drift_models = []
for model in self.registry.models.values():
if model.stage == Stage.PRODUCTION:
# Compare with current deployment environment
current_deploy_env = self._get_deployment_env(model)
if not model.environment.is_compatible_with(current_deploy_env):
drift_models.append({
"model": model.id,
"training_env": model.environment.spec_hash[:8],
"deployment_env": current_deploy_env.spec_hash[:8],
"severity": "HIGH"
})
return {"drift_count": len(drift_models), "models": drift_models}
6. Compliance Reports
def generate_compliance_report(registry: ModelRegistry) -> str:
"""Generate compliance report for auditors"""
report = []
report.append("=== Model Registry Compliance Report ===\n")
# Lineage completeness
incomplete = [m for m in registry.models.values()
if not m._has_complete_lineage()]
report.append(f"1. Lineage completeness: {len(incomplete)} incomplete\n")
# Immutability checks
modified = []
for model in registry.models.values():
if model._compute_artifact_hash() != model.artifact_hash:
modified.append(model.id)
report.append(f"2. Artifact integrity: {len(modified)} modified\n")
# Environment parity
prod_models = [m for m in registry.models.values()
if m.stage == Stage.PRODUCTION]
report.append(f"3. Production models: {len(prod_models)}\n")
return "\n".join(report)
7. Key Implementation Notes
- Immutable Storage: Use S3 Object Lock, GCS Object Versioning, or content-addressable storage (IPFS/CAS)
- Lineage Graph: Store in graph database (Neo4j) or use recursive CTEs in relational DB
- Hash Computation: SHA-256 for all artifacts, normalized (sorted keys for dicts)
- Environment Compatibility:
- Exact match:
spec_hash equality
- Semantic compatibility: Package version constraints (using
packaging.version)
- Allowlist mechanism for approved exceptions
- Audit Requirements: All transitions logged with user, timestamp, justification
8. Exception Handling
class PolicyViolationError(Exception):
"""Raised when policy violation prevents operation"""
pass
class IncompleteLineageError(PolicyViolationError):
pass
class EnvironmentMismatchError(PolicyViolationError):
pass
class ArtifactModifiedError(PolicyViolationError):
pass
This policy provides:
- Strong guarantees through immutable storage and content addressing
- Flexible compatibility with semantic version checking
- Complete audit trail for compliance
- Graph-based lineage for full traceability
- CI/CD integration for automated enforcement
The implementation balances strict enforcement with practical flexibility through:
- Exact hash matching as primary mechanism
- Semantic compatibility as secondary (with approval)
- Content-addressable storage for immutability
- Graph-based lineage for full DAG representation