We are to design a training-to-serving schema harmonization process that manages feature definitions and contract tests.
The goal is to ensure that the features used during model training are the same as those used during serving (inference).
We'll outline a process that includes:
Definition of features (feature schema) in a central registry.
Use of the same feature definitions in both training and serving code.
Contract tests (e.g., schema tests, feature value tests) to validate that the serving environment is using the same features as training.
Steps:
I. Centralized Feature Registry
- A central place (like a database, config files in version control, or a feature store) where each feature is defined with:
* name
* data type (e.g., int, float, string)
* validation rules (e.g., min, max, allowed values)
* description
* perhaps, transformation logic (if applicable)
II. Training Pipeline
- During training, the feature definitions are read from the central registry.
- The training data is validated against the feature definitions (contract test at training time).
- The model is trained using the features as defined.
III. Serving Pipeline
- During serving (inference), the same feature definitions are read from the central registry.
- The incoming request data is validated against the feature definitions (contract test at serving time).
- The model uses the same features (with same transformations) as during training.
IV. Contract Tests (Continuous Validation)
- We need to ensure that the feature definitions used in training and serving are exactly the same.
- We can have a test that compares the feature definitions from the registry used in training and serving.
- Additionally, we can have tests that:
a) Check that the schema (feature names and types) of the input data in serving matches the training schema.
b) Check that the feature values in serving are within the same bounds as during training (if applicable).
V. Implementation Steps
code
A. Define a Feature Schema Format
- Example (using JSON Schema or a custom format):
{
"features": [
{
"name": "age",
"type": "integer",
"min": 0,
"max": 120
},
{
"name": "income",
"type": "float",
"min": 0.0
}
]
}
B. Store the Feature Schema in a Version-Controlled Repository
- So that we can track changes and use the same version in training and serving.
C. In Training Code:
- Load the feature schema (from a file or a feature store API) for the specific version.
- Validate the training data against the schema.
- Save the feature schema version along with the model (so that we know which schema was used for training).
D. In Serving Code:
- Load the same feature schema (by version, or the latest if the model specifies the version).
- Validate the incoming request data against the schema.
- Use the same transformations (if any) as in training (these might be defined in the registry as well).
E. Contract Tests (as part of CI/CD):
- Test that the feature schema used in the current training pipeline matches the one used in the current serving pipeline (for the same model version).
- Test that the serving code can load the feature schema and validate a sample request.
F. Monitoring in Production:
- Log the feature schema version used for each prediction (or at least the model and feature schema version).
- Monitor for feature distribution shifts (but that's beyond schema harmonization).
VI. Example Workflow:
code
1. Data scientist defines a new feature set (version 1) and stores it in the registry.
2. Training job uses feature schema version 1 to train a model (model v1). The model is stored with metadata: feature_schema_version=1.
3. When deploying model v1, the serving service is configured to use feature schema version 1 (or reads it from the model metadata).
4. Contract test:
- Check that the serving service's configuration (or model metadata) points to the same feature schema version as the training job.
- Check that the serving code's feature definitions (if any) match the registry's for that version.
5. If we update the feature schema to version 2, we must retrain the model (or at least change the serving to use the new schema only with a model that was trained on it). We cannot mix and match.
VII. Tools and Technologies:
code
- Feature Store: e.g., Feast, Tecton, or a custom solution.
- Schema Registry: e.g., Confluent Schema Registry (if using Avro/Protobuf) or a custom one.
- Contract Testing: e.g., using Pact (for API contracts) but for features we might write custom tests.
VIII. Challenges:
code
- Ensuring that the same version of the feature schema is used in both training and serving.
- Handling schema evolution (how to update the schema and retrain models).
- Managing multiple models with different feature schemas.
IX. Summary:
code
We need a process that:
1. Centralizes feature definitions.
2. Version controls them.
3. Uses them in both training and serving.
4. Validates that the same version is used in both.
5. Tests the contract (schema and possibly value ranges) at deployment time.
Let's write a sample design in more detail.
I'll design a comprehensive training-to-serving schema harmonization process that ensures feature consistency across ML pipelines. This solution addresses the common problem of "training-serving skew" where feature definitions diverge between training and production.
Option C: Git-based registry with version-controlled YAML/JSON files
Option D: Database table with audit history
Recommended: Hybrid approach - Git for definition + Feature Store for materialization.
2. Training Pipeline Integration
2.1 Feature Retrieval
python
# Training script example
from feature_registry import get_feature_vector
# Load exact feature definitions used for training
feature_vector = get_feature_vector(
feature_names=["user_age", "avg_transaction_30d", "is_premium"],
entity_ids=training_entities,
version="v1.2.0", # Pinned version
timestamp=training_timestamp # Point-in-time correctness
)
# Validate against registry schema
validate_feature_vector(feature_vector, registry_schema)
# Train model
model.fit(feature_vector, labels)
2.2 Training-Time Validation
Schema Compliance Test: All features match registry types/ranges
Completeness Test: No missing required features
Point-in-Time Test: Features computed at correct historical timestamp
Drift Test: Compare feature distributions with expected baseline
3. Serving Pipeline Integration
3.1 Feature Retrieval at Inference
python
# Serving code example
from feature_registry import get_online_features
def predict(request):
# Get features using same version as model
features = get_online_features(
feature_names=model.feature_names,
entity_ids=request.entity_ids,
version=model.metadata.feature_schema_version # From model artifact
)
# Validate request against schema
validate_request(request, registry_schema)
return model.predict(features)
Availability Check: All required features available online
Freshness Check: Feature values within acceptable staleness window
Transformation Consistency: Same code/logic as training
4. Contract Test Framework
4.1 Contract Test Types
Test Type
Purpose
Execution
Schema Contract
Feature names/types match
Training artifact ↔ Serving config
Logic Contract
Transformation code identical
Git diff of transformation functions
Version Contract
Same registry version
Compare pinned versions
Value Range Contract
Statistical distributions compatible
KS-test on sample data
Dependency Contract
Source data dependencies match
Compare source table requirements
4.2 Implementation with Pytest
python
# tests/contract/test_feature_schema.py
import pytest
from feature_registry import RegistryClient
from model_artifacts import load_model_metadata
def test_feature_schema_contract():
"""Test that model and serving use identical feature schema"""
model_meta = load_model_metadata("model_v1.2.0")
serving_config = load_serving_config("production")
# Compare pinned registry versions
assert model_meta.feature_schema_version == \
serving_config.feature_schema_version
# Compare feature definitions
registry = RegistryClient()
model_features = registry.get_features(model_meta.feature_schema_version)
serving_features = registry.get_features(serving_config.feature_schema_version)
assert model_features == serving_features
def test_transformation_code_contract():
"""Test that transformation logic is identical"""
model_meta = load_model_metadata("model_v1.2.0")
for feature_name in model_meta.feature_names:
train_code = get_transformation_code(feature_name, "training")
serve_code = get_transformation_code(feature_name, "serving")
# Normalize whitespace/comments for comparison
assert normalize_code(train_code) == normalize_code(serve_code)
def test_point_in_time_correctness():
"""Test that point-in-time features are computed correctly"""
test_event = {
"entity_id": "user_123",
"event_timestamp": "2024-01-10T14:30:00Z"
}
# Compute features using training pipeline logic
training_features = compute_features_training(test_event)
# Compute features using serving pipeline logic
serving_features = compute_features_serving(test_event)
assert training_features == serving_features
5. CI/CD Integration
5.1 Pre-Deployment Gates
yaml
# .github/workflows/deploy.yml
jobs:
validate-contract:
runs-on: ubuntu-latest
steps:
- name: Check feature schema version match
run: |
python scripts/validate_schema_version.py \
--model-artifact s3://models/v1.2.0 \
--serving-config config/production.yaml
- name: Run contract test suite
run: |
pytest tests/contract/ \
--feature-version $(get_model_feature_version) \
--serving-config config/production.yaml
- name: Validate data quality
run: |
python scripts/validate_feature_distributions.py \
--training-data data/training/v1.2.0/features.parquet \
--sample-serving-data data/serving/sample.parquet
5.2 Deployment Pipeline
code
1. Model Training Complete
└─> Feature schema version captured in model metadata
2. Staging Deployment
└─> Contract tests run against staging serving environment
└─> If pass: Promote to production
3. Production Deployment
└─> Final contract verification
└─> Canary validation with shadow traffic
4. Post-Deployment Monitoring
└─> Continuous drift detection
└─> Schema mismatch alerts
6. Version Management Strategy
6.1 Semantic Versioning
MAJOR: Breaking changes (feature removed, type changed)
MINOR: Additive changes (new feature, looser constraints)
PATCH: Documentation fixes, bug fixes in validation logic
6.2 Compatibility Matrix
code
Training Schema Version | Compatible Serving Versions
------------------------|---------------------------
v1.0.0 | v1.0.x only
v1.1.0 | v1.1.x, v1.0.x (if backward compatible)
v2.0.0 | v2.x.x only (breaking change)
6.3 Migration Path
Additive changes: Deploy new features to serving first (with defaults), then retrain model
Breaking changes:
Deploy new serving version alongside old
Train new model with new schema
Gradual traffic shift with feature flag
Decommission old schema after migration complete
7. Monitoring & Alerting
7.1 Key Metrics
python
monitoring_metrics = {
"feature_schema_mismatch": "Count of prediction requests with schema violations",
"feature_availability": "% of required features available at inference",
"feature_freshness": "Max staleness of feature values",
"transformation_latency": "P99 time for feature computation",
"contract_test_failure_rate": "% of contract tests failing"
}
Set up centralized feature registry (Git-based initially)
Define feature schema standard
Implement basic contract tests for schema matching
Phase 2: Integration (2-3 weeks)
Modify training pipeline to use registry
Modify serving pipeline to validate against registry
Implement version pinning in model artifacts
Phase 3: Automation (1-2 weeks)
CI/CD integration of contract tests
Pre-deployment validation gates
Basic monitoring alerts
Phase 4: Advanced (Ongoing)
Point-in-time correctness validation
Feature distribution drift detection
Automated schema migration tools
Cross-team governance dashboard
10. Governance & Best Practices
Mandatory Requirements:
All features MUST be registered before use in training
Every model MUST reference feature schema version
Contract tests MUST pass before deployment
Change Management:
Schema changes require PR review from serving team
Breaking changes need migration plan approval
Deprecation period of at least 2 versions
Documentation:
Feature catalog with examples and ownership
Clear migration guides for schema changes
Runbooks for schema mismatch incidents
Access Control:
Schema modifications restricted to senior engineers
Read access for all ML practitioners
Audit log of all schema changes
Key Benefits of This Design
✅ Eliminates training-serving skew through single source of truth
✅ Prevents silent failures with proactive contract testing
✅ Enables safe schema evolution with versioning and compatibility matrix
✅ Improves observability with dedicated monitoring
✅ Facilitates collaboration between training/serving teams
✅ Supports regulatory compliance with full feature lineage
This process ensures that what you train is exactly what you serve, dramatically reducing production ML failures due to feature inconsistencies.