Connect the dataset, source, fitting settings and validation result to one MLflow run, then retrieve the model another process can use.
Problem
When you need this. A validation score alone cannot tell another process how to predict. The return model also needs its fitted scaler and weights. A reproducible experiment must connect those bytes to the selected observations, feature definition and training code.
This workshop wraps the manual trainer and keeps its mathematics. The wrapper creates a local MLflow experiment and copies a snapshot of the source. It then runs preparation, fitting and validation as separate processes, and stores the model file apart from its evaluation report.
Concepts
MLflow records training executions, their measurements and saved files. An experiment groups related executions. A run identifies one execution, with parameters, metrics and artifacts. A parameter records an input such as the learning rate; a metric records an observation such as validation accuracy. An artifact is a saved file.
The model artifact is candidate.json: full-precision weights, bias and fitted preprocessing. validation.json describes an evaluation of that model. Loading the report as a model is an error. workflow.load_model reads this custom JSON format; it is not an MLflow pyfunc model.
The snapshot contract hashes the selected dataset and implementation files. Before it runs any copied file, the wrapper compares the copied files with those hashes, so a later edit in the original working directory cannot change this run. MLflow records the identity; the wrapper enforces the binding.
Architecture
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.
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements-platform.txtOn PowerShell, activate with .venv\Scripts\Activate.ps1.
Continue from Version data and feature definitions; keep the same lab directory and outputs.
Create a local experiment and execute the selected source
The tracking URI names a local SQLite database, and the experiment stores artifacts in a local directory. The wrapper captures the source before any training command runs.
def client(workspace):
# Explicit local SQLite and file artifacts; no provider credentials or cloud URI.
os.environ['MLFLOW_ENABLE_ASYNC_LOGGING']='false'
os.environ['MLFLOW_ENABLE_SYSTEM_METRICS_LOGGING']='false'
os.environ['MLFLOW_DISABLE_TELEMETRY']='true'
import mlflow
uri='sqlite:///'+str((Path(workspace).resolve()/'tracking.sqlite'))
mlflow.set_tracking_uri(uri)
c=mlflow.MlflowClient(tracking_uri=uri)
experiment=c.get_experiment_by_name(w.PROJECT)
if experiment is None:
artifact=(Path(workspace).resolve()/'artifacts');artifact.mkdir(parents=True,exist_ok=True)
experiment_id=c.create_experiment(w.PROJECT,artifact_location=artifact.as_uri())
else:experiment_id=experiment.experiment_id
return mlflow,c,experiment_iddef execute(source, workspace, fail_before_training=False, prepared_cohort=None):
workspace=Path(workspace).resolve();workspace.mkdir(parents=True,exist_ok=True)
mlflow,c,experiment_id=client(workspace)
with mlflow.start_run(experiment_id=experiment_id) as run:
run_id=run.info.run_id;folder=workspace/'runs'/run_id
manifest=f.snapshot(source,folder/'workspace')
if w.sha(folder/'workspace/scenario.json')!=manifest['dataset_sha256']:
raise ValueError('copied dataset differs from selected identity')
for name,expected in manifest['implementation'].items():
if w.sha(folder/'workspace'/name)!=expected:
raise ValueError('copied source differs from selected identity: '+name)
runtime={'python':sys.version.split()[0],
'packages':{name:importlib.metadata.version(name) for name in ['mlflow-skinny','SQLAlchemy']},
'contract_id':f.digest(manifest),'source':manifest,
'tracker_sha256':w.sha(Path(__file__))}
w.save(folder/'runtime.json',runtime)
mlflow.log_params({'project':w.PROJECT,'feature':w.FEATURE,'epochs':w.baseline.EPOCHS,
'learning_rate':w.baseline.LEARNING_RATE,'threshold':0.5,
'contract_id':f.digest(manifest)})
mlflow.set_tags({'execution':'actual local CPU training','dataset':'authored synthetic user-return fixture'})
commands=[['workflow.py','prepare','--out','outputs/cohort.json'],
['workflow.py','train','--cohort','outputs/cohort.json','--out','outputs/candidate.json'],
['workflow.py','evaluate','--cohort','outputs/cohort.json','--model','outputs/candidate.json','--out','outputs/validation.json']]
try:
if fail_before_training:raise ValueError('deliberate pre-training failure')
if prepared_cohort is not None:
supplied=w.cohort(prepared_cohort)
if supplied!=w.prepare(folder/'workspace/scenario.json'):
raise ValueError('supplied cohort differs from selected source')
w.save(folder/'workspace/outputs/cohort.json',supplied)
commands=commands[1:]
for index,argv in enumerate(commands):
completed=subprocess.run([sys.executable,*argv],cwd=folder/'workspace',text=True,capture_output=True,timeout=30)
(folder/f'command-{index}.stdout.txt').write_text(completed.stdout)
(folder/f'command-{index}.stderr.txt').write_text(completed.stderr)
if completed.returncode:raise ValueError('trainer command failed: '+str(index))
output=folder/'workspace/outputs';model=w.load_model(output/'candidate.json')
validation=w.strict_json(output/'validation.json')
if model['cohort_sha256']!=w.sha(output/'cohort.json'):raise ValueError('trained model cohort binding differs')
mlflow.log_metrics({'validation_accuracy':validation['accuracy'],'validation_correct':validation['correct'],
'validation_rows':validation['rows'],'majority_correct':validation['majority_correct']})
mlflow.log_artifact(str(output/'candidate.json'),'model')
mlflow.log_artifact(str(folder/'workspace/contract.json'),'model')
mlflow.log_artifact(str(output/'validation.json'),'evaluation')
mlflow.log_artifact(str(folder/'runtime.json'),'recipe')
mlflow.log_artifact(str(Path(__file__)),'recipe')
summary={'run_id':run_id,'status':'FINISHED','model_sha256':w.sha(output/'candidate.json'),
'model_artifact':'model/candidate.json','evaluation_artifact':'evaluation/validation.json',
'contract_id':f.digest(manifest),'validation_accuracy':validation['accuracy'],
'training_rows':model['training_rows'],'final_test_used':False}
except Exception as error:
mlflow.log_artifact(str(folder/'runtime.json'),'recipe')
mlflow.set_tag('failure_reason',str(error))
w.save(folder/'failure.json',{'reason':str(error),'model_artifact':None})
mlflow.log_artifact(str(folder/'failure.json'),'failure')
raise
actual=c.get_run(run_id)
if actual.info.status!='FINISHED':raise ValueError('MLflow run did not finish')
w.save(folder/'summary.json',summary)
return summarypython tracking.py --workspace work/tracking --out work/tracking.json{
"run_id": "f649d327780a48c4831963d79039880b",
"status": "FINISHED",
"model_sha256": "6ec6c622ac475213b6b13723e5cb8cdeb14d5bdccd93ca2ee42ba0d684917ab7",
"model_artifact": "model/candidate.json",
"evaluation_artifact": "evaluation/validation.json",
"contract_id": "c5949d7b20bb578e0e641aec284179b3c36cf54e6fdbc3862760439b6214905f",
"validation_accuracy": 0.6041666666666666,
"training_rows": 144,
"final_test_used": false
}The actual run fits 144 training rows and scores the same 48 validation rows: 29 correct, or 0.6042 accuracy. The run does not fit or score the final test window. Your run ID will differ from the one shown.
Check the artifact and the failed-run boundary
The integration tests use the installed MLflow client and a local SQLite store, not a mock. They download artifacts, load the saved model and stop a separate run on purpose before fitting.
class TrackingTests(unittest.TestCase):
def test_completed_run_stores_reloadable_model_and_separate_report(self):
with tempfile.TemporaryDirectory() as tmp:
result=tracking.execute(w.HERE/'scenario.json',tmp)
_,client,experiment=tracking.client(tmp)
run=client.get_run(result['run_id'])
self.assertEqual(run.info.status,'FINISHED')
downloaded=client.download_artifacts(result['run_id'],'model/candidate.json')
self.assertEqual(w.sha(downloaded),result['model_sha256'])
self.assertAlmostEqual(w.predict(w.load_model(downloaded),3)['return_probability'],0.40381146876849405)
report=client.download_artifacts(result['run_id'],'evaluation/validation.json')
self.assertEqual(w.strict_json(report)['correct'],29)
with self.assertRaises(ValueError):w.load_model(report)
self.assertFalse(result['final_test_used'])
def test_failure_is_failed_run_without_model(self):
with tempfile.TemporaryDirectory() as tmp:
with self.assertRaisesRegex(ValueError,'deliberate'):
tracking.execute(w.HERE/'scenario.json',tmp,True)
_,client,experiment=tracking.client(tmp)
runs=client.search_runs([experiment])
self.assertEqual(len(runs),1)
self.assertEqual(runs[0].info.status,'FAILED')
self.assertEqual(client.list_artifacts(runs[0].info.run_id,'model'),[])
failure=client.download_artifacts(runs[0].info.run_id,'failure/failure.json')
self.assertIsNone(w.strict_json(failure)['model_artifact'])
def test_copied_source_is_checked_before_execution(self):
from unittest.mock import patch
original=tracking.f.snapshot
def corrupt(source,destination):
manifest=original(source,destination)
(Path(destination)/'workflow.py').write_text('raise RuntimeError("should never run")')
return manifest
with tempfile.TemporaryDirectory() as tmp,patch.object(tracking.f,'snapshot',corrupt):
with self.assertRaisesRegex(ValueError,'copied source differs'):
tracking.execute(w.HERE/'scenario.json',tmp)
_,client,experiment=tracking.client(tmp)
self.assertEqual(client.search_runs([experiment])[0].info.status,'FAILED')
if __name__=='__main__':unittest.main()python -m unittest -v test_tracking.pyThe completed run contains a reloadable model and a separate report. The deliberate failure ends in FAILED state with no model artifact. A second failure test changes a copied source file and confirms that execution stops before that file runs.
The tracking output in the previous step is from a saved run in recorded-platform/; your commands write to work/. Read the actual command records. Use a fresh work directory for another attempt so the earlier outputs stay unchanged.
Failure cases
A run can finish a Python command yet store the wrong artifact. test_completed_run_stores_reloadable_model_and_separate_report downloads the model, checks its digest and reproduces the count-three prediction. It also confirms that workflow.load_model rejects the evaluation report.
test_failure_is_failed_run_without_model reads the failed run back from MLflow and confirms its FAILED status, no artifacts under model/ and a failure record with no model artifact. test_copied_source_is_checked_before_execution checks the snapshot before execution. These are integration and contract checks; they do not measure future prediction quality.
python -m unittest -v test_tracking.pyRunning and scaling the workshop
The tracker runs locally without an HTTP tracking server. Keep tracking.sqlite, its artifact directory and run workspaces together when backing up this exercise. A database backup alone does not contain the model files.
SQLite and local files suit this single-process workshop. A shared deployment needs authenticated storage, coordinated backups and a supported database; this workshop does not set them up. The client disables MLflow telemetry and automatic system-metric collection.
Key takeaways
- A run connects input identities and settings to an execution.
- A model file and its evaluation report serve different consumers.
- A failed run remains inspectable without becoming a release candidate.
Best practices
Retain the fitted preprocessing with the weights, and check model and cohort digests before evaluating.
Keep original run records. Start another run for a changed recipe instead of rewriting an earlier result.
Give a consumer the run ID, the model/candidate.json path and the model_sha256 value from work/tracking.json, and have it compare the downloaded file with that digest before loading it.
When a training command or result check fails, read its failure_reason tag and failure/failure.json before you start the next attempt. A snapshot mismatch stops the run before those records exist, so read the command’s error message instead.
Check your understanding
Why is a high validation score insufficient to let another process make predictions?
Show the explanation
The score contains no fitted weights or scaler. The consumer must retrieve the actual model, verify its identity and load its supported format.
Read the explanation
The model artifact contains fitted preprocessing and parameters. The evaluation report is a separate artifact with a different purpose.