CI/CD, continuous training & feature stores
Test data, features and models automatically; build a GitHub Actions pipeline with a model quality gate; add continuous training; and avoid training-serving skew with a feature store.
In normal software, CI/CD means every change is automatically built and tested (Continuous Integration) and can be released safely at any time (Continuous Delivery/Deployment). ML adds two twists: the system's behaviour depends on data as much as on code, and models decay, so you also need Continuous Training (CT) — automatically retraining and validating models as new data arrives[1].
CI vs CD vs CT in ML
| Practice | Triggered by | What runs | Output |
|---|---|---|---|
| CI | Pull request / push | Lint, unit tests for features, data-schema tests, a quick training smoke test on a small sample | Green/red check on the PR |
| CD | Merge to main / new approved model version | Build Docker image, deploy pipeline or serving service, canary, rollback on failure | Running service / pipeline |
| CT | Schedule, new data, drift alert | Full training pipeline → evaluation → quality gate → registry | New model version (+ alias if it wins) |
What to test: the ML Test Score
Breck et al. (Google) proposed a rubric of concrete tests in four areas — data, model development, ML infrastructure and monitoring — to measure production readiness and reduce technical debt[2]. Examples you can automate:
- Data: schema and types, allowed ranges, null rates, label balance, no duplicate IDs, no train/test overlap, feature expectations encoded as tests.
- Features & code: unit tests for every transformation (edge cases: zeros, missing values, unseen categories).
- Model: beats the Baseline and the current champion; no slice regresses; invariance tests (changing a customer's name must not change the score); a tiny overfit test (can the model memorise 32 examples?).
- Infrastructure: training is reproducible, the serving model gives the same predictions as offline (no training-serving skew), the model loads and answers within the latency budget, rollback works.
import numpy as np
import pandas as pd
import pytest
@pytest.fixture(scope="module")
def df():
return pd.read_parquet("data/processed/train.parquet")
def test_schema(df):
expected = {"customer_id", "tenure_months", "monthly_charges", "contract", "churned"}
assert expected <= set(df.columns)
def test_ranges_and_nulls(df):
assert df["tenure_months"].between(0, 600).all()
assert (df["monthly_charges"] > 0).all()
assert df["churned"].isin([0, 1]).all()
assert df["monthly_charges"].isna().mean() < 0.01
def test_no_duplicate_customers(df):
assert df["customer_id"].is_unique
# --- model behaviour tests ---------------------------------------------
from src.model import load_model, predict_proba # your own code
def test_invariance_to_irrelevant_field():
m = load_model()
a = pd.DataFrame([{"tenure_months": 5, "monthly_charges": 70.0,
"contract": "monthly", "customer_name": "Ana"}])
b = a.assign(customer_name="Budi")
assert np.isclose(predict_proba(m, a), predict_proba(m, b)).all()
def test_directional_expectation():
m = load_model()
short = pd.DataFrame([{"tenure_months": 1, "monthly_charges": 90.0, "contract": "monthly"}])
loyal = short.assign(tenure_months=60, contract="two_year")
assert predict_proba(m, short)[0] > predict_proba(m, loyal)[0]pytestA GitHub Actions pipeline for ML
name: ml-pipeline
on:
pull_request:
push:
branches: [main]
schedule:
- cron: "0 3 * * 1" # continuous training: Mondays 03:00 UTC
workflow_dispatch: # manual "retrain now" button
jobs:
test-train-gate:
runs-on: ubuntu-latest
env:
MLFLOW_TRACKING_URI: ${{ secrets.MLFLOW_TRACKING_URI }}
AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
cache: pip
- run: pip install -r requirements.txt # includes dvc[s3], mlflow, pytest
- name: Lint and unit tests
run: |
ruff check src tests
pytest -q tests/unit
- name: Pull versioned data
run: dvc pull
- name: Data validation tests
run: pytest -q tests/test_data.py
- name: Train (sample on PRs, full data on main/schedule)
run: |
if [ "${{ github.event_name }}" = "pull_request" ]; then
python -m src.train --config configs/ci_sample.yaml
else
python -m src.train --config configs/full.yaml --register-as challenger
fi
- name: Model tests + quality gate
if: github.event_name != 'pull_request'
run: |
pytest -q tests/test_model.py
python -m src.quality_gate --model churn-clf --min-gain 0.005import argparse, sys
from mlflow import MlflowClient
p = argparse.ArgumentParser()
p.add_argument("--model"); p.add_argument("--min-gain", type=float, default=0.0)
args = p.parse_args()
client = MlflowClient()
def score(alias):
mv = client.get_model_version_by_alias(args.model, alias)
return mv, client.get_run(mv.run_id).data.metrics["val_pr_auc"]
challenger, s_new = score("challenger")
champion, s_old = score("champion")
print(f"challenger v{challenger.version}: {s_new:.4f} champion v{champion.version}: {s_old:.4f}")
if s_new < s_old + args.min_gain:
sys.exit("Quality gate FAILED - champion stays") # non-zero exit fails the CI job
client.set_registered_model_alias(args.model, "champion", challenger.version)
print("Promoted to @champion")Notice the pattern: tests and training run in CI, results land in MLflow, and the registry alias is the deployment contract. The serving service (previous lesson) loads @champion, so a successful gate deploys the new model without changing serving code; a failed gate leaves production untouched. GitHub Actions workflows are YAML files in .github/workflows/ triggered by events like pull_request, push, schedule and workflow_dispatch[3].
- What it is
- How much the challenger must beat the champion on the validation metric to be promoted.
- ↑ If you increase it
- Avoids churn from noise-level “wins”; may reject genuinely better models when gains are small.
- ↓ If you decrease it
- 0 or negative (“not worse than”) keeps models fresh after drift, but random fluctuations can swap models back and forth.
- Typical values
- About the run-to-run standard deviation of the metric (measure it with several seeds).
- What it is
- How much data the quick training smoke test on each pull request uses.
- ↑ If you increase it
- Catches more problems (e.g. convergence issues) but CI gets slow and costly; developers start skipping it.
- ↓ If you decrease it
- Fast feedback (minutes), but only proves the pipeline runs end to end, not that the model is good.
- Typical values
- A fixed, versioned sample of 1–5% of the data or a few thousand rows; keep CI under ~10 minutes.
- What it is
- How often the full continuous-training pipeline runs automatically (in addition to drift-triggered runs).
- ↑ If you increase it
- More frequent retrains track fast-changing data, at higher compute cost and more model churn to monitor.
- ↓ If you decrease it
- Cheaper and calmer, but the model ages between runs.
- Typical values
- Daily for news/ads, weekly–monthly for most business models.
Feature stores and training-serving skew
Training-serving skew happens when a feature is computed one way in the training pipeline (e.g. SQL over historical tables) and another way in the online service (e.g. Python over a live request) — the model then sees subtly different inputs in production. A [[feature-store]] defines each feature once and serves it from two places: an offline store (historical values with point-in-time-correct joins, so training never peeks at future values) and an online store (latest values with millisecond lookups for serving)[4].
from feast import FeatureStore
import pandas as pd
store = FeatureStore(repo_path="feature_repo") # after: feast apply
features = ["customer_stats:avg_monthly_charges_90d",
"customer_stats:support_tickets_30d"]
# Training: point-in-time-correct join against historical labels
labels = pd.read_parquet("data/labels.parquet") # customer_id, event_timestamp, churned
train_df = store.get_historical_features(entity_df=labels, features=features).to_df()
# Serving: latest values from the online store (after feast materialize-incremental)
online = store.get_online_features(
features=features, entity_rows=[{"customer_id": 1001}]).to_dict()- What it is
- How often feature values are computed and copied from the offline source into the online store.
- ↑ If you increase it
- Materialising more often (or streaming) gives fresher features and better predictions for fast-moving signals, at higher infrastructure cost.
- ↓ If you decrease it
- Cheaper, but serving sees stale values — a form of skew if training used fresher ones.
- Typical values
- Hourly–daily batch for slow aggregates; streaming for minute-level signals (fraud).
▸Go deeper: how the ML Test Score is computed
In Breck et al.'s rubric each test earns half a point if it is done manually with documented results and a full point if it is automated and runs repeatedly. Points are summed per section (data, model, infrastructure, monitoring), and the final score is the minimum of the four section scores — a team with perfect model tests but no monitoring still scores low, because the weakest area is what breaks in production[2]. Combined with Google's maturity levels (manual → pipeline automation → CI/CD automation)[1], it gives a practical roadmap: automate the weakest section first.
Kreuzberger et al. list the same building blocks as core MLOps components: source-code repository, CI/CD component, workflow orchestration, feature store, model training infrastructure, model registry, ML metadata store and monitoring[5].
Quiz
avg_spend_30d is computed in SQL for training and in Python for the API, with a small rounding difference. What is this problem called?--min-gain 0 and the champion changes almost every week, sometimes swapping back to an older version. What should you try?References
- [1]MLOps: Continuous delivery and automation pipelines in machine learningArticleGoogle Clouddocs.cloud.google.com
- [2]The ML Test Score: A Rubric for ML Production Readiness and Technical Debt ReductionPaperBreck et al.2017research.google
- [3]GitHub Actions documentationDocsGitHubdocs.github.com
- [4]Feast documentationDocsFeastdocs.feast.dev
- [5]Machine Learning Operations (MLOps): Overview, Definition, and ArchitecturePaperKreuzberger et al.2022arxiv.org