aiml

Lesson 10 of 21Module 4

Connect preparation, training and evaluation with Prefect

Automate the manual return-model workflow while keeping the accepted events, historical features and fitted model connected.

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

  • Carry validated artifacts between actual Prefect tasks.
  • Distinguish input validation from candidate quality evaluation.
  • Produce a candidate without automatically authorizing serving.
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.

Automate the manual return-model workflow while keeping the accepted events, historical features and fitted model connected.

Problem

When you need this. The manual commands show that the model can be fitted and reloaded. An automated run must keep those steps connected: fitting must not start after an invalid event batch, and evaluation must use the cohort that produced the candidate.

The pipeline reads the same scenario and validates its event records. It then materializes the historical count for each observation and passes that prepared cohort to the tracked trainer. The output is a candidate model and its validation result, ready for evaluation against a release policy.

Concepts

Prefect runs Python functions as workflows and records the state of each flow and task. A flow coordinates work; a task is a separately tracked unit inside it. When the flow calls a decorated task and passes its return value to the next call, the next task depends on that result. Naming three tasks in a flow does not connect their data; passing the return values does.

The validation task keeps both the accepted and the rejected bytes. Only a ready batch produces accepted-scenario.json. The history task reads that accepted source, joins the prediction cutoffs to their historical counts and saves cohort.json. It checks those counts against the direct assembler before training reads the file.

The flow passes the prepared file to the tracked trainer as an argument. The trainer checks that the supplied cohort matches its copy of the scenario, then fits only the training window. MLflow stores the model and validation artifacts. Prefect manages execution state; it does not grade the model.

Architecture

Event batchauthored scenarioValidate recordsaccepted bytes onlyReconstruct featuresSQLite history joinsPrepared cohortprediction-time countsTracked trainerchild Python processesCandidate + reportseparate saved artifactsEvent batchauthored scenarioValidate recordsaccepted bytes onlyReconstruct featuresSQLite history joinsPrepared cohortprediction-time countsTracked trainerchild Python processesCandidate + reportseparate saved artifacts
Data dependencies in the local Prefect flow. The wrapper passes the historical cohort to the trainer; Prefect run state and MLflow metadata are retained separately.

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 Track a training run and reload its model; keep the same lab directory and outputs.

Validate events before constructing features

The next task must read the validator’s accepted records. Otherwise validation only writes a report, and fitting still reads unchecked input.

Source excerpt: validate_eventsSource · pythonDownload
Source excerpt: materialize_cohortSource · pythonDownload

The clean fixture contains 240 observations. Each joined historical count matches the original direct calculation. An invalid record blocks training and remains in the quarantine output.

Run the connected tasks

The flow passes each file path to the task that reads it. Each task sets cache_policy=NO_CACHE, so Prefect does not reuse task results on its own; the following workshop introduces explicit result reuse.

Source excerpt: train_flowSource · pythonDownload
Run the connected tasksTerminal · bash
python course.py pipeline --workspace work/course
Actual local application outputRecorded output · jsonDownload
{
  "status": "FINISHED",
  "training_rows": 144,
  "validation_accuracy": 0.6041666666666666,
  "run_id": "4cdcd1ccf1f14fb4a52cc5674c0b2a9e",
  "model_sha256": "576847afc0d4b064e9f3653f2d25b994b638ae12dcb53fcf02beae45a0799b43",
  "cohort_consumed_from_history": "4e808d638866651009546e045fa211836690b0a4210e7bec816e4bc4165834be",
  "receipt_attempts": 1,
  "final_test_used": false
}

The local run trains on 144 rows and reports validation accuracy 0.6042. The model and cohort digests identify these exact files. The final test window stays unused.

The output above is from a saved run in recorded-platform/; your commands write to work/. Read the actual command records. If a run fails partway, start again with a fresh --workspace: pipeline.py refuses a folder that still holds an incomplete attempt.

Failure cases

test_invalid_event_batch_cannot_train appends a malformed event, expects the run to fail with an invalid batch error and confirms that no candidate.json exists. The quarantine file stays in the attempt folder for diagnosis.

test_completed_cohort_tampering_is_refused changes one count in the saved cohort. A rerun with the same inputs must reject the altered result instead of reusing it.

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

Running and scaling the workshop

Running course.py starts a temporary local Prefect server. pipeline.py disables server analytics and clears any Prefect Cloud URL or API key, so no Prefect Cloud account is used. Keep the command log when you inspect a task failure.

Tasks run in sequence because each one reads the previous task’s output. Run independent partitions in parallel only after you define each partition’s identity and the rule that merges their results. This small fixture gives no throughput or worker-capacity measurement.

Key takeaways

  • An automated pipeline must carry artifacts between stages.
  • Data validation and model-quality evaluation are separate decisions.
  • A successful flow produces a candidate, not permission to serve it.

Best practices

Pass each downstream input explicitly, and keep the failed batch. When a run stops at validation, read validation.json and the quarantine file before you change the trainer: an invalid batch stops the flow before fitting starts.

Keep orchestration outside the reusable prediction mathematics. The flow calls tracking.execute, the same trainer that the manual tracking command runs.

Check your understanding

Would a ready validation report be enough if the training task still read the original unchecked event file?

Show the explanation

No. The task must consume the accepted records. This flow writes and reads the accepted scenario before materializing or fitting.

An input event is invalid. Where should this flow stop?

Choose one answer, then check your reasoning.

Read the explanation

The validation task blocks invalid input before cohort preparation and training can create a candidate. Quarantine retains the failed input for diagnosis.

References

Written by Arjun Prabhulal.

Module 4

Automate and test the workflow