The user wants a "data contract testing harness."
This harness needs to do three main things:
- Provision synthetic producers/consumers: It needs to generate fake data (producers) and read that data (consumers) automatically.
- Verify schemas: It needs to check if the data structure matches a predefined definition (e.g., Avro, Protobuf, JSON Schema).
- Measure data quality drift: It needs to detect statistical changes or anomalies in the data values over time, not just the structure.
Target Audience/Context: Likely a Data Engineer or Platform Engineer looking to implement Data Mesh or strict data governance. They need code, not just theory.
Key Technologies:
- Language: Python is the standard for data engineering.
- Messaging/Storage: Kafka is the most common use case, but a file-based approach (Parquet/Delta) is easier to demo without infrastructure setup. I will stick to a modular design but default to a JSON/In-memory or file-based approach for the MVP code, perhaps mentioning Kafka adapters. Correction: A streaming context (Kafka) is implied by "producers/consumers". I will use the
confluent-kafka library logic or a mock implementation to make it runnable without a live cluster, or use a lightweight broker like Redpanda. Decision: I'll write a harness that abstracts the transport layer so it can be tested locally but deployed against Kafka.
- Schema Registry: Confluent Schema Registry is standard. I'll simulate a simple registry for the demo.
- Quality Framework: Great Expectations (GX) or Soda Core. GX is very Pythonic and easy to embed. I will use Great Expectations.
Architecture of the Harness:
- Contract Definition: A YAML or JSON file defining the schema (fields, types) and quality rules (mean, nullability, regex).
- Synthetic Generator: A component that reads the contract and produces valid (and intentionally invalid) data.
- Validator (Schema): Checks structure.
- Validator (Quality): Checks stats/distribution (Great Expectations).
- Drift Detector: Compares current batch stats against a baseline.
Step-by-Step Implementation Plan:
- Step 1: The Contract Definition. Define a simple schema (e.g.,
User event).
- Step 2: The Producer. A class that generates random user events based on the schema.
- Step 3: The Consumer & Validator. A class that reads data, validates schema, and runs GX suites.
- Step 4: Drift Detection. A mechanism to store historical stats and compare them (e.g., KL Divergence or simple threshold comparison).
- Step 5: The Harness/Orchestrator. Ties it all together.
Refining the Code Structure:
- Use
pydantic for the schema definition/verification (it's cleaner than raw JSON schema for Python).
- Use
pandas for data manipulation.
- Use
great_expectations for quality checks.
Drafting the Logic (Mental or scratchpad):
- Contract:
id: int, age: int [0-100], signup_date: datetime.
- Quality Rules:
age mean should be ~40. id unique.
- Producer: Faker library is perfect here.
- Drift: If
age suddenly jumps to mean 80, alert.
Detailed Features:
- Synthetic Producer: Use
Faker.
- Schema Verifier: Use
Pydantic or Fastavro. Let's use Pydantic for ease of use in Python, but acknowledge Avro for production. Let's stick to Pydantic for the "Schema" part to make the code runnable immediately.
- Quality/Drift: Use
Pandas + Great Expectations.
Writing the Code (Iterative refinement):
- Imports:
json, random, pandas, pydantic, great_expectations.
- Contract: A class defining the data model.
- Synthetic Producer: A function yielding dictionaries.
- Harness: The main class.
Self-Correction during thought process: Great Expectations can be heavy to set up inline. Maybe I should implement a simpler statistical drift detector for the MVP to keep the code concise and dependency-light, while mentioning GX as the production approach.
Decision: I will implement a custom lightweight "Drift Monitor" using Pandas for the demo so the user can run the script immediately without complex GX setup, but I will structure it so GX could plug in.
Structure of the Final Response:
- Concept Overview: Briefly explain the components.
- The Python Solution: A complete, runnable script.
- Dependencies (
pip install...)
- Data Model (The Contract)
- Producer (Synthetic Data)
- Consumer/Validator (Schema & Quality)
- Drift Detector (Statistics)
- How to Run: Instructions.
- Production Considerations: How to scale this to Kafka, Snowflake, etc.
Let's write the code components.
- Contract: Use a YAML/Dict config style.
- Producer:
Faker.
- Drift: Calculate mean/std dev of numeric columns. Check if current batch mean is > 2 sigma away from historical mean.
Refining the Drift Logic:
Need a BaselineProfile and a CurrentProfile.
BaselineProfile: mean=50, std=5.
CurrentBatch: mean=70. Drift detected.
Final Polish:
Ensure error handling is clean. Make the output readable.
(Self-Correction on "Producers/Consumers"):
The prompt asks to "provision" them. In a local script, this means creating the objects. In Kubernetes, it means spinning up pods. I will provide a local simulation framework that abstracts the producer/consumer logic so it can be swapped for real Kafka clients later.
Let's go. Use Python, Pandas, and Faker. It's the most practical stack for this.
- File 1:
contract.py (The definition)
- File 2:
harness.py (The logic)
- File 3:
main.py (The runner)
Actually, putting it in one modular block is better for a chat response.
Key Code Sections:
DataContract: Pydantic model + Quality constraints.
SyntheticProducer: Generates data based on DataContract.
QualityMonitor: Checks for drift using simple Z-score logic on numerical features.
TestHarness: Orchestrates the flow.
Let's write the solution.
This solution provides a complete Data Contract Testing Harness implemented in Python.
It is designed to be technology-agnostic regarding the transport layer (it uses an in-memory bus for simulation) but strictly enforces schema validity (using Pydantic) and data quality (using statistical drift detection).
Architecture of the Harness
- The Contract: A Pydantic model defining the schema and strict constraints (e.g.,
age must be non-negative).
- Synthetic Producer: Uses the
Faker library to generate realistic data that conforms (or intentionally violates) the contract.
- Drift Detector: A statistical monitor that establishes a baseline of data distribution and alerts if the incoming synthetic data shifts significantly (simulating a "broken" producer).
- The Harness: Orchestrates the production, validation, and monitoring loops.
Prerequisites
You will need to install the following libraries:
pip install pydantic faker pandas numpy
The Testing Harness Code
Save this into a file named contract_harness.py.
import asyncio
import random
import numpy as np
import pandas as pd
from datetime import datetime
from typing import List, Optional, Dict, Any
from pydantic import BaseModel, Field, ValidationError, field_validator
from faker import Faker
from dataclasses import dataclass, field
from enum import Enum
# ==========================================
# 1. THE DATA CONTRACT (Schema & Semantics)
# ==========================================
class UserStatus(str, Enum):
ACTIVE = "active"
INACTIVE = "inactive"
SUSPENDED = "suspended"
class UserContract(BaseModel):
"""
Defines the strict schema for the 'user' data product.
This serves as the 'Interface' between Producer and Consumer.
"""
user_id: str
email: str
age: int = Field(..., ge=0, le=120) # Semantic rule: Age must be realistic
status: UserStatus
signup_ts: datetime
account_balance: float
@field_validator('email')
@classmethod
def email_must_be_valid(cls, v: str) -> str:
if "@" not in v:
raise ValueError("Invalid email format")
return v
# ==========================================
# 2. SYNTHETIC PRODUCER
# ==========================================
class SyntheticProducer:
def __init__(self, inject_bad_schema: bool = False, inject_drift: bool = False):
self.fake = Faker()
self.inject_bad_schema = inject_bad_schema
self.inject_drift = inject_drift
def generate_record(self) -> Dict[str, Any]:
"""Generates a single record dictionary."""
# Logic to simulate Data Drift (changing statistical properties)
# E.g., Suddenly everyone is a child (age drift)
if self.inject_drift and random.random() > 0.7:
age = random.randint(0, 5)
else:
age = random.randint(18, 70)
# Logic to simulate Schema Violation
# E.g., Sending an integer as an ID instead of string, or negative age
if self.inject_bad_schema and random.random() > 0.8:
return {
"user_id": 12345, # Wrong type (int vs str)
"email": "bad-email",
"age": -5,
"status": "alien", # Invalid Enum
"signup_ts": "yesterday", # Wrong format
"account_balance": "rich"
}
return {
"user_id": f"user_{random.randint(1000, 9999)}",
"email": self.fake.email(),
"age": age,
"status": random.choice(list(UserStatus)),
"signup_ts": datetime.now(),
"account_balance": round(random.uniform(100, 10000), 2)
}
# ==========================================
# 3. DATA QUALITY & DRIFT MONITOR
# ==========================================
@dataclass
class DriftReport:
is_drift_detected: bool
metric_name: str
baseline_mean: float
current_mean: float
deviation_pct: float
class DataQualityMonitor:
def __init__(self, sensitivity: float = 0.2):
self.baseline_stats: Dict[str, float] = {}
self.sensitivity = sensitivity # 20% deviation threshold
def train_baseline(self, data: List[UserContract]):
"""Calculates baseline statistics from a valid training set."""
df = pd.DataFrame([model.model_dump() for model in data])
self.baseline_stats['age_mean'] = df['age'].mean()
self.baseline_stats['balance_mean'] = df['account_balance'].mean()
print(f"--- Baseline Trained: Age Mean={self.baseline_stats['age_mean']:.2f} ---")
def check_drift(self, batch: List[UserContract]) -> DriftReport:
"""Compares current batch against baseline."""
if not self.baseline_stats:
raise Exception("Baseline not trained")
df = pd.DataFrame([model.model_dump() for model in batch])
current_age_mean = df['age'].mean()
baseline = self.baseline_stats['age_mean']
deviation = abs(current_age_mean - baseline) / baseline
if deviation > self.sensitivity:
return DriftReport(
is_drift_detected=True,
metric_name="age_mean",
baseline_mean=baseline,
current_mean=current_age_mean,
deviation_pct=deviation * 100
)
return DriftReport(is_drift_detected=False, metric_name="age_mean",
baseline_mean=baseline, current_mean=current_age_mean, deviation_pct=0)
# ==========================================
# 4. THE TESTING HARNESS
# ==========================================
class ContractTestHarness:
def __init__(self):
self.valid_buffer: List[UserContract] = []
self.monitor = DataQualityMonitor()
async def consume_batch(self, producer: SyntheticProducer, batch_size: int = 50):
raw_batch = [producer.generate_record() for _ in range(batch_size)]
valid_records = []
schema_errors = 0
# 1. Schema Verification
for record in raw_batch:
try:
# Pydantic Validation
validated = UserContract(**record)
valid_records.append(validated)
except ValidationError as e:
schema_errors += 1
# In a real system, route to Dead Letter Queue (DLQ)
print(f"Batch Received: {len(raw_batch)} records | Valid: {len(valid_records)} | Schema Errors: {schema_errors}")
# 2. Data Quality Drift Measurement (Only if schema passed)
if valid_records:
drift_report = self.monitor.check_drift(valid_records)
if drift_report.is_drift_detected:
print(f"!!! DRIFT ALERT !!! Metric: {drift_report.metric_name} shifted "
f"from {drift_report.baseline_mean:.2f} to {drift_report.current_mean:.2f} "
f"({drift_report.deviation_pct:.1f}% change)")
async def run(self):
print("=== PHASE 1: Baseline Training ===")
# Create a "Good" producer to train the baseline
good_producer = SyntheticProducer(inject_bad_schema=False, inject_drift=False)
training_data = []
# Generate 200 valid records to establish "Normal"
for _ in range(200):
rec = good_producer.generate_record()
try:
training_data.append(UserContract(**rec))
except:
pass
self.monitor.train_baseline(training_data)
print("\n=== PHASE 2: Steady State Testing ===")
# Run a few batches of good data
for _ in range(2):
await self.consume_batch(good_producer, batch_size=100)
await asyncio.sleep(0.5)
print("\n=== PHASE 3: Injecting Schema Violations ===")
bad_schema_producer = SyntheticProducer(inject_bad_schema=True)
await self.consume_batch(bad_schema_producer, batch_size=50)
print("\n=== PHASE 4: Injecting Data Drift (Semantic Change) ===")
# Producer changes logic: Now generating mostly toddlers (Age drift)
drift_producer = SyntheticProducer(inject_drift=True)
for _ in range(3):
await self.consume_batch(drift_producer, batch_size=100)
await asyncio.sleep(0.5)
# ==========================================
# 5. EXECUTION
# ==========================================
if __name__ == "__main__":
harness = ContractTestHarness()
asyncio.run(harness.run())
How It Works
1. The Contract (UserContract)
We use Pydantic BaseModel. This acts as the "Source of Truth."
- Schema Enforcement: It automatically checks types (e.g.,
user_id must be a string).
- Semantic Rules: We added
Field(ge=0, le=120) to ensure age is physically possible.
- Custom Validators: The
@field_validator ensures email strings contain an @.
2. Synthetic Producer (SyntheticProducer)
This class simulates an upstream data team or microservice.
- It uses
Faker to generate realistic PII (emails, names).
- It has flags (
inject_bad_schema, inject_drift) to intentionally break the system to verify the harness is working.
3. The Quality Monitor (DataQualityMonitor)
Schema validation is not enough. Data might pass the schema but be statistically wrong (e.g., database corruption sets all user ages to 0).
- Baseline: We feed it "historical good data" to calculate a mean (average).
- Drift Detection: When new data arrives, we compare the
mean of the new batch against the baseline. If the difference exceeds the sensitivity threshold (20% in this example), it fires an alert.
4. The Harness Loop
The run method simulates the lifecycle of a data pipeline:
- Training: Establishes what "good" data looks like.
- Steady State: Runs normal data; expects no errors.
- Schema Attack: Sends malformed JSON; expects Pydantic errors.
- Drift Attack: Sends valid schemas but statistically weird data (toddlers); expects Drift Alerts.
Extending for Production
To move this from a PoC to a Production tool:
- Transport: Replace the in-memory lists with Kafka consumers or S3 bucket listeners.
- Schema Registry: Load the
UserContract from a central Schema Registry (like Confluent or Glue) instead of hardcoding it.
- Advanced Drift: Replace the simple mean check with KL Divergence or Population Stability Index (PSI) for better accuracy with non-normal distributions.
- Orchestration: Containerize this harness and run it as a CronJob (Kubernetes) or Airflow DAG to constantly probe your data pipelines.