Sub topic 14
Automating Promotion Gates and Controlling Access
Earlier chapters promoted a model by hand: you ran set_registered_model_alias and moved champion. That works for one person. On a team, anyone can move an alias at any moment, and nobody checks whether the new version is better. This chapter covers two fixes. A script checks a candidate version before the alias moves, and permissions restrict who can move it.
Assumed prerequisites: you have a tracking server with a SQL backend store, you can register a model and set aliases with MlflowClient, and your training runs log metrics with mlflow.log_metric. The examples use the iris-classifier model from earlier chapters and assume each run logs an accuracy metric.
What a promotion gate is
A promotion gate is a check that must pass before an alias moves. The check is code, so it runs the same way every time and can run in CI. A gate needs three things:
- Evidence attached to the candidate version, such as the
validation_statustag and the metrics on its source run. - A baseline to compare against, usually the version the
championalias points to now. - A single place that moves the alias, so no other code path can bypass the checks.
Registry data is the right place to keep this evidence. The version records its source run through run_id, and the run holds the metrics. Tags on the version hold results from validation jobs that ran after training.
A gate script
The script below takes a version number as its only argument. It exits with status 0 on success and 1 on rejection, so a CI job fails when the gate fails.
import sys
from mlflow import MlflowClient
from mlflow.exceptions import MlflowException
MODEL = "iris-classifier"
ALIAS = "champion"
METRIC = "accuracy"
client = MlflowClient(tracking_uri="http://127.0.0.1:5000")
def run_metric(version):
"""Return the metric value from the run that produced a version."""
run = client.get_run(version.run_id)
return run.data.metrics.get(METRIC)
def current_champion():
"""Return the version behind the alias, or None if the alias is unset."""
try:
return client.get_model_version_by_alias(MODEL, ALIAS)
except MlflowException:
return None
def main(candidate_number):
candidate = client.get_model_version(MODEL, candidate_number)
if candidate.tags.get("validation_status") != "passed":
print(f"Rejected: version {candidate.version} has no passing validation tag")
return 1
candidate_score = run_metric(candidate)
if candidate_score is None:
print(f"Rejected: run {candidate.run_id} did not log '{METRIC}'")
return 1
champion = current_champion()
if champion is not None:
champion_score = run_metric(champion)
if champion_score is not None and candidate_score < champion_score:
print(
f"Rejected: {METRIC} {candidate_score:.4f} is below "
f"champion {champion_score:.4f}"
)
return 1
client.set_registered_model_alias(MODEL, ALIAS, candidate.version)
confirmed = client.get_model_version_by_alias(MODEL, ALIAS)
print(f"Promoted: {ALIAS} now points to version {confirmed.version}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1]))Run it as python gate.py 3. Several details matter here:
get_model_version_by_aliasraisesMlflowExceptionwhen the alias does not exist. The first promotion of a model has no champion, so the script treats that case as "nothing to beat".- The script reads the alias back after writing it. If a network or permission problem left the alias unchanged, the confirmation line shows the old version instead of the candidate.
- Version numbers are strings in the client API, which is why
argv[1]is passed through unchanged. - A missing metric is a rejection, not a pass. A gate that treats missing data as success hides broken training jobs.
Race conditions and the single promoter
Setting an alias is last-writer-wins. The registry offers no compare-and-set operation, such as "move the alias only if it still points at version 2". If two gate jobs run at once, both can read the same champion and then write in either order. Reduce the risk by running promotion from one CI job with a concurrency limit of one, and by granting alias-moving rights to that job's account only (see below).
Keep the gate's checks reproducible
Store the threshold values in the repository next to the gate, not in someone's shell history. When you later ask why version 4 was promoted, the answer is the gate's commit plus the tags and metrics on version 4.
Finding candidates with a search
A gate often starts from "which versions are waiting for review". Use search_model_versions to list versions by name, then filter on tags in Python. Filtering in Python avoids depending on which tag filter syntax your server version supports.
from mlflow import MlflowClient
client = MlflowClient(tracking_uri="http://127.0.0.1:5000")
versions = client.search_model_versions("name='iris-classifier'")
pending = [
mv for mv in versions
if mv.tags.get("validation_status") == "passed"
and "champion" not in mv.aliases
]
for mv in sorted(pending, key=lambda v: int(v.version)):
print(mv.version, mv.run_id, mv.aliases)Each ModelVersion carries its tags dictionary and its aliases list. Sort by int(mv.version), because the version field is a string and "10" sorts before "2" as text. For a registry with many versions, the search call returns results in pages. Iterate over the returned list rather than assuming one page holds everything.
Controlling who can promote
Promotion code is only as safe as the accounts allowed to run it. A script that checks tags does nothing if a user can call set_registered_model_alias directly. Access control closes that gap.
What open-source MLflow offers
Open-source MLflow ships a basic authentication app. Start the server with it, and every request needs a username and password:
export MLFLOW_AUTH_CONFIG_PATH=./basic_auth.ini
mlflow server \
--app-name basic-auth \
--backend-store-uri sqlite:///mlflow.db \
--default-artifact-root ./mlartifacts \
--host 127.0.0.1 \
--port 5000The config file sets the defaults:
[mlflow]
default_permission = READ
database_uri = sqlite:///basic_auth.db
admin_username = admin
admin_password = change-me-before-first-startThe first start creates the admin account from these values. The documented default admin password is a well-known value, so set your own before the server first runs. Clients then identify themselves with the MLFLOW_TRACKING_USERNAME and MLFLOW_TRACKING_PASSWORD environment variables. Never put these in code.
Permissions attach to a user and a registered model. The four levels are:
| Permission | Meaning |
|---|---|
| `NO_PERMISSIONS` | The user cannot see or use the model. |
| `READ` | The user can read the model and load it. |
| `EDIT` | The user can also change it, for example register versions, set tags, and move aliases. |
| `MANAGE` | The user can also manage the model's permissions and delete it. |
Basic auth also has experiment-level permissions. A model version's source run lives in an experiment, so read access on the model does not always imply read access on the run's artifacts. Test this with a non-admin account before relying on it.
A reasonable team layout has three kinds of user. Data scientists get READ on the production model, plus EDIT on a staging model they own. The CI service account gets EDIT on the production model, so only the gate can move champion. Maintainers get MANAGE. Set default_permission to READ or NO_PERMISSIONS, not EDIT, so new models start locked down.
Granting permissions from code
The auth app has its own client, separate from MlflowClient:
from mlflow.server.auth.client import AuthServiceClient
auth = AuthServiceClient("http://127.0.0.1:5000")
auth.create_user(username="ci-promoter", password="a-long-random-secret")
auth.create_registered_model_permission(
name="iris-classifier",
username="ci-promoter",
permission="EDIT",
)Run this as the admin account, with the admin credentials set in the environment. Check the permission names and client methods against the version you run, because this module has changed between releases.
Permissions do not replace the gate
Access control answers "who may move the alias". The gate answers "is this version fit to be moved to". You need both. If everyone with EDIT can run an ungated script, the tag and metric checks are decoration.
Failure modes
- Gate passes, serving does not change. A running service that called
load_model("models:/iris-classifier@champion")at startup keeps its loaded model. Moving the alias changes future loads only. Either restart or reload the service after promotion, or have it re-resolve the alias on a schedule. - Tag set by the wrong party. If anyone with
EDITcan writevalidation_status, anyone can fake a pass. Let only the validation job's account set that tag. - Metric from the wrong run. A version registered from a run URI links to that run. If someone registers a model from a different run than the one you evaluated, the gate compares the wrong numbers. Make the validation job record the version's
run_idin a tag and have the gate confirm it matches. - Stale baseline. If the champion changes between the gate's read and write, the comparison used an old baseline. Serialize promotions as described above.
Exercise
Your gate script rejects every candidate on the first promotion of a brand-new model, because it crashes when it asks for the current champion. What change fixes this, and what should the gate do when there is no champion?
Show answer
Catch MlflowException around getmodelversionbyalias, which raises when the alias is not set, and return None. When there is no champion, skip the comparison and apply only the absolute checks, such as the validation_status tag and a logged metric. Then set the alias to the candidate.
Exercise
A teammate has READ permission on iris-classifier and calls setregisteredmodel_alias for champion. What do you expect to happen with basic auth enabled, and why does the gate script not make this unnecessary to configure?
Show answer
The server rejects the request with a permission error, because moving an alias needs EDIT on the registered model. The gate script runs client-side and only checks the candidate. It cannot stop someone from calling the alias API directly, so permissions must restrict who can write the alias.