Skip to main content
LearnMLAcademy
Advanced10 min read

Testing, CI/CD & Continuous Training for ML

Implement automated CI/CD pipelines and continuous retraining, with pipeline maps, deployment choices, and production reliability checks.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Automate releases without automating unsafe promotion

Ordinary software tests whether code behaves as expected. ML systems also depend on changing data, feature meaning, statistical behaviour, artifact compatibility, and delayed outcomes. A deployment can therefore have perfectly valid code and still produce a worse model.

CI, CD, and CT automate different parts of the lifecycle. Continuous integration validates changes; continuous delivery or deployment moves an approved release; continuous training produces a new candidate when an approved trigger justifies it. None of them means releasing every change automatically.

What You Will Be Able to Explain

  • Design code, data, feature, model, and integration tests
  • Separate CI, CD, and CT responsibilities
  • Trace an evaluated release pipeline
  • Stop deployment when a model regression test fails
  • Explain why drift alone must not trigger blind retraining

What CI, CD, CT and release gates each mean

These terms name different responsibilities. Read the meaning before following them through the diagrams and worked example.

Core vocabulary

Core vocabulary
TermMeaning in this lesson
CIContinuous Integration: merge small changes frequently and run automated validation on the integrated code.
Continuous DeliveryKeep an approved release ready for a deliberate production decision.
Continuous DeploymentAutomatically promote a release that passes every required control.
CTContinuous Training: run a repeatable candidate-training workflow from an approved trigger.
Regression testChecks that a new change has not broken previously accepted behaviour.
Golden exampleA stable input with an expected deterministic or bounded output used to detect unintended change.
CanaryA release exposed to a small controlled portion of traffic before broader rollout.

Testing creates gates across the entire ML contract

Code tests cover transformations, utility functions, and the inference interface. Data tests cover schema, ranges, missingness, category membership, timestamps, and duplicates. They answer different questions: correct function logic versus acceptable input.

Feature tests verify expected calculations, freshness, and parity between historical and serving paths. Model tests enforce minimum metrics, slice requirements, regression limits, and deterministic examples where appropriate. Integration tests load the real preprocessing and artifact together and exercise the endpoint contract.

ML tests protect more than application code

Which different contracts can fail before a model reaches users?

Integration testspreprocessing + artifact load + endpoint contract
Model testsmetric gate + slices + regression + golden cases
Feature teststransformation + freshness + training/serving parity
Data testsschema + ranges + missingness + duplicates
Code testsutilities + transformations + interface
How to read it: Code, data, features, model behaviour, and integration each need targeted tests. Passing a schema test cannot prove that a new model still meets recall or slice requirements.

Each test layer protects a different contract

Each test layer protects a different contract
Test typeExample assertionFailure means
Codenormalize_age(40) returns expected valueFunction or interface logic changed
Dataage exists, is numeric, and is within reviewed boundsIncoming data violates its contract
Featurehistorical and live orders_last_30_days agree for a replay caseFeature meaning or freshness diverged
Modelrecall ≥ 0.75 overall and required slices do not regressCandidate behaviour is not release-eligible
Integrationpreprocessor v4 loads with model v13 and endpoint schema v3Combined artifact/service contract is broken

Follow the release path from a change to production

A complete release path is code or approved data change → tests → train candidate → evaluate → register → approve → shadow or canary → production → monitor. Each transition records evidence and retains the current production artifact until the new one proves safe.

CI, CD, and CT are related but distinct loops

What is integrated, released, and retrained?

CI · integratechange → code/data/feature tests → package
CD · releaseapproved artifact → shadow/canary → production
CT · retrainjustified trigger → train new candidate → evaluate
CT never skips evaluation, approval, or controlled release
How to read it: CI validates changes, CD moves an approved artifact through release stages, and CT creates a new candidate from justified fresh evidence. CT still returns to evaluation and approval.

CI, CD, and CT have different outputs

CI, CD, and CT have different outputs
PracticeStarts fromProducesMust not imply
CICode/configuration changeValidated package and test evidenceThe model is good enough for production
CDApproved release candidateControlled delivery/deployment and rollback evidenceEvery passing build gets all traffic
CTApproved schedule/data/performance triggerEvaluated new model candidateDrift automatically retrains and releases

A training trigger is not permission to deploy

CT may start on a schedule, enough new labelled data, measured performance decay, or an approved drift investigation. Drift alone says the input distribution changed; retraining on corrupt, biased, or unlabelled data can make the system worse.

Worked Example: A valid dataset still produces a rejected candidate

Given: The incoming data passes schema, range, missingness, and duplicate checks. The current production model has recall 0.78 on the fixed release set. The candidate has recall 0.71; the required minimum is 0.75 and regression beyond 0.02 is prohibited.

  1. Data gate passes: the records are structurally acceptable. This says nothing yet about candidate quality.
  2. Training completes and produces a loadable artifact with recorded lineage.
  3. Minimum metric gate: 0.71 < 0.75, so the candidate fails.
  4. Regression check: 0.78 − 0.71 = 0.07 decline, which is greater than the allowed 0.02. It fails again.
  5. The pipeline records the failed evidence, does not promote the candidate, and leaves the current production version serving.

Result and interpretation: Deployment stops even though data validation and training succeeded. Layered tests prevent one kind of success from being mistaken for complete release readiness.

The following figures turn the example into an operational decision. Follow every branch and note which state is recorded before work continues.

A model regression test can stop an otherwise valid build

What happens when data is valid but candidate performance declines?

Code + data change
Data tests PASSschema and ranges valid
Train candidate
Model test FAILrecall .71 < required .75
STOP deploymentproduction stays on v12
How to read it: The schema and range checks pass, training completes, but recall falls below the approved minimum. The gate rejects the candidate and keeps the current production version.

Encode the metric and regression checks that block a release

The label above each block states what it is. Runnable Python can be executed as shown with the standard library; pseudocode and configuration communicate architecture and require adaptation to a real platform.

Write separate data and model assertions

These checks show why a passing data contract cannot override a failed model gate.

Write separate data and model assertionsPythonRUNNABLE PYTHON
def validate_rows(rows):
    assert rows, "dataset is empty"
    assert all(0 <= r["age"] <= 120 for r in rows)
    assert len({r["event_id"] for r in rows}) == len(rows)

def validate_candidate(metrics, production_metrics):
    assert metrics["recall"] >= 0.75
    assert production_metrics["recall"] - metrics["recall"] <= 0.02

validate_rows([{"event_id":"e1", "age":41}])       # passes
validate_candidate({"recall":0.71}, {"recall":0.78}) # fails

Describe an evidence-driven CT trigger

The drift alert begins diagnosis. Candidate training starts only after evidence and approval satisfy the policy.

Describe an evidence-driven CT triggerCONCEPTUAL PSEUDOCODE
on drift_alert:
    verify pipeline and source health
    wait for sufficient outcome labels
    compare production performance and required slices
    if persistent material degradation is confirmed and retraining is approved:
        train candidate
        run all release tests
        register and canary only if every gate passes

Choose triggers, approvals and rollback conditions

  • Choose tests from plausible failures and product risk, not only from easy-to-measure functions.
  • Keep fixed release sets and golden cases versioned; refresh them through review rather than silently.
  • Separate candidate creation from approval and traffic release.
  • Automate reversible low-risk steps first; keep explicit approval where consequences or evidence uncertainty are high.

Failure Analysis and Recovery

Observed failure → likely cause → controlled response

Observed failure → likely cause → controlled response
Observed failureLikely causeResponse
All unit tests pass, endpoint crashesArtifact/preprocessor contract untestedAdd integration load and request/response tests
Aggregate metric passes, region failsNo slice gateRequire relevant segment thresholds and sample support
Every drift alert retrainsCT trigger confuses change with degradationInvestigate, wait for outcomes, and evaluate candidate
Canary is bad but rollout continuesNo automatic stop/rollback criteriaPredefine guardrail metrics and traffic reversal

Connect to Earlier Lessons

Summary / Key Takeaways

  • ML testing covers code, data, features, model behaviour, and integration because each can fail independently.
  • A passing data contract proves structural acceptability, not that a trained candidate meets quality requirements.
  • CI validates integrated changes, CD controls an approved release, and CT creates a newly trained candidate.
  • Candidate creation, evaluation, approval, canary release, and production promotion are separate governed transitions.
  • Drift is an investigation signal; automatic retraining on unverified data can amplify defects or bias.
  • A candidate with recall 0.71 is correctly blocked when the minimum is 0.75, even though its data and artifact are valid.
  • Every release pipeline needs explicit stop conditions, preserved evidence, a known-good production version, and tested rollback.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Testing, CI/CD & Continuous Training for ML"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5application/scenario
Data validation passes, but candidate recall is 0.71 against a required 0.75. What should the release pipeline do?
Question 2 of 5conceptual
Which statement correctly separates CI, CD, and CT?
Question 3 of 5interpretation
Why must drift not automatically trigger retraining and deployment?
Question 4 of 5practical selection
Which is an integration test?
Question 5 of 5debugging/diagnostic
Aggregate recall passes, but recall for one required region falls sharply. Which test was missing?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1Data validation passes, but candidate recall is 0.71 against a required 0.75. What should the release pipeline do?▼

Correct Answer: Stop promotion and keep the current production model

Different gates test different contracts. Valid data does not override a failed model-quality requirement.

2Which statement correctly separates CI, CD, and CT?▼

Correct Answer: CI validates integrated changes, CD controls release, and CT creates a new candidate

The practices automate distinct lifecycle stages. CT still returns its candidate through evaluation and release controls.

3Why must drift not automatically trigger retraining and deployment?▼

Correct Answer: Changed inputs do not prove performance failed, and new data may be defective

Drift is a change signal. Diagnosis and labelled outcome evidence are needed before retraining, and the candidate must still pass gates.

4Which is an integration test?▼

Correct Answer: Load preprocessing v4 with model v13 and exercise the endpoint contract

Integration tests verify that real components operate together. The other options are data, code/feature, or model tests.

5Aggregate recall passes, but recall for one required region falls sharply. Which test was missing?▼

Correct Answer: Slice regression gate

A slice gate detects degradation hidden by the aggregate and should include sample-size context and a reviewed requirement.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next