aiml

Lesson 14 of 21Module 5

Register and select an explicit model version

Package the fitted return model with its contract and gate decision, then select a checked version through a local MLflow alias.

Prerequisites

Complete the preceding course lessons in the shared user-return lab; keep their work/ outputs. Python functions and local CLI commands.

Preparation and term definitions

By the end, you can

  • Register a packaged candidate as an explicit MLflow version.
  • Distinguish alias selection from traffic selection.
  • Load the custom model flavor through its checked application loader.
Runtime
Python 3.12+; local CPU
Dependencies
Pinned MLflow, Prefect and FastAPI dependencies in requirements-platform.txt

Lab code, tests and fixtures (ZIP, 1.6 MB)Quiz check your understanding

Progress is saved in this browser.

Package the fitted return model with its contract and gate decision, then select a checked version through a local MLflow alias.

Problem

When you need this. A run ID locates an experiment, but a prediction process needs a deployable set of files: the model, preprocessing, feature contract, application compatibility and evaluation policy. Selecting the latest directory by timestamp would hide which version is actually intended.

This workshop packages two runs of the same trainer and registers both in the local MLflow store that holds their training runs. A review alias selects a version without changing any prediction traffic.

Concepts

A registered model groups versions of one model interface. A version identifies a specific packaged candidate. An alias is a movable name pointing to one version. A consumer resolves the alias once, verifies the selected bundle and keeps its identity with the predictions.

The package declares a custom user_return flavor in MLmodel. The supplied loader is release.load_bundle; it loads this project’s JSON model. It is not an MLflow pyfunc model, and this lesson does not use the built-in MLflow serving command.

The bundle manifest hashes its files and records the serving and release implementation digests. Loading checks those bytes, the feature contract and a freshly recomputed gate. The digests detect a file that differs from the manifest. They are not signatures, so they cannot tell you who published a bundle.

The second run produces the same model bytes but a different run ID and bundle identity. It exists to give version selection and rollout a second version. Repeating training has not improved the model. A higher version number does not mean a better model; compare the model_sha256 in each bundle.json before you treat a new version as a change.

Architecture

Candidate bundlemodel, policy, sourceVerify packagebytes + fresh gateMLflow registryversion 1 and version 2Resolve review aliasselect version 2Selected bundlecustom JSON loaderCandidate bundlemodel, policy, sourceVerify packagebytes + fresh gateMLflow registryversion 1 and version 2Resolve review aliasselect version 2Selected bundlecustom JSON loader
Registration and alias selection use the original local MLflow store. Resolving a version does not change traffic.

Working code

Download the shared application and tests, unzip it and enter mlops-return-workflow/. Keep the same directory throughout the course. Create the environment once. Install the pinned platform dependencies for this workshop.

Create the local environmentTerminal · bash
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-platform.txt

On PowerShell, activate with .venv\Scripts\Activate.ps1.

Continue from Evaluate a candidate against a declared release policy; keep the same lab directory and outputs.

Package the actual candidate

The package keeps the evaluation report separate from candidate.json, includes the fitted preprocessing and records the exact application implementation it supports.

Source excerpt: package_candidateSource · pythonDownload
def package_candidate(pipeline_result,destination,policy=None):
    result,source=candidate_files(pipeline_result)
    if result['status']!='FINISHED' or w.sha(source/'outputs/candidate.json')!=result['model_sha256']:
        raise ValueError('pipeline model identity differs')
    decision=gate(source/'outputs/cohort.json',source/'outputs/candidate.json',policy)
    target=Path(destination);target.mkdir(parents=True)
    for name in ['candidate.json','cohort.json','validation.json']:
        shutil.copyfile(source/'outputs'/name,target/name)
    shutil.copyfile(source/'contract.json',target/'contract.json')
    # Include the exact trainer and application implementation for this artifact.
    for name in f.CORE_FILES:
        if name!='scenario.json':
            dest=target/'source'/name;dest.parent.mkdir(parents=True,exist_ok=True);shutil.copyfile(source/name,dest)
    w.save(target/'gate.json',decision)
    from mlflow.models import Model
    metadata=Model();metadata.add_flavor('user_return',model_file='candidate.json',loader='release.load_bundle',format='return-model-v1');metadata.save(str(target/'MLmodel'))
    files={str(p.relative_to(target)):w.sha(p) for p in target.rglob('*') if p.is_file()}
    manifest={'format':'return-bundle-v1','project':w.PROJECT,'feature':f.FEATURE_CONTRACT,
              'run_id':result['run_id'],'model_sha256':result['model_sha256'],
              'policy_sha256':decision['policy_sha256'],'serving_code_sha256':w.sha(w.HERE/'serving.py'),
              'release_code_sha256':w.sha(Path(__file__)),'files':files}
    w.save(target/'bundle.json',manifest)
    load_bundle(target)
    return {'bundle_id':f.digest(manifest),'path':str(target.resolve()),'gate_passed':decision['passed'],
            'model_sha256':result['model_sha256'],'format':'custom MLflow user_return flavor; local loader'}
Source excerpt: load_bundleSource · pythonDownload
def load_bundle(path):
    path=Path(path);manifest=w.strict_json(path/'bundle.json')
    if manifest.get('format')!='return-bundle-v1' or manifest.get('project')!=w.PROJECT or manifest.get('feature')!=f.FEATURE_CONTRACT:
        raise ValueError('incompatible bundle contract')
    for key in ['serving_code_sha256','release_code_sha256']:
        file='serving.py' if key.startswith('serving') else 'release.py'
        if manifest[key]!=w.sha(w.HERE/file):raise ValueError('application code is incompatible with bundle')
    for name,expected in manifest['files'].items():
        p=(path/name).resolve()
        if not p.is_relative_to(path.resolve()) or w.sha(p)!=expected:raise ValueError('bundle artifact changed: '+name)
    if w.sha(path/'candidate.json')!=manifest['model_sha256']:raise ValueError('bundle model changed')
    model=w.load_model(path/'candidate.json');decision=w.strict_json(path/'gate.json')
    if f.digest(decision['policy'])!=manifest['policy_sha256']:raise ValueError('bundle policy changed')
    actual=gate(path/'cohort.json',path/'candidate.json',decision['policy'])
    if actual!=decision:raise ValueError('stored gate differs from fresh checks')
    return model,manifest,decision

The loader reruns the gate instead of treating an MLmodel file as approval. It refuses the bundle if any artifact changed or if the application code digest differs.

Load bundles through release.load_bundle rather than reading candidate.json directly. The predictor, the rollout step and selected all call it, so they run the same checks.

Register versions and resolve the review alias

Registration requires the original completed run in this MLflow store. A passing candidate receives the local review alias. A failing candidate is still registered, but the alias stays where it was.

Source excerpt: registerSource · pythonDownload
def register(bundle,workspace):
    path=Path(bundle).resolve();_,manifest,decision=load_bundle(path)
    _,c,_=tracking.client(workspace)
    if c.get_run(manifest['run_id']).info.status!='FINISHED':raise ValueError('registry requires the original completed run in this store')
    name=w.PROJECT
    try:c.get_registered_model(name)
    except __import__('mlflow').exceptions.MlflowException as e:
        if e.error_code!='RESOURCE_DOES_NOT_EXIST':raise
        c.create_registered_model(name,description='Local user-return custom JSON flavor')
    version=c.create_model_version(name,source=path.as_uri(),run_id=manifest['run_id'],tags={'bundle_sha256':f.digest(manifest),'gate_passed':str(decision['passed']).lower(),'format':'user_return'})
    if decision['passed']:c.set_registered_model_alias(name,'review',version.version)
    return {'name':name,'version':str(version.version),'bundle_sha256':f.digest(manifest),
            'review_alias_selected':decision['passed'],'source':version.source,'model_sha256':manifest['model_sha256']}
Source excerpt: selectedSource · pythonDownload
def selected(workspace,version=None):
    from urllib.parse import urlparse,unquote
    _,c,_=tracking.client(workspace)
    item=c.get_model_version(w.PROJECT,str(version)) if version else c.get_model_version_by_alias(w.PROJECT,'review')
    url=urlparse(item.source)
    if url.scheme!='file' or url.netloc:raise ValueError('only local registry sources supported')
    path=Path(unquote(url.path));_,manifest,decision=load_bundle(path)
    if item.tags.get('bundle_sha256')!=f.digest(manifest):raise ValueError('registry binding differs')
    if not decision['passed']:raise ValueError('selected candidate failed its release gate')
    return path,str(item.version)
Register versions and resolve the review aliasTerminal · bash
python course.py registry --workspace work/course
Actual local application outputRecorded output · jsonDownload
{
  "registered_versions": [
    "1",
    "2"
  ],
  "review_alias_version": "2",
  "format": "custom user_return MLflow flavor; release.load_bundle loader",
  "model_bytes_equal": true,
  "bundle_ids_distinct": true,
  "traffic_changed": false
}

The command registers versions 1 and 2 in a fresh store. Both have the same model bytes but different bundle identities. Resolving review returns version 2, and no routing table changes.

The output above is from an actual local run saved in recorded-platform/; your commands write to work/. Read the actual command records. Use a fresh work directory for another attempt.

Failure cases

test_registry_roundtrip_and_alias_does_not_select_failed_gate registers a stricter-policy failure and checks that the previous alias remains selected. The consumer also refuses an explicit request for the failed version.

test_bundle_tampering_and_incompatible_application_are_refused changes model bytes or the declared application compatibility. The loader rejects both before any prediction.

Run the application failure checksTerminal · bash
python -m unittest -v test_platform.py

Running and scaling the workshop

The registry and artifacts are local files. Keep the tracking store and the bundles where they were created. Registration looks up the original run in that store, and each version records its bundle’s absolute file path, so a moved bundle can no longer be selected.

A shared registry also needs authentication, access control, trusted release provenance and artifact retention. When you roll back, use an application build that the older bundle accepts; moving the alias does not fix a code or feature mismatch.

Key takeaways

  • A registry version identifies a packaged candidate.
  • Alias selection and traffic selection are different actions.
  • A custom flavor needs its own tested loader.

Best practices

Resolve a selected version and retain its exact bundle identity.

Keep failed candidates inspectable while blocking them from the serving consumer: read the selected version through selected, which reloads the bundle, compares its digest with the registry tag and refuses a candidate that failed its gate.

Check your understanding

Why does changing the review alias leave the currently served model unchanged?

Show the explanation

The local routing table selects serving bundles separately. Registry selection prepares a candidate; the rollout step explicitly changes traffic.

A registered version fails its gate. Can changing the selected alias make it eligible?

Choose one answer, then check your reasoning.

Read the explanation

The consumer reloads the bundle and checks its gate. An alias identifies a version; it cannot turn a failed quality decision into an eligible release.

References

Written by Arjun Prabhulal.

Module 5

Release the model