We are going to design a CI pipeline for ML code that includes:
- Unit tests (for both data processing and model code)
- Data contract checks (to ensure data quality and schema adherence)
- Pipeline linting (code style, structure, and best practices for ML pipelines)
We assume the project structure is typical for ML projects:
project/
├── src/
│ ├── data/
│ │ ├── init.py
│ │ ├── data_loader.py
│ │ └── preprocessor.py
│ ├── models/
│ │ ├── init.py
│ │ ├── model.py
│ │ └── train.py
│ └── pipelines/
│ ├── init.py
│ └── training_pipeline.py
├── tests/
│ ├── unit/
│ │ ├── test_data_loader.py
│ │ ├── test_preprocessor.py
│ │ ├── test_model.py
│ │ └── test_train.py
│ └── integration/
│ └── test_pipeline.py
├── data/
│ ├── raw/
│ └── processed/
├── config/
│ └── config.yaml
├── requirements.txt
├── .github/workflows/ci.yml (if using GitHub Actions)
└── ... other files
Steps in the CI pipeline:
- Checkout code
- Set up Python environment (with specific version)
- Install dependencies (from requirements.txt)
- Run unit tests (using pytest, for example)
- Run data contract checks (we can use a tool like
pandera for schema validation, or custom checks)
- Run pipeline linting (using tools like
flake8, black, isort, and maybe ML-specific linters like mlflow or dvc if used, but note: we are focusing on code structure and style)
However, note that data contract checks might require sample data. We can have a small sample data in the repo (or generate it) for testing.
Alternatively, we can structure the data contract checks as part of the unit tests? But let's separate them for clarity.
Let's break down:
- Unit tests: test individual functions and classes.
- Data contract checks: validate that the data meets certain expectations (e.g., no nulls in critical columns, data types, value ranges). We can have a separate script for this that runs on a sample dataset.
- Linting: code style and structure.
We assume we are using GitHub Actions for CI.
Let's create a .github/workflows/ci.yml:
Steps:
- Checkout
- Setup Python
- Cache pip dependencies (optional but recommended)
- Install dependencies
- Run unit tests
- Run data contract checks (we'll create a script for this, e.g.,
scripts/check_data_contracts.py)
- Run linting (flake8, black --check, isort --check)
However, note that black and isort are formatters, so we might want to fail if code is not formatted. Alternatively, we can have a separate step for formatting and then fail if there are changes.
But note: we don't want to change code in CI, just check. So we use --check for black and isort.
Let's write the workflow:
We'll also consider that the data contract checks might require a sample data file. We can have a tests/data/sample.csv or similar.
Alternatively, if we use pandera, we can define schemas and then check the data against them.
Example of a data contract check script:
import pandas as pd
import pandera as pa
Define schema
schema = pa.DataFrameSchema({
"col1": pa.Column(int, pa.Check.gt(0)),
"col2": pa.Column(str, pa.Check.str_length(2, 10)),
})
Load data (sample)
df = pd.read_csv("tests/data/sample.csv")
Validate
schema.validate(df)
But note: we might have multiple data sources and contracts. So we might have a config for contracts.
Alternatively, we can have a function in the code that defines the contracts and then run that function in the CI.
However, for simplicity, let's assume we have a script scripts/check_data_contracts.py that runs all the checks.
We can also integrate data contract checks with the unit tests? But then we are testing the data, which might be part of integration tests.
Let's decide:
- Unit tests: test code (functions, classes) in isolation.
- Data contract checks: test that the data (sample) meets the expected schema and quality. This is more of a data quality test.
- Integration tests: test the entire pipeline (which might include data contract checks as part of the pipeline). But we are asked for data contract checks separately.
So:
- Unit tests:
pytest tests/unit
- Data contract checks:
python scripts/check_data_contracts.py
- Linting:
flake8 src/ and black --check src/ and isort --check src/
But note: we might have configuration files for flake8, black, isort. We assume they are in the root.
Let's create the workflow:
We'll also set up the environment with the same Python version as in production (specified in the project, say 3.8).
We assume the project uses a requirements.txt for dependencies.
Steps:
-
name: Checkout
uses: actions/checkout@v2
-
name: Set up Python 3.8
uses: actions/setup-python@v2
with:
python-version: 3.8
-
name: Cache pip dependencies
uses: actions/cache@v2
with:
path: ~/.cache/pip
key: runner.os−pip−{{ hashFiles('requirements.txt') }}
restore-keys: |
${{ runner.os }}-pip-
-
name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
pip install pytest flake8 black isort pandera # and any other test dependencies
-
name: Run unit tests
run: pytest tests/unit
-
name: Run data contract checks
run: python scripts/check_data_contracts.py
-
name: Run linting
run: |
flake8 src/
black --check src/
isort --check src/
However, note that the data contract checks script might require additional dependencies (like pandera). We can either put them in requirements.txt or install them separately.
But we already installed from requirements.txt, so we assume pandera is in requirements.txt? Or we can have a separate requirements-dev.txt for development and CI.
Let's adjust:
We can have:
requirements.txt: for production
requirements-dev.txt: for development and CI (includes pytest, flake8, black, isort, pandera, etc.)
Then in CI:
pip install -r requirements.txt
pip install -r requirements-dev.txt
Alternatively, we can have one requirements.txt that includes everything. But it's common to separate.
Let's assume we have:
requirements.txt: only production dependencies (like pandas, numpy, scikit-learn, etc.)
requirements-dev.txt: includes everything in requirements.txt plus dev tools.
Then:
pip install -r requirements.txt
pip install -r requirements-dev.txt
But note: if we do that, we might install production dependencies twice? Actually, pip will handle it.
Alternatively, we can have:
requirements-dev.txt: includes -r requirements.txt and then the dev tools.
So:
In requirements-dev.txt:
-r requirements.txt
pytest
flake8
black
isort
pandera
Then in CI:
pip install -r requirements-dev.txt
This ensures we have both production and dev dependencies.
Let's adjust the workflow accordingly.
Also, note that the data contract checks might require the data. We assume we have a sample data file in the repo (like tests/data/sample.csv). If not, we might need to generate it or fetch it.
But for CI, we want to avoid large data. So we should have a small sample.
Alternatively, we can have the data contract checks generate a small synthetic dataset that meets the contract? That might be more complex.
Let's assume we have a small sample in the repo.
Now, what about the scripts/check_data_contracts.py? We haven't created it.
Let's sketch:
scripts/check_data_contracts.py:
import pandas as pd
import pandera as pa
from pathlib import Path
# Define the schema for each dataset we want to check.
# We might have multiple datasets, so we can have a dictionary of schemas and paths.
CONTRACTS = {
"sample_data": {
"path": Path("tests/data/sample.csv"),
"schema": pa.DataFrameSchema({
"col1": pa.Column(int, pa.Check.gt(0)),
"col2": pa.Column(str, pa.Check.str_length(2, 10)),
})
}
}
def check_contract(contract):
df = pd.read_csv(contract["path"])
contract["schema"].validate(df, lazy=True) # lazy=True to collect all errors
if __name__ == "__main__":
for name, contract in CONTRACTS.items():
try:
check_contract(contract)
print(f"✅ {name} passed data contract checks.")
except pa.errors.SchemaErrors as err:
print(f"❌ {name} failed data contract checks:")
print(err)
exit(1)
But note: we might have more complex contracts that require multiple files or more complex validation.
Alternatively, we can have the contracts defined in the code (maybe in the data module) and then import them.
However, for simplicity and to avoid coupling, we might keep the contracts in the CI script? But then we are duplicating the contract definitions.
Alternatively, we can have a module in the project that defines the contracts, and then the CI script uses that.
Let's assume we have a module src/data/contracts.py that defines the schemas.
Then in scripts/check_data_contracts.py:
from src.data.contracts import SCHEMAS
and then use SCHEMAS (which is a dict similar to CONTRACTS above, but defined in the code).
But note: the contracts might depend on the data processing code? Then we are testing the contracts as part of the code.
However, if we change the contract in the code, then the CI will break until we update the sample data? That's the point.
But we must have the sample data in sync with the contract.
Alternatively, we can have the contract defined in the code and then generate a sample that satisfies the contract? That's more advanced.
For now, let's assume we have a fixed sample data and the contract must match it.
But note: the contract is supposed to define the expected structure, so the sample data should satisfy the contract. So if we change the contract, we must change the sample data accordingly.
This is a design decision.
Alternatively, we can have the contract defined separately from the code? But then we are not testing the code's contract.
I think the contract should be defined in the code (so that the code knows what to expect) and then we test that the sample data (which represents the expected input) meets the contract.
So:
In src/data/contracts.py:
import pandera as pa
SAMPLE_DATA_SCHEMA = pa.DataFrameSchema({
"col1": pa.Column(int, pa.Check.gt(0)),
"col2": pa.Column(str, pa.Check.str_length(2, 10)),
})
Then in scripts/check_data_contracts.py:
from src.data.contracts import SAMPLE_DATA_SCHEMA
import pandas as pd
df = pd.read_csv("tests/data/sample.csv")
SAMPLE_DATA_SCHEMA.validate(df)
But wait: what if we have multiple contracts for multiple datasets? Then we can have a dictionary of schemas in contracts.py.
CONTRACTS = {
"sample_data": SAMPLE_DATA_SCHEMA,
"another_data": ANOTHER_SCHEMA,
}
and then in the script:
from src.data.contracts import CONTRACTS
for name, schema in CONTRACTS.items():
df = pd.read_csv(f"tests/data/{name}.csv") # assuming the file name matches the key
schema.validate(df)
But note: the paths might be different. So we can have a configuration that maps contract names to file paths.
Alternatively, we can have the contract definitions include the path? That would be more self-contained.
In contracts.py:
CONTRACTS = {
"sample_data": {
"path": "tests/data/sample.csv",
"schema": SAMPLE_DATA_SCHEMA,
},
...
}
Then in the script:
from src.data.contracts import CONTRACTS
for name, contract in CONTRACTS.items():
df = pd.read_csv(contract["path"])
contract["schema"].validate(df)
This way, the contract definition (including the sample data path) is in the code.
But then the code (contracts.py) has a dependency on the file system? Not really, it just defines the path. The script reads the file.
However, if we run the script from a different directory, we might have issues. We can use absolute paths or paths relative to the project root.
We can use pathlib.Path(__file__).parent.parent to get the project root? But then the contracts.py must know its location.
Alternatively, we can have the paths in the contract definitions be relative to the project root and then in the script we compute the project root.
But let's keep it simple: we assume the CI runs from the project root.
So in the script:
from pathlib import Path
from src.data.contracts import CONTRACTS
for name, contract in CONTRACTS.items():
path = Path(contract["path"])
df = pd.read_csv(path)
contract["schema"].validate(df)
But note: the contract["path"] is a string. We can make it a Path object in the contracts.py? That might be better.
In contracts.py:
from pathlib import Path
CONTRACTS = {
"sample_data": {
"path": Path("tests/data/sample.csv"),
"schema": SAMPLE_DATA_SCHEMA,
},
}
Then in the script:
for name, contract in CONTRACTS.items():
df = pd.read_csv(contract["path"])
contract["schema"].validate(df)
This is acceptable.
However, what if the sample data is not in the repo? Then we might need to generate it or fetch it.
But for CI, we want to keep the repo small, so we have a small sample.
Let's assume we have the sample data in the repo.
Now, what about the linting? We run flake8, black, isort on the src/ directory.
We might also want to lint the tests? But note: the tests are part of the codebase, so we should lint them too.
Let's change:
flake8 src/ tests/
black --check src/ tests/
isort --check src/ tests/
But note: the tests might have a different style? We can configure flake8, black, isort to ignore test directories if needed.
Alternatively, we can have separate configurations for tests? But for simplicity, we lint everything.
Now, let's put it all together in the workflow.
We'll also add a step to export the environment variables? Not necessary.
We assume the project uses a virtual environment? In GitHub Actions, we are installing globally, so we don't need to activate.
But note: the src directory is not in the PYTHONPATH? We are running the script from the project root, and we have src as a module? We can set PYTHONPATH or use relative imports.
Since we are running from the project root and we have src as a package (with init.py), we can run the script as:
python scripts/check_data_contracts.py
and the imports from src.data.contracts will work because the current directory (project root) is in the PYTHONPATH.
Alternatively, we can set the PYTHONPATH in the CI:
export PYTHONPATH=$(pwd)/src
But if we run the script from the project root and the script is in scripts/ and we import src.data.contracts, that should work because the project root is in the path.
However, if we run pytest from the project root, it will also find the src module? Yes, because the project root is in the path.
But note: when we run pytest tests/unit, it will run from the project root and the src is in the path? Actually, pytest adds the root to the path.
So we are safe.
Let's write the workflow:
name: CI
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
ci:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Set up Python 3.8
uses: actions/setup-python@v2
with:
python-version: 3.8
- name: Cache pip dependencies
uses: actions/cache@v2
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-${{ hashFiles('requirements-dev.txt') }}
restore-keys: |
${{ runner.os }}-pip-
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Run unit tests
run: pytest tests/unit
- name: Run data contract checks
run: python scripts/check_data_contracts.py
- name: Run linting
run: |
flake8 src/ tests/
black --check src/ tests/
isort --check src/ tests/
But note: we might want to run the integration tests as well? The problem says unit tests, data contract checks, and pipeline linting. So we are not asked for integration tests.
However, we have an integration test in tests/integration/test_pipeline.py. We might want to run that too? But the problem doesn't specify.
Let's stick to the requirements: unit tests, data contract checks, and linting.
But note: the pipeline linting might include checking the pipeline code? We are linting the code, so we are checking the pipeline code too.
So we are good.
However, what if the data contract checks require more than one sample? We might have multiple contracts for different datasets.
We designed the contracts to be in a dictionary, so we can have multiple.
Now, what about the possibility that the data contract checks might fail because the sample data is not in the repo? We assume it is.
But what if the sample data is generated by the code? Then we might need to run a function to generate it.
We can change the contract definition to include a function that generates the data? That might be too complex.
Alternatively, we can have the sample data in the repo and update it when the contract changes.
This is a trade-off.
Let's assume we keep the sample data in the repo and update it when the contract changes.
Now, what about the linting? We are running flake8, black, isort. We might have configuration files for these (like .flake8, pyproject.toml for black and isort). We assume they are in the root.
If not, we can run without configuration.
But note: the project might have a specific configuration. We assume the configuration files are in the root and the tools will pick them up.
So the workflow is as above.
Let's also consider that we might want to run the data contract checks only on the sample data that is relevant to the changes? But for simplicity, we run on all.
Now, what about the possibility that the data contract checks require a large dataset? We are using a sample, so it should be small.
We can also have a separate job for data contract checks that runs on a schedule? But for every push and PR, we run on the sample.
This should be acceptable.
Let's write the workflow file.
However, note: the workflow file is in .github/workflows/ci.yml.
We'll create that file.
But note: the project might have a different structure. We are assuming the above structure.
If the project has a different structure, we adjust the paths.
Now, what about the requirement of "pipeline linting"? We are linting the code, which includes the pipeline code. But maybe we want to lint the pipeline structure? That might be more about the DAG or the steps.
We are using code linting (flake8, black, isort) which checks the code style. But if by pipeline linting we mean checking the structure of the pipeline (like no circular dependencies, proper order of steps), then we might need a different tool.
However, the problem says "pipeline linting", which could be ambiguous. Since we are in ML, we might be using a pipeline framework (like sklearn's Pipeline, or a custom one). We might want to check that the pipeline is correctly built.
But note: we are already running unit tests on the pipeline? We have a unit test for the training_pipeline? We don't have that in the unit tests? We have a unit test for the model and train, but not for the pipeline.
We might want to add a unit test for the pipeline? But the problem says "pipeline linting", not necessarily unit tests for the pipeline.
Let's break down:
-
Unit tests: we are testing the data_loader, preprocessor, model, train. We are not testing the pipeline (which orchestrates these).
-
Data contract checks: we are checking the data.
-
Pipeline linting: we are linting the code (style). But we might also want to check the pipeline structure? That could be part of unit tests or a separate step.
Since the problem says "pipeline linting", and we are already doing code linting, maybe that's enough? But note: the pipeline might be defined in a config file (like YAML) or in code.
If the pipeline is defined in code (like in training_pipeline.py), then code linting covers it.
If the pipeline is defined in a config file (like a DVC pipeline or an Airflow DAG), then we might need to lint that config file.
But the problem says "ML code", so we assume the pipeline is in code.
Therefore, we are covering the pipeline with code linting.
However, we might want to add a step that checks the pipeline for common mistakes (like missing steps, incorrect order). That would be more of a static analysis of the pipeline.
But without a specific tool, we can only do code linting.
Alternatively, we can write a script that checks the pipeline structure? But that would be project-specific.
Since the problem is general, we stick to code linting.
So the above workflow is acceptable.
Let's write the workflow file.
But note: we are using black --check and isort --check. These will fail if the code is not formatted. We might want to have a step that auto-formats? But that's not for CI, that's for a pre-commit hook.
We are only checking.
Now, let's consider the possibility that the data contract checks might take a long time? We are using a small sample, so it should be fast.
We are done.
However, we must create the scripts/check_data_contracts.py and the src/data/contracts.py and the sample data.
But the problem says "engineer a CI pipeline", so we are designing the pipeline, not implementing the contracts.
So we assume the project already has:
src/data/contracts.py with the CONTRACTS dictionary.
tests/data/sample.csv (or multiple sample files) that satisfy the contracts.
If not, we must create them.
But note: the problem says "engineer a CI pipeline", so we are setting up the CI. The project must have the contracts and sample data.
Alternatively, we can design the CI to run even if the contracts are not defined? Then we skip the data contract step? But we want to fail if the step fails.
So we assume the project has the contracts.
Now, what if the project doesn't use pandera? We are using pandera in the example. The project might use a different library or custom checks.
We can change the check_data_contracts.py to use whatever the project uses.
But we are designing a general CI. We can have a placeholder for the data contract checks.
Alternatively, we can make the data contract checks step run a script that the project must provide.
So in the CI, we run python scripts/check_data_contracts.py and that script is provided by the project.
The project must implement that script to do the data contract checks.
So our CI is generic: it runs that script.
Similarly, for unit tests, we run pytest tests/unit and for linting we run the linters.
So the CI is:
- Install dependencies (from requirements-dev.txt)
- Run unit tests (pytest on tests/unit)
- Run data contract checks (python scripts/check_data_contracts.py)
- Run linting (flake8, black, isort on src/ and tests/)
We are done.
Let's write the workflow file accordingly.
But note: the project might not have a scripts/check_data_contracts.py? Then the CI will fail. We can check for the existence? But we want the project to have it.
Alternatively, we can have a default script that does nothing? But then the step would pass. We want to enforce that the project implements it.
So we assume the project has it.
Now, let's write the workflow file.
However, we must also consider that the project might have a different structure. We are assuming the above structure.
We can make the workflow more flexible by allowing the project to specify the paths? But that's overkill.
We are designing for a typical project.
If the project has a different structure, they can adjust the workflow.
Now, let's write the workflow file.
We'll also add a step to display the versions of the tools? Not necessary.
We'll also consider that the linters might have different configurations. We assume they are in the root.
If the project doesn't have configuration files, the linters will use defaults.
Now, what about the unit tests? We are running pytest tests/unit. What if the project has a different test directory structure? Then they can adjust.
But we are designing for the given structure.
We are done.
Let's write the workflow file.
I'll design a comprehensive CI pipeline for ML code with the three specified components. This pipeline will be implemented using GitHub Actions (but can be adapted to other CI/CD systems).
Project Structure Assumptions
project/
├── src/
│ ├── data/
│ │ ├── ingestion.py
│ │ ├── validation.py
│ │ └── preprocessing.py
│ ├── models/
│ │ ├── train.py
│ │ ├── predict.py
│ │ └── registry.py
│ └── pipelines/
│ └── training_pipeline.py
├── tests/
│ ├── unit/
│ │ ├── test_data_ingestion.py
│ │ ├── test_preprocessing.py
│ │ └── test_model.py
│ ├── integration/
│ │ └── test_pipeline.py
│ └── data_contracts/
│ └── test_data_quality.py
├── config/
│ ├── data_contracts.yaml
│ └── model_params.yaml
├── requirements/
│ ├── base.txt
│ ├── dev.txt
│ └── test.txt
├── .github/workflows/ci.yml
├── pyproject.toml (or setup.cfg)
├── .flake8
├── .isort.cfg
├── .black
└── dvc.yaml (if using DVC)
1. Configuration Files
requirements/test.txt
pytest>=7.0.0
pytest-cov>=4.0.0
pytest-mock>=3.10.0
pytest-xdist>=3.3.0
pandera[io]>=0.16.0 # For data contracts
great-expectations>=0.17.0 # Alternative for data validation
requirements/dev.txt
-r base.txt
-r test.txt
black>=23.0.0
isort>=5.12.0
flake8>=6.0.0
flake8-bugbear>=23.0.0
flake8-docstrings>=1.7.0
mypy>=1.0.0
pre-commit>=3.0.0
dvc[all]>=2.40.0 # If using DVC
mlflow>=2.0.0 # For model tracking
pyproject.toml (or setup.cfg)
[tool.black]
line-length = 88
target-version = ['py38']
[tool.isort]
profile = "black"
line_length = 88
[tool.flake8]
max-line-length = 88
extend-ignore = ["E203", "W503"]
exclude = [".git", "__pycache__", "build", "dist", "*.egg-info"]
config/data_contracts.yaml
data_contracts:
raw_data:
path: "data/raw/training_data.csv"
schema:
columns:
id:
dtype: "int64"
nullable: false
checks:
- "unique"
feature_1:
dtype: "float64"
nullable: false
checks:
- "min_val: 0"
- "max_val: 100"
target:
dtype: "int64"
nullable: false
checks:
- "in_set: [0, 1]"
quality_checks:
- "no_nulls: [id, feature_1, target]"
- "row_count: > 1000"
- "duplicate_rows: 0"
processed_data:
path: "data/processed/training_data.parquet"
schema:
columns:
feature_1_scaled:
dtype: "float64"
nullable: false
checks:
- "min_val: -3"
- "max_val: 3"
2. Data Contract Validation Script
scripts/check_data_contracts.py
#!/usr/bin/env python3
"""
Data contract validation for ML pipelines.
Validates both schema and quality metrics.
"""
import sys
import yaml
from pathlib import Path
import pandera as pa
import pandas as pd
from typing import Dict, Any
class DataContractChecker:
def __init__(self, config_path: str = "config/data_contracts.yaml"):
with open(config_path) as f:
self.config = yaml.safe_load(f)
def load_schema(self, contract: Dict[str, Any]) -> pa.DataFrameSchema:
"""Convert YAML schema to pandera DataFrameSchema"""
columns = {}
for col_name, col_spec in contract["schema"]["columns"].items():
checks = []
if "checks" in col_spec:
for check in col_spec["checks"]:
if check.startswith("min_val:"):
checks.append(pa.Check.ge(float(check.split(":")[1].strip())))
elif check.startswith("max_val:"):
checks.append(pa.Check.le(float(check.split(":")[1].strip())))
elif check.startswith("in_set:"):
values = eval(check.split(":")[1].strip())
checks.append(pa.Check.isin(values))
elif check == "unique":
checks.append(pa.Check.unique())
columns[col_name] = pa.Column(
dtype=col_spec["dtype"],
nullable=col_spec.get("nullable", True),
checks=checks if checks else None,
required=not col_spec.get("nullable", True)
)
return pa.DataFrameSchema(
columns=columns,
index=pa.Index(pa.Int64),
strict=True,
coerce=True
)
def validate_data(self, contract_name: str) -> bool:
"""Validate a single data contract"""
contract = self.config["data_contracts"][contract_name]
data_path = Path(contract["path"])
if not data_path.exists():
print(f"❌ Data file not found: {data_path}")
return False
# Load data
if data_path.suffix == ".csv":
df = pd.read_csv(data_path)
elif data_path.suffix == ".parquet":
df = pd.read_parquet(data_path)
else:
print(f"❌ Unsupported file format: {data_path.suffix}")
return False
# Validate schema
schema = self.load_schema(contract)
try:
schema.validate(df, lazy=True)
print(f"✅ Schema validation passed: {contract_name}")
except pa.errors.SchemaErrors as err:
print(f"❌ Schema validation failed: {contract_name}")
print(err.failure_cases)
return False
# Validate quality checks
quality_checks = contract.get("quality_checks", [])
for check in quality_checks:
if check.startswith("no_nulls:"):
cols = [c.strip() for c in check.split(":")[1].strip("[]").split(",")]
null_counts = df[cols].isnull().sum()
if null_counts.sum() > 0:
print(f"❌ Null values found in {cols}: {null_counts.to_dict()}")
return False
elif check.startswith("row_count:"):
op, val = check.split(":")[1].strip().split()
expected_count = int(val)
actual_count = len(df)
if op == ">" and actual_count <= expected_count:
print(f"❌ Row count {actual_count} not > {expected_count}")
return False
elif op == "<" and actual_count >= expected_count:
print(f"❌ Row count {actual_count} not < {expected_count}")
return False
print(f"✅ All quality checks passed: {contract_name}")
return True
def run_all_checks(self) -> bool:
"""Run all data contract validations"""
all_passed = True
for contract_name in self.config["data_contracts"]:
if not self.validate_data(contract_name):
all_passed = False
return all_passed
if __name__ == "__main__":
checker = DataContractChecker()
success = checker.run_all_checks()
sys.exit(0 if success else 1)
3. GitHub Actions CI Pipeline
.github/workflows/ci.yml
name: ML CI Pipeline
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
lint-and-test:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.8", "3.9", "3.10"]
steps:
- name: Checkout code
uses: actions/checkout@v3
with:
fetch-depth: 0 # For better pre-commit analysis
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Cache pip dependencies
uses: actions/cache@v3
with:
path: |
~/.cache/pip
~/.cache/pypoetry
~/.venv
key: ${{ runner.os }}-pip-${{ hashFiles('**/requirements*.txt') }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements/dev.txt
pip install -e .
- name: Lint with flake8
run: |
flake8 src/ tests/ --count --select=E9,F63,F7,F82 --show-source --statistics
flake8 src/ tests/ --count --exit-zero --max-complexity=10 --max-line-length=88 --statistics
- name: Check formatting with black
run: |
black --check --diff src/ tests/
- name: Check imports with isort
run: |
isort --check-only --profile black src/ tests/
- name: Type checking with mypy (optional)
run: |
mypy src/ --ignore-missing-imports --no-strict-optional
continue-on-error: true # Don't fail on type errors initially
- name: Run unit tests with coverage
run: |
pytest tests/unit/ -v --cov=src --cov-report=xml --cov-report=html --cov-fail-under=80
- name: Run data contract validation
run: |
python scripts/check_data_contracts.py
env:
PYTHONPATH: ${{ github.workspace }}
- name: Run integration tests
run: |
pytest tests/integration/ -v --tb=short
env:
# Set environment variables for integration tests
DATA_PATH: data/raw/
MODEL_DIR: models/
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
with:
file: ./coverage.xml
flags: unittests
name: codecov-umbrella
data-contract-monitor:
runs-on: ubuntu-latest
needs: lint-and-test
if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.9"
- name: Install dependencies
run: |
pip install -r requirements/dev.txt
pip install -e .
- name: Monitor data drift (example)
run: |
python scripts/monitor_data_drift.py --reference data/processed/reference.parquet --current data/processed/latest.parquet
env:
PYTHONPATH: ${{ github.workspace }}
model-validation:
runs-on: ubuntu-latest
needs: lint-and-test
if: github.ref == 'refs/heads/main'
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: "3.9"
- name: Install dependencies
run: |
pip install -r requirements/dev.txt
pip install -e .
- name: Validate model performance
run: |
pytest tests/model_validation/ -v --tb=short
env:
MODEL_PATH: models/production/
TEST_DATA_PATH: data/processed/test.parquet
- name: Check model size
run: |
MODEL_SIZE=$(du -m models/production/model.pkl | cut -f1)
if [ $MODEL_SIZE -gt 100 ]; then
echo "❌ Model size ($MODEL_SIZE MB) exceeds 100MB limit"
exit 1
fi
echo "✅ Model size OK: ${MODEL_SIZE}MB"
notify:
runs-on: ubuntu-latest
needs: [lint-and-test, data-contract-monitor, model-validation]
if: always()
steps:
- name: Send notification
uses: 8398a7/action-slack@v3
with:
status: ${{ job.status }}
channel: "#ml-pipeline-alerts"
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK }}
4. Additional Scripts
scripts/monitor_data_drift.py (optional)
#!/usr/bin/env python3
"""Simple data drift monitoring"""
import sys
import pandas as pd
from scipy import stats
def compare_distributions(ref_path: str, curr_path: str, threshold: float = 0.05):
"""KS test for numerical columns"""
ref_df = pd.read_parquet(ref_path)
curr_df = pd.read_parquet(curr_path)
drift_detected = False
for col in ref_df.select_dtypes(include='number').columns:
if col in curr_df.columns:
stat, p_value = stats.ks_2samp(ref_df[col], curr_df[col])
if p_value < threshold:
print(f"⚠️ Drift detected in {col}: p-value={p_value:.4f}")
drift_detected = True
if not drift_detected:
print("✅ No significant drift detected")
return not drift_detected
if __name__ == "__main__":
success = compare_distributions(sys.argv[1], sys.argv[2])
sys.exit(0 if success else 1)
5. Pre-commit Hooks (.pre-commit-config.yaml)
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/psf/black
rev: 23.3.0
hooks:
- id: black
- repo: https://github.com/pycqa/isort
rev: 5.12.0
hooks:
- id: isort
args: ["--profile", "black"]
- repo: https://github.com/pycqa/flake8
rev: 6.0.0
hooks:
- id: flake8
additional_dependencies: [flake8-bugbear, flake8-docstrings]
- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.0.1
hooks:
- id: mypy
additional_dependencies: [pandas-stubs]
exclude: ^tests/
6. Installation & Usage
- Install pre-commit hooks:
pip install pre-commit
pre-commit install
- Run CI locally (using act):
# Install act (GitHub Actions本地运行工具)
brew install act # macOS
# or download from https://github.com/nektos/act
# Run CI locally
act
- Manual pipeline execution:
# Run all checks manually
make ci # with a Makefile containing:
# ci: lint test data-contracts
# Or individually:
black --check src/ tests/
isort --check-only src/ tests/
flake8 src/ tests/
pytest tests/unit/ tests/integration/
python scripts/check_data_contracts.py
Key Features of This Pipeline:
- Multi-Python version matrix - Tests against multiple Python versions
- Data contracts as code - YAML schemas converted to pandera validation
- Layered testing - Unit → Integration → Data contracts → Model validation
- Quality gates:
- Coverage threshold (80%)
- Code formatting (black/isort)
- Linting (flake8)
- Schema validation
- Data quality checks
- Model size limits
- Scheduled monitoring - Data drift detection on schedule
- Notifications - Slack alerts on pipeline status
- Caching - Pip cache for faster builds
- Separation of concerns - Clear distinction between unit, integration, and contract tests
Adapting to Other CI Systems:
GitLab CI:
stages:
- lint
- test
- data-contracts
- deploy
lint:
stage: lint
script:
- black --check src/
- flake8 src/
test:
stage: test
script:
- pytest tests/unit/
data-contracts:
stage: data-contracts
script:
- python scripts/check_data_contracts.py
Jenkins:
pipeline {
agent any
stages {
stage('Lint') {
steps {
sh 'black --check src/'
sh 'flake8 src/'
}
}
stage('Unit Tests') {
steps {
sh 'pytest tests/unit/ --cov=src'
}
}
stage('Data Contracts') {
steps {
sh 'python scripts/check_data_contracts.py'
}
}
}
post {
always {
junit 'test-results.xml'
cobertura coberturaReportFile: 'coverage.xml'
}
}
}
This pipeline provides:
- Fast feedback (lints + unit tests first)
- Progressive quality gates
- Reproducible environments
- Clear separation between code quality, data quality, and model quality
- Extensible for additional checks (security scanning, performance benchmarks)
Would you like me to adapt this for a specific ML framework (TensorFlow/PyTorch), orchestrator (Airflow/Kubeflow), or deployment target (AWS SageMaker/Azure ML)?