We are going to design a data contract testing harness. The harness should be able to:
- Provision synthetic producers and consumers (i.e., simulate data sources and sinks).
- Verify schemas (i.e., check that the data produced/consumed adheres to a contract/schema).
- Measure data quality drift (i.e., detect changes in the distribution or structure of the data over time).
We'll break down the design into components:
-
Schema Registry/Contract Definition: We need a way to define the expected schema and constraints (maybe using JSON Schema, Avro, etc.). We'll assume we have a way to get the contract (schema) for a given data topic/stream.
-
Synthetic Data Producer: A component that generates synthetic data according to a given schema. It should be able to produce data that is either exactly according to the contract or with some controlled deviations (to test drift).
-
Synthetic Data Consumer: A component that receives data (from the producer) and checks the data against the contract (schema validation) and also measures data quality metrics (like null rate, distinct count, min/max for numeric, etc.) and compares them to a baseline.
-
Drift Detection: We need a way to define what is considered drift. This could be statistical tests (like t-test for numeric, chi-square for categorical) or simple thresholds on metrics. We'll have a baseline (maybe from historical data or from the first run) and then compare current metrics to the baseline.
-
Orchestration: We need to run the producer and consumer, potentially for a period of time, and then generate a report.
-
Reporting: After the test, we should output the results: which records violated the schema, which metrics drifted, etc.
Let's design a simple class structure:
However, note: We might want to run the producer and consumer in parallel. We can use a queue (like queue.Queue in Python) for in-memory communication, or use a file/stream.
Let's assume we are using a queue for simplicity.
Steps in run:
- Create a queue.
- Start producer with the queue as output.
- Start consumer with the queue as input.
- Wait for producer to finish.
- Signal consumer to stop (maybe by putting a sentinel in the queue).
- Wait for consumer to finish.
- Get baseline metrics: For the first run (or if we have a separate baseline run) we set the baseline. Alternatively, we can run the test in two phases: first phase to establish baseline, second phase to test and compare.
But note: the problem says "measures data quality drift", so we need to compare to a baseline. We can have two modes:
baseline_mode: run the test without drift and record metrics as baseline.
test_mode: run the test and compare to baseline.
Alternatively, we can have the harness run multiple times and store the baseline from the first run.
Let's design:
TestHarness:
__init__(self, contract, producer_config, consumer_config, drift_thresholds, baseline_file=None)
run(self):
If we are in baseline mode (or first run and no baseline exists), then run producer and consumer, then save the metrics as baseline.
Otherwise, run producer and consumer, then compare to baseline.
We can also have:
`set_baseline(metrics)`: to set the baseline from outside.
How do we get the baseline? We can run the harness with a producer that generates data according to the contract (without drift) and then save the metrics.
Alternatively, we can have the harness run in two steps: first run with baseline=True to establish baseline, then run with baseline=False to test.
Let's do:
harness = TestHarness(contract, producer_config, consumer_config, drift_thresholds)
harness.run(baseline=True) # This will run and save metrics to a file (or memory)
Then later:
harness.run(baseline=False) # This will load the baseline and compare.
But note: the contract might change? We should also validate that the contract is the same? We can store the contract hash with the baseline.
Implementation:
We'll store the baseline in a JSON file with:
{
"contract_hash": "sha256 of contract schema string",
"metrics": {
"field1": {"mean": 0.5, "std": 0.1, ...},
...
}
}
In the test run, we compute the current contract hash and compare. If different, we might fail (or at least warn) because the contract changed.
Alternatively, we can store the contract itself and compare.
Let's store the contract schema string and its hash.
We'll design:
class BaselineStore:
def __init__(self, filepath):
self.filepath = filepath
def save(self, contract, metrics):
# contract is the DataContract object? We'll store the schema and maybe the contract definition.
data = {
"contract_schema": contract.schema, # assuming contract has a schema attribute (dict)
"contract_hash": hashlib.sha256(json.dumps(contract.schema, sort_keys=True).encode()).hexdigest(),
"metrics": metrics
}
with open(self.filepath, 'w') as f:
json.dump(data, f, indent=2)
def load(self):
with open(self.filepath, 'r') as f:
return json.load(f)
Then in the harness:
if baseline:
... run and collect metrics ...
store.save(contract, consumer.get_metrics())
else:
baseline_data = store.load()
# Check contract hash
current_hash = hashlib.sha256(json.dumps(contract.schema, sort_keys=True).encode()).hexdigest()
if current_hash != baseline_data['contract_hash']:
raise Exception("Contract has changed! Baseline is invalid.")
... run and collect metrics ...
drifts = consumer.compare_to_baseline(baseline_data['metrics'])
print_drifts(drifts)
But note: the producer might be generating data with drift in the test run. We need to configure the producer to introduce drift? Or we are testing the consumer's ability to detect drift that might come from the real world?
The harness should be flexible:
- In baseline mode, we want to generate data that exactly follows the contract (so we can establish a baseline of a healthy contract).
- In test mode, we might want to generate data that has some intentional drift (to test the drift detection) OR we might want to generate data that is supposed to be healthy (to check that there's no false positive).
So we can have:
producer_config = {
"num_records": 10000,
"drift": { # optional, if we want to introduce drift in the test
"field1": {"type": "null_rate_increase", "params": {"target_null_rate": 0.2}},
...
}
}
In the producer, if drift is specified for a field, then we generate data that violates the contract or has different distribution.
However, note that the contract might have constraints on nullability, data types, etc. We want to generate data that is valid according to the contract in baseline, and in test we might want to generate invalid data (to test schema validation) or valid but with different distribution (to test data quality drift).
So we need two kinds of testing:
a) Schema compliance: Does the data adhere to the contract (types, required fields, etc.)?
b) Data quality drift: For the fields that are present and of the correct type, are the statistical properties changing?
The consumer should:
- Validate each record against the schema (using a JSON Schema validator, for example). Record violations.
- For each field (or a subset of fields that we care about for drift) compute metrics (like for numeric: mean, std, min, max, distinct count, null rate; for string: distinct count, null rate, maybe length distribution; etc.)
Then compare these metrics to the baseline.
How to define the metrics for each field? We can have a mapping from the field's type to a set of metrics.
Let's assume the contract is in JSON Schema. We can infer the type and then compute:
- For numeric (integer, number): mean, std, min, max, 25th, 50th, 75th percentiles, null rate.
- For string: distinct count (maybe distinct count ratio), null rate, average length, maybe top N values.
- For boolean: null rate, true rate.
- For array: average length, null rate, maybe distinct count (if elements are simple).
- For object: we might not go deep, but count of keys? (but that's more complex)
We can let the user specify which metrics to track for which fields in the consumer config.
Alternatively, we can have a default set per type.
We'll design:
consumer_config = {
"metrics": {
"field1": ["mean", "std", "null_rate", "min", "max"],
"field2": ["distinct_count", "null_rate"],
...
}
}
But note: the contract might have hundreds of fields. We can also have a pattern: for all numeric fields, track these metrics.
We can do:
consumer_config = {
"default_metrics": {
"number": ["mean", "std", "null_rate", "min", "max"],
"string": ["distinct_count", "null_rate", "avg_length"],
...
},
"field_overrides": {
"field1": ["null_rate"] # only track null rate for field1
}
}
Then for each field, we look up the type in the contract and then get the metrics from default_metrics for that type, then apply overrides.
Now, the producer:
We need to generate synthetic data. We can use a library like `faker` for strings, `numpy` for numbers, etc.
But we need to generate according to the contract's constraints (like minimum, maximum, pattern, etc.) and also according to a distribution.
We can have a generator for each type that respects the constraints.
For example, for a number with minimum and maximum, we can generate from a uniform distribution in that range.
For a string with a pattern, we might generate random strings that match the pattern? That's complex. Alternatively, we can ignore pattern in synthetic generation and just generate random strings of length between minLength and maxLength.
We might not be able to generate data that exactly conforms to every constraint in the contract (like a complex regex). But for testing, we can try to generate valid data as much as possible.
In baseline mode, we want to generate valid data. In test mode, if we want to test schema validation, we might want to generate invalid data. So we need a way to specify for each field whether to generate valid or invalid data.
We can extend the drift specification in the producer_config:
"drift": {
"field1": {
"type": "invalid_type", # generate an invalid type (e.g., string for a number)
"probability": 0.1
},
"field2": {
"type": "null_rate_increase",
"params": {"target_null_rate": 0.2}
}
}
But note: if we generate invalid data, then the consumer's schema validation should catch it. So we are testing two things:
- In baseline: no invalid data, so schema validation should pass for all.
- In test: with drift, we might have some invalid data, so we expect schema validation failures.
However, the drift detection on metrics should only be done on the valid records? Or on all? Probably only on the valid records, because invalid records are already a separate problem.
So in the consumer:
- For each record:
- Validate against schema. If invalid, record the error and skip the record for metric calculation? Or count as invalid and then for metrics we only use valid ones? We need to be clear.
We can have:
total_records = 0
valid_records = 0
invalid_records = 0
And for metrics, we only use valid_records.
Then when we compare metrics, we compare the metrics of the valid records to the baseline (which was computed on 100% valid records?).
In baseline, we assume 100% valid. In test, we might have some invalid. But note: if we have a high invalid rate, then the metrics might be computed on fewer records and might drift because of that? But that's a different issue.
We can also track the invalid rate as a metric? But that's more about schema compliance.
Let's break:
- Schema compliance: record the number of invalid records (and the reasons). This is separate from data quality drift.
- Data quality drift: we only consider valid records and compare their metrics to the baseline.
So in the consumer, we have:
- A counter for invalid records (and maybe store the errors?).
- For each field, we aggregate metrics only for the valid records.
Then in the report:
- Schema compliance: invalid record count and percentage, and maybe the error types.
- Data quality drift: for each metric, compare current (from valid records) to baseline.
Now, for drift detection on metrics, we need to handle the case where the baseline was computed on a large number of records and the current valid records might be fewer. We can use statistical tests that take into account the sample size.
But for simplicity, we can use:
- For mean and std: we can do a t-test (if we have the raw data? But we only have metrics). Alternatively, we can store the raw data for baseline? That might be too big.
Alternatively, we can store for the baseline:
- For each metric: value, and also the sample size (n) and for mean and std we might need the sum of squares? But we are computing metrics on the fly and then comparing.
We can compute:
- For mean: we have current mean and baseline mean. We can compute the standard error of the mean for the current sample and see if the difference is within, say, 2 standard errors.
But we don't have the variance of the current sample? We are computing the std of the current sample. We can use:
z = (current_mean - baseline_mean) / (current_std / sqrt(current_n))
Then if |z| > threshold (e.g., 1.96 for 95% confidence) then drift.
But note: the baseline_std is from the baseline sample, which might be large and fixed. We are using the current_std, which is from the current sample.
Alternatively, we can do a t-test with:
t = (current_mean - baseline_mean) / sqrt( (current_std^2/current_n) + (baseline_std^2/baseline_n) )
and degrees of freedom? We can approximate with Welch's t-test.
But note: we might not have stored the baseline_std and baseline_n? We should.
So in the baseline store, for each metric that is a statistic (like mean, std, etc.) we should store:
- For mean: we store the baseline_mean and also the baseline_n (number of valid records) and baseline_sum (or baseline_sum_sq) so we can compute the standard error? Actually, for t-test we need the baseline_std and baseline_n.
So we should store for each metric:
- For mean: we need baseline_mean, baseline_std, baseline_n.
- For std: we can store baseline_std, but also baseline_n? Because we might want to compare the std itself? We can do an F-test for variance.
Alternatively, we can store the raw data for baseline? But that might be too big.
Let's simplify:
We'll store for the baseline:
metrics = {
"field1": {
"mean": {
"value": 0.5,
"std": 0.1,
"n": 10000
},
"null_rate": {
"value": 0.01,
"n": 10000 # for proportion, n is the total number of records (or the number of non-null? Actually, for null_rate, we have:
# p = null_count / n, and the std of p is sqrt(p*(1-p)/n). So we can store p and n.
}
}
}
But note: for null_rate, the baseline_n is the total number of records (valid+invalid?) but we are computing null_rate only on valid records? Actually, null_rate is computed on all records? Or only on non-null? We have to be consistent.
Let's define:
For a field, null_rate = (number of records where the field is null) / (total number of records) [including invalid records?]
But invalid records might not have the field at all? That's a different issue.
We'll compute:
total_records = total number of records (including invalid)
for a field:
if the record is invalid, we don't count it for field metrics? Or we count it as null? That's a design choice.
Let's say: if a record is invalid, then we don't consider any field in that record for metric calculation. But then the null_rate for a field is computed only on valid records? That might be acceptable.
Alternatively, we can count invalid records as having every field as null? That would inflate null rates.
I think it's better to separate:
- Schema validation: invalid records are those that fail the schema.
- Metric calculation: only on valid records.
Then the null_rate for a field in the valid records is: (number of valid records where the field is null) / (number of valid records).
And the baseline is computed on 100% valid records (so baseline_n = total baseline records). In test, we have current_n = number of valid records.
Then for mean, we have:
current_mean, current_std (from the valid records), current_n (number of valid records)
baseline_mean, baseline_std, baseline_n
Then we can do a t-test.
For a proportion (like null_rate), we have:
current_p = current_null_count / current_n
baseline_p = baseline_null_count / baseline_n
We can do a z-test for two proportions.
But note: the baseline might have been computed on a large n, so the baseline_p is known exactly? We can treat it as fixed.
However, for simplicity, we might just set thresholds:
For mean: if |current_mean - baseline_mean| > 3 * (baseline_std / sqrt(baseline_n))? That's a common rule (3 standard errors).
But that doesn't take into account the current sample's variability.
Alternatively, we can compute:
se = sqrt( (current_std^2/current_n) + (baseline_std^2/baseline_n) )
Then if |current_mean - baseline_mean| > 1.96 * se, then drift (at 5% significance).
We'll do that for mean and for other metrics that are means (like avg_length).
For std, we can compare the variances with an F-test.
But let's not get too complex. We can have a simple threshold:
For each metric, we define a relative change threshold (e.g., 10%) and if the absolute relative change exceeds that, then drift.
However, the user might want to set different thresholds per metric.
We can have in drift_thresholds:
{
"field1": {
"mean": {"relative": 0.1}, # 10% relative change
"null_rate": {"absolute": 0.05} # 5% absolute change
}
}
Then for each metric, we check:
if metric is "mean":
rel_change = abs(current_mean - baseline_mean) / baseline_mean
if rel_change > threshold.relative: drift
but if baseline_mean is 0? Then we can't use relative. So we might have absolute threshold as well.
We can design:
threshold = {
"type": "relative", # or "absolute"
"value": 0.1
}
Then:
if type == "relative":
if baseline_value != 0:
change = abs(current_value - baseline_value) / abs(baseline_value)
else:
# if baseline is 0, then if current_value is also 0, no change, else drift?
change = abs(current_value) # not scaled, so maybe set an absolute threshold in that case?
else:
change = abs(current_value - baseline_value)
if change > threshold.value: drift
But note: for null_rate, we might want to use absolute because baseline might be 0 and then any change is infinite relative.
So we can let the user specify per metric.
Alternatively, we can have a default:
For mean, std, min, max, avg_length: use relative (with a cap? if baseline is 0 then use absolute?).
For null_rate, distinct_count_ratio: use absolute.
But let the user override.
Now, let's code the high-level structure.
We'll assume:
- The contract is a JSON Schema.
- We use `jsonschema` for validation.
Steps:
1. Define DataContract:
class DataContract:
def __init__(self, schema: dict, topic: str):
self.schema = schema
self.topic = topic
2. SyntheticProducer:
class SyntheticProducer:
def __init__(self, contract: DataContract, config: dict):
self.contract = contract
self.config = config
self.num_records = config.get('num_records', 1000)
self.drift_config = config.get('drift', {})
def generate_record(self):
# generate a single record that is valid according to the contract, unless drift is specified for some fields.
# We'll have a generator for each field.
# This is complex because the contract can have nested objects, arrays, etc.
# For simplicity, let's assume a flat schema (no nested objects or arrays) for now.
# We'll generate a record as a dict with keys from the contract's properties.
record = {}
properties = self.contract.schema.get('properties', {})
for field, field_schema in properties.items():
# Check if we have drift for this field
drift = self.drift_config.get(field, {})
if drift:
# Generate invalid or drifted data for this field
record[field] = self._generate_with_drift(field_schema, drift)
else:
record[field] = self._generate_valid(field_schema)
return record
def _generate_valid(self, field_schema):
# Generate a value valid according to field_schema.
# We'll handle:
# type: string, number, integer, boolean, null
# format: for email, date, etc. (maybe)
# minLength, maxLength, minimum, maximum, etc.
pass
def _generate_with_drift(self, field_schema, drift):
# Generate a value that may be invalid or have a different distribution.
# drift could be:
# {"type": "invalid_type"} -> generate a value of a different type (e.g., string for number)
# {"type": "null_rate", "params": {"target_rate": 0.5}} -> with probability target_rate, generate null.
# {"type": "distribution_shift", "params": {"mean_shift": 10}} -> for number, shift the mean.
pass
def run(self, output_queue):
for i in range(self.num_records):
record = self.generate_record()
output_queue.put(record)
output_queue.put(None) # sentinel
3. SyntheticConsumer:
class SyntheticConsumer:
def __init__(self, contract: DataContract, config: dict):
self.contract = contract
self.config = config
self.metrics_config = config.get('metrics', {})
self.validator = jsonschema.Draft7Validator(contract.schema) # or whatever version
# We'll store metrics per field
self.reset_metrics()
def reset_metrics(self):
self.total_records = 0
self.valid_records = 0
self.invalid_records = 0
self.invalid_errors = []
# For each field, we store:
# For numeric: sum, sum_sq, min, max, count (non-null), null_count
# For string: count, null_count, distinct set? (but if too many, we might use HyperLogLog? For simplicity, we'll store a set until a limit)
# For boolean: true_count, false_count, null_count
self.field_metrics = {}
# Initialize per field
properties = self.contract.schema.get('properties', {})
for field, field_schema in properties.items():
self.field_metrics[field] = self._init_field_metrics(field_schema)
def _init_field_metrics(self, field_schema):
field_type = field_schema.get('type', [])
if isinstance(field_type, list):
# It's an array of types, we take the first? or we have to handle multiple?
# For simplicity, we assume one type.
field_type = field_type[0] if field_type else 'string'
metrics = {
'type': field_type,
'count': 0, # number of times this field appeared (in valid records) and is not null? Actually, we count every valid record that has this field (even if null)? We'll count every valid record that has this key.
'null_count': 0,
'min': None,
'max': None,
'sum': 0,
'sum_sq': 0,
'distinct_set': set(),
'distinct_count': 0,
'true_count': 0,
'false_count': 0
}
return metrics
def process(self, record):
self.total_records += 1
try:
self.validator.validate(record)
self.valid_records += 1
# Now update metrics for each field in the record.
for field, value in record.items():
if field not in self.field_metrics:
continue # field not in contract? should not happen.
metrics = self.field_metrics[field]
metrics['count'] += 1
if value is None:
metrics['null_count'] += 1
else:
# Update based on type
if metrics['type'] in ['number', 'integer']:
# numeric
metrics['min'] = min(metrics['min'], value) if metrics['min'] is not None else value
metrics['max'] = max(metrics['max'], value) if metrics['max'] is not None else value
metrics['sum'] += value
metrics['sum_sq'] += value * value
elif metrics['type'] == 'string':
metrics['distinct_set'].add(value)
if len(metrics['distinct_set']) > 1000: # limit
# we stop tracking distinct? or use a HyperLogLog? For simplicity, we stop.
pass
elif metrics['type'] == 'boolean':
if value:
metrics['true_count'] += 1
else:
metrics['false_count'] += 1
except jsonschema.ValidationError as e:
self.invalid_records += 1
self.invalid_errors.append(str(e))
def get_metrics(self):
# Compute derived metrics (mean, std, distinct_count, etc.) and return a dict.
result = {}
for field, metrics in self.field_metrics.items():
field_result = {}
n = metrics['count'] # number of non-null? Actually, count is the number of times the field appeared (including null? no, we increment count for every record that has the field, even if null? But then we have null_count.
# Actually, we increment count for every valid record that has the field (regardless of null). Then null_count is the number of nulls in those.
# So non-null count = count - null_count.
# For numeric, we have:
if metrics['type'] in ['number', 'integer']:
if n > 0:
mean = metrics['sum'] / n
# variance = (sum_sq - (sum^2)/n) / (n-1) for sample variance
if n > 1:
variance = (metrics['sum_sq'] - (metrics['sum']**2)/n) / (n-1)
std = variance ** 0.5
else:
std = 0
field_result['mean'] = mean
field_result['std'] = std
field_result['min'] = metrics['min']
field_result['max'] = metrics['max']
else:
field_result['mean'] = None
field_result['std'] = None
field_result['min'] = None
field_result['max'] = None
elif metrics['type'] == 'string':
distinct_count = len(metrics['distinct_set'])
field_result['distinct_count'] = distinct_count
if n > 0:
field_result['distinct_ratio'] = distinct_count / n
else:
field_result['distinct_ratio'] = None
elif metrics['type'] == 'boolean':
if n > 0:
field_result['true_rate'] = metrics['true_count'] / n
field_result['false_rate'] = metrics['false_count'] / n
else:
field_result['true_rate'] = None
field_result['false_rate'] = None
# null rate: null_count / (count) but note: count is the number of records that have the field (including null). But what about records that don't have the field?
# In JSON, if a field is missing, then it's not in the record. So we are only counting records that have the field (either with a value or null).
# But the contract might have required fields? We are not handling required fields in metric calculation?
# Actually, if a field is required and missing, then the record is invalid. So in valid records, all required fields are present (at least as null if allowed?).
# So for valid records, if the field is required and nullable, then it can be null. If it's required and not nullable, then null is invalid? Actually, the schema validation would catch if a required field is missing, but if it's present and null, and the type doesn't include null, then invalid.
# So in valid records, for a field that is present (and the record is valid) we have:
# If the field is in the record, then it's either null or a value of the correct type.
# If the field is not in the record, then it's missing and that would be invalid if required? So in valid records, if the field is required, it must be present. If it's not required, it may be absent.
# So we have two counts:
# total_valid_records: self.valid_records
# field_count: number of valid records that have this field (including null). This is metrics['count'].
# field_null_count: number of valid records that have this field and it's null. This is metrics['null_count'].
# Then the null rate for the field (among records that have the field) is: null_count / count.
# But also, we might want the overall null rate (including records that don't have the field). That would be: (null_count + (valid_records - count)) / valid_records?
# However, if the field is not required, then it's okay to be absent. So we have two ways:
# 1. Null rate only among records that have the field.
# 2. Overall missing rate (including absent and null) among all valid records.
# Let's do:
# missing_count = valid_records - count (records that don't have the field)
# overall_missing_rate = (missing_count + null_count) / valid_records
# We'll compute both? But the contract might specify if the field is required. We can check the contract's required array.
# For now, we'll compute:
field_result['null_rate'] = metrics['null_count'] / metrics['count'] if metrics['count'] > 0 else None
field_result['missing_rate'] = (self.valid_records - metrics['count']) / self.valid_records if self.valid_records > 0 else None
result[field] = field_result
return result
def compare_to_baseline(self, baseline_metrics, thresholds):
# baseline_metrics: same structure as get_metrics output.
# thresholds: dict of thresholds per field and metric.
drifts = []
for field, current in self.get_metrics().items():
if field not in baseline_metrics:
continue
baseline = baseline_metrics[field]
field_thresholds = thresholds.get(field, {})
for metric, current_value in current.items():
if metric not in baseline:
continue
baseline_value = baseline[metric]
if current_value is None or baseline_value is None:
continue
threshold = field_thresholds.get(metric, {"type": "relative", "value": 0.1})
change = abs(current_value - baseline_value)
if threshold['type'] == 'relative':
if baseline_value != 0:
rel_change = change / abs(baseline_value)
else:
rel_change = change # if baseline is 0, then we treat change as absolute? but we don't have an absolute threshold in this case?
# Actually, if baseline is 0 and we are using relative, then we should consider any change as drift? But that's too strict.
# So we might require an absolute threshold in that case? Let's say if baseline_value==0 and threshold.type is relative, then we use an absolute threshold of 1 (or the user must specify absolute for that metric).
# We'll leave it as: if baseline_value==0, then we use absolute change and compare to threshold.value? But threshold.value is for relative? That doesn't make sense.
# So let's change: if baseline_value==0 and we are using relative, then we consider any non-zero current_value as drift? But that might be too much.
# Alternatively, we can skip this metric if baseline_value==0 and threshold is relative? Not good.
# Let's design:
# If threshold.type is "relative", then:
# if baseline_value == 0:
# if current_value == 0: no drift
# else: drift (because any change from 0 is infinite relative)
# But that might be too harsh. So maybe we require the user to set an absolute threshold for such cases.
# We'll do:
if current_value == 0:
# no change
rel_change = 0
else:
# change from 0 to non-zero: we consider it as drift if absolute change > threshold.value? But threshold.value is for relative.
# We'll treat it as absolute change and use the threshold.value as absolute? Not consistent.
# Let's change the threshold definition:
# threshold = {"type": "relative", "value": 0.1} or {"type": "absolute", "value": 0.05}
# So if baseline_value==0 and type is relative, then we cannot compute relative. So we skip? or we use absolute?
# We'll skip and require the user to set an absolute threshold for that metric if they care about changes from 0.
continue # skip this metric for drift? Or we can use absolute if the user also provided an absolute?
# Actually, the user might have provided both? We can design the threshold to have both, but we use one.
# We'll require that for metrics that can be 0, the user should set an absolute threshold.
pass # we'll skip for now.
else: # absolute
rel_change = change # we'll use change as absolute
# Now, if threshold.type is relative, we compare rel_change to threshold.value.
# If absolute, we compare change to threshold.value.
if threshold['type'] == 'relative':
if baseline_value != 0 and rel_change > threshold['value']:
drifts.append({
'field': field,
'metric': metric,
'baseline_value': baseline_value,
'current_value': current_value,
'change': change,
'rel_change': rel_change,
'threshold': threshold['value']
})
else:
if change > threshold['value']:
drifts.append({
'field': field,
'metric': metric,
'baseline_value': baseline_value,
'current_value': current_value,
'change': change,
'threshold': threshold['value']
})
return drifts
4. TestHarness:
class TestHarness:
def __init__(self, contract, producer_config, consumer_config, drift_thresholds, baseline_store=None):
self.contract = contract
self.producer_config = producer_config
self.consumer_config = consumer_config
self.drift_thresholds = drift_thresholds
self.baseline_store = baseline_store or BaselineStore('baseline.json')
def run(self, baseline_mode=False):
# Create a queue
from queue import Queue
queue = Queue(maxsize=10000)
# Start producer
producer = SyntheticProducer(self.contract, self.producer_config)
producer_thread = threading.Thread(target=producer.run, args=(queue,))
producer_thread.start()
# Start consumer
consumer = SyntheticConsumer(self.contract, self.consumer_config)
consumer_thread = threading.Thread(target=self._consumer_run, args=(consumer, queue))
consumer_thread.start()
# Wait for producer to finish
producer_thread.join()
# Wait for consumer to finish (it will stop when it gets None)
consumer_thread.join()
# Now, if baseline_mode, save baseline
if baseline_mode:
metrics = consumer.get_metrics()
self.baseline_store.save(self.contract, metrics)
print("Baseline saved.")
else:
# Load baseline
baseline_data = self.baseline_store.load()
# Check contract hash
current_hash = hashlib.sha256(json.dumps(self.contract.schema, sort_keys=True).encode()).hexdigest()
if current_hash != baseline_data['contract_hash']:
raise Exception("Contract has changed. Baseline is invalid.")
baseline_metrics = baseline_data['metrics']
drifts = consumer.compare_to_baseline(baseline_metrics, self.drift_thresholds)
# Also report schema validation errors
print(f"Total records: {consumer.total_records}")
print(f"Valid records: {consumer.valid_records}")
print(f"Invalid records: {consumer.invalid_records}")
if consumer.invalid_errors:
print("Sample invalid errors:")
for err in consumer.invalid_errors[:10]:
print(f" {err}")
print("\nData quality drifts:")
for d in drifts:
print(f"Field: {d['field']}, Metric: {d['metric']}")
print(f" Baseline: {d['baseline_value']}, Current: {d['current_value']}, Change: {d.get('change')}, Rel change: {d.get('rel_change')}")
print(f" Threshold: {d['threshold']} ({'relative' if 'rel_change' in d else 'absolute'})")
def _consumer_run(self, consumer, queue):
while True:
record = queue.get()
if record is None:
break
consumer.process(record)
# After done, we can get metrics, but we'll do that in the main thread.
This is a basic structure. We need to implement the data generation for the producer, which is complex for nested schemas.
Given the complexity, we might limit to flat schemas for now.
Also, we need to handle the case where the contract has arrays or objects. We'll skip for now.
We can extend the producer to handle nested objects by recursively generating.
But note: the consumer's metric calculation for nested objects? We are only doing top-level fields.
We can decide to only support flat schemas for this harness.
Alternatively, we can flatten the schema? But that might not be straightforward.
Let's assume the contract is flat.
We'll implement:
_generate_valid for flat fields:
if field_type == 'string':
# generate a random string. If there's a minLength and maxLength, generate a string of random length between them.
# We can use faker or random.choices.
min_length = field_schema.get('minLength', 1)
max_length = field_schema.get('maxLength', 20)
length = random.randint(min_length, max_length)
# generate random letters
import string
return ''.join(random.choices(string.ascii_letters, k=length))
elif field_type in ['number', 'integer']:
minimum = field_schema.get('minimum', 0)
maximum = field_schema.get('maximum', 100)
if field_type == 'integer':
return random.randint(minimum, maximum)
else:
return random.uniform(minimum, maximum)
elif field_type == 'boolean':
return random.choice([True, False])
elif field_type == 'null':
return None
else:
# for other types (array, object) we return None? or we skip?
return None
And for drift:
For a field with drift type "invalid_type", we generate a value of a different type. For example, for a number field, we generate a string.
For "null_rate" with params: {"target_rate": 0.5}, then with probability target_rate we return None, else generate valid.
For "distribution_shift" for number: we shift the mean by params['mean_shift'].
But note: if we are generating invalid data (like wrong type), then the record might become invalid. That's okay because we are testing schema validation.
However, if we generate an invalid value for a field, the whole record might be invalid? Yes, because the schema validation will fail.
So in the producer, when we generate with drift for a field, we might intentionally generate an invalid value for that field, which will cause the record to be invalid. That's fine.
But then in the consumer, we will count that record as invalid and skip metric calculation for that record. So the metrics will be computed only on the valid records. That means if we introduce drift that makes records invalid, then the number of valid records will decrease, but the metrics of the valid records might still be the same (if the invalid records are random and not affecting the distribution of the valid ones).
However, if we want to test drift in the data quality of the valid records, we need to generate valid data with a shifted distribution. So we need two kinds of drift:
- Schema drift: changing the type or structure so that the record becomes invalid.
- Data drift: changing the distribution of the values (but still valid).
So in the drift config, we can have:
"field1": {
"schema_drift": {"type": "invalid_type", "probability": 0.1},
"data_drift": {"type": "mean_shift", "params": {"shift": 10}}
}
But then we have to generate:
With probability 0.1, generate an invalid type (which will make the record invalid). Otherwise, generate a valid type but with mean shifted by 10.
However, if we generate an invalid type, then the record is invalid and we don't count it for metrics. So the data drift will only be on the 90% valid records, and we shifted the mean by 10 for those.
So we can combine.
But note: if we shift the mean for a number field, we have to make sure the value is still within the min and max? Otherwise it becomes invalid because of minimum/maximum constraints.
So when generating with data_drift, we must respect the constraints (min, max, etc.) so that the record remains valid.
So for data_drift, we generate valid data but with a different distribution.
We'll implement:
For a number field with data_drift type "mean_shift":
We generate from a normal distribution with mean = original_mean + shift, and std = original_std.
But we have to clip to min and max.
How do we know the original distribution? We don't. We can assume the baseline generation uses uniform between min and max, so original_mean = (min+max)/2, original_std = (max-min)/sqrt(12). But we might not have min and max? Then we generate from a standard normal and then scale?
Alternatively, we can define a baseline distribution in the producer_config?
This is getting complex.
Given the time, let's keep it simple:
In baseline mode, we generate uniformly for numbers between min and max (or 0 to 100 if not specified).
In data_drift, we shift the mean by a fixed amount and then clip to min and max.
For other types (string), we might change the length distribution? But we don't have a baseline distribution for length? We can generate strings of random length between minLength and maxLength. For drift, we can change the length to be longer? But we have maxLength constraint, so we can only shift within the allowed range.
So for string, we can change the average length by generating with a different distribution? But we are bounded by minLength and maxLength.
We might not be able to change the average length without violating minLength or maxLength? We can generate with a distribution that is skewed towards longer strings, but still within min and max.
We'll leave data_drift for strings as: increase the average length by generating with a minimum of minLength and maximum of maxLength, but with a bias towards maxLength? We can use a beta distribution? But that's complex.
Alternatively, we can change the character set? But that doesn't affect the metrics we track (distinct count, etc.).
So maybe for strings, we don't do data_drift? Or we can change the distinct count by generating more repeated values? That would be a different kind of drift.
Given the complexity, let's focus on numeric fields for data_drift.
We'll design:
For a numeric field:
baseline: uniform between min and max (if min and max are given, else 0 to 100).
data_drift:
type: "mean_shift"
params: {"shift": 10} # shift the mean by 10.
Then we generate from a normal distribution with mean = original_mean + shift, and std = (max-min)/4 (approximately, so that 95% of the data is within min and max). Then we clip to [min, max].
But what if min and max are not given? Then we don't have bounds? Then we can just shift the mean without clipping.
We'll do:
if min is not None and max is not None:
original_mean = (min + max)/2
# We want the shifted mean to be within [min, max] as much as possible? But if shift is large, we might have to clip a lot.
# We can generate from a normal and then clip.
else:
original_mean = 50 # arbitrary
This is very ad-hoc.
Given the time, we might skip the producer implementation details and focus on the harness structure.
We'll assume the producer is given and we just use it.
Alternatively, we can use a simple producer that generates random data according to the contract (without drift) and then we have a way to inject drift by modifying the data after generation? But that might be easier.
We can have:
producer generates valid data (according to contract) and then we apply a series of "mutations" to the records to introduce drift.
But then we have to be careful that the mutations don't break the contract? For schema drift we want to break it, for data drift we don't.
We can have:
mutation rules:
- For a field, set to null with probability p (if the field is nullable, then it's valid; if not, then invalid).
- For a numeric field, add a value (shift) and then clip to min/max if defined.
- For a string field, change the string to a fixed string (reducing distinct count) or increase length (if within min/max).
But again, we need to know the constraints.
Given the complexity, we might limit the harness to:
- Flat JSON schemas.
- Only support string, number, integer, boolean, null.
- For numbers: if min and max are defined, generate uniformly. Then for data drift, shift the mean by a fixed amount and clip.
- For strings: generate random strings of random length between minLength and maxLength (if defined, else 1 to 20). For data drift, we can change the distinct count by replacing with a common value with some probability?
But let's not overcomplicate.
Since the question is about engineering a harness, we can assume that the synthetic producer is given and we focus on the testing and drift detection.
We'll design the harness to be pluggable:
- The producer is an object that has a `run(output_queue)` method.
- The consumer is an object that has a `process(record)` method and `get_metrics()` and `compare_to_baseline(baseline_metrics, thresholds)`.
Then we can implement a simple producer that generates valid data and another that generates data with drift.
But the harness should be able to test both schema compliance and data drift.
We'll provide:
- A `ValidDataProducer` that generates data that is valid according to the contract.
- A `DriftDataProducer` that generates data with some controlled deviations (both schema and data).
However, the drift configuration might be specific to the contract and the type of drift we want to test.
So we can have:
producer_config = {
"type": "valid" # or "drift"
"drift_rules": {...} # if type is drift
}
But then we have to implement the drift rules.
Given the time, we'll leave the producer implementation as an exercise and focus on the harness that uses a producer and consumer.
We'll assume we have:
class ValidProducer:
def run(self, queue):
for i in range(num_records):
record = generate_valid_record(contract)
queue.put(record)
queue.put(None)
class DriftProducer:
def __init__(self, contract, drift_rules):
self.contract = contract
self.drift_rules = drift_rules
def run(self, queue):
for i in range(num_records):
record = generate_valid_record(contract)
# apply drift rules to the record
record = apply_drift(record, self.drift_rules)
queue.put(record)
queue.put(None)
And then the harness can use either.
Now, for the consumer, we have implemented a basic one that tracks metrics for flat schemas.
We need to handle the case where the contract has nested objects? We can skip for now.
Also, we need to handle arrays? We can skip.
We'll state that the harness currently only supports flat schemas.
Now, the baseline store: we store the contract schema and the metrics.
We'll write the BaselineStore as:
import json, hashlib
class BaselineStore:
def __init__(self, filepath):
self.filepath = filepath
def save(self, contract, metrics):
data = {
'contract_schema': contract.schema,
'contract_hash': hashlib.sha256(json.dumps(contract.schema, sort_keys=True).encode()).hexdigest(),
'metrics': metrics
}
with open(self.filepath, 'w') as f:
json.dump(data, f, indent=2)
def load(self):
with open(self.filepath, 'r') as f:
return json.load(f)
Now, the TestHarness as above.
We'll also need to handle the consumer's metric calculation: we are computing metrics on the fly and storing intermediate sums, etc. Then get_metrics computes the final metrics.
We'll run the consumer in a separate thread, and we call consumer.get_metrics() after the consumer thread finishes.
But note: the consumer might be processing records and updating the metrics. We are not using locks because it's single-threaded (the consumer runs in its own thread and no one else touches its state). So it's safe.
However, if we want to get metrics while the consumer is running (for monitoring), we would need a lock. But we don't need that.
Let's adjust:
In the harness, we start the consumer thread and then wait for it to finish. Then we get the metrics.
So it's safe.
Now, we need to implement the generate_valid_record and apply_drift for a flat schema.
We'll write a helper:
def generate_valid_record(contract_schema):
properties = contract_schema.get('properties', {})
record = {}
for field, schema in properties.items():
record[field] = generate_value(schema)
return record
def generate_value(schema):
# generate a value according to the schema.
# We'll handle:
# type: string, number, integer, boolean, null
# format: ignore for now.
# minLength, maxLength for string.
# minimum, maximum for numbers.
# exclusiveMinimum, exclusiveMaximum? ignore.
# enum: pick a random enum value.
import random
import string
types = schema.get('type', [])
if isinstance(types, list):
# pick one randomly? or we have to handle multiple? For simplicity, we pick the first that we can generate.
# We'll try to generate for the first type that we support.
for t in types:
if t in ['string', 'number', 'integer', 'boolean', 'null']:
type_ = t
break
else:
type_ = 'string' # default
else:
type_ = types
if type_ == 'string':
min_length = schema.get('minLength', 1)
max_length = schema.get('maxLength', 20)
length = random.randint(min_length, max_length)
return ''.join(random.choices(string.ascii_letters, k=length))
elif type_ in ['number', 'integer']:
minimum = schema.get('minimum', 0)
maximum = schema.get('maximum', 100)
if type_ == 'integer':
return random.randint(minimum, maximum)
else:
return random.uniform(minimum, maximum)
elif type_ == 'boolean':
return random.choice([True, False])
elif type_ == 'null':
return None
else:
return None
For drift:
def apply_drift(record, drift_rules):
new_record = record.copy()
for field, rules in drift_rules.items():
if field not in new_record:
continue
value = new_record[field]
for rule in rules: # but drift_rules might be a dict of rule_name: params? We designed as a dict with keys like "schema_drift" and "data_drift". But we can have multiple rules per field? Let's say drift_rules[field] is a list of rules.
We'll design:
drift_rules = {
"field1": [
{"type": "schema_drift", "subtype": "invalid_type", "probability": 0.1},
{"type": "data_drift", "subtype": "mean_shift", "params": {"shift": 10}}
]
}
Then for each rule, we apply with the given probability? Or we apply only if the rule says so.
We'll do:
for rule in drift_rules.get(field, []):
if rule['type'] == 'schema_drift':
if rule['subtype'] == 'invalid_type':
# With probability rule['probability'], set the field to an invalid type.
if random.random() < rule['probability']:
# Generate an invalid value for the field. We need to know the original type.
# We can look up the contract schema for the field? But we don't have the contract here.
# So we should pass the contract to apply_drift? Or we can have the drift_rules specify what invalid type to generate?
# Let's change: the rule can have a "target_type" to generate instead.
# Example: {"type": "schema_drift", "subtype": "invalid_type", "target_type": "string", "probability": 0.1}
# Then we generate a string for a field that is supposed to be number.
target_type = rule.get('target_type', 'string')
new_record[field] = generate_value_of_type(target_type)
elif rule['type'] == 'data_drift':
if rule['subtype'] == 'mean_shift':
# Only for numbers
if isinstance(value, (int, float)):
shift = rule['params']['shift']
new_record[field] = value + shift
But note: if we shift the mean, we might go out of bounds. We should clip if the contract has min/max? We don't have the contract in apply_drift.
So we need to pass the contract schema to apply_drift? Or we can have the drift rule also include min and max? That's redundant.
Alternatively, we can have the producer generate the record and then apply drift, and the producer has the contract, so we can clip.
So we should have the producer do the drift, not a separate function.
Given the complexity, we'll stop here.
Given the time, we'll provide a high-level design and leave the implementation of the producer as an exercise.
We'll provide a simple producer that generates valid data and a simple drift producer that:
- For numeric fields: with probability 0.1, generate null (if the field is nullable, then it's valid; if not, then invalid). And also shift the mean by 10 (but without clipping, so might become invalid if there are min/max constraints).
But note: if we generate a null for a non-nullable field, then the record becomes invalid. That's okay.
So we can do:
class DriftProducer(SyntheticProducer):
def __init__(self, contract, config):
super().__init__(contract, config)
# config should have:
# null_rate_increase: {field: probability} # probability of setting to null (if the field is not required and nullable, then valid; if not nullable, invalid)
# mean_shift: {field: shift}
def generate_record(self):
record = super().generate_record() # this generates a valid record according to the contract.
# Then apply drift:
for field, shift in self.config.get('mean_shift', {}).items():
if field in record and isinstance(record[field], (int, float)):
record[field] += shift
for field, prob in self.config.get('null_rate_increase', {}).items():
if field in record:
if random.random() < prob:
record[field] = None
return record
But note: the super().generate_record() might have already set the field to null if the field is nullable? And we are increasing the null rate by setting more to null.
And for mean_shift, we are shifting the value. If the field has min/max, we might go out of bounds and then the record becomes invalid.
That's acceptable.
So we can have:
producer_config = {
"type": "drift",
"mean_shift": {"price": 10},
"null_rate_increase": {"price": 0.1}
}
But we need to know the fields and their types.
We'll leave it at that.
Now, the consumer will:
- Count invalid records (due to null in non-nullable field or out-of-bound numbers, etc.)
- For the valid records, compute metrics. For the field with mean_shift, we expect the mean to be higher. For the field with null_rate_increase, we expect the null_rate to be higher (among valid records? but note: if we set a field to null and the field is nullable, then the record is still valid and the field is null. So the null_rate will increase. But if the field is not nullable, then setting to null makes the record invalid, so the valid records will not have that field? Actually, if the field is required and not nullable, then setting to null will make the record invalid, so we won't count that record in the valid set. So the null_rate for that field in the valid set will be 0? Because in valid records, the field cannot be null.
So we have to be careful.
Given the time, we'll assume the contract allows null for the fields we are drifting with null.
Now, the harness is designed.
We'll write the code accordingly, but note that this is a high-level design and we might have to adjust.
Given the complexity and time, we'll provide a simplified version that works for flat schemas and only for numbers and strings.
Let's code accordingly.
Steps:
1. Install required packages: jsonschema, faker (maybe for strings, but we are using random.choices so no need), etc.
2. Write the classes as above.
We'll write the code in one file.
Let's code:
- DataContract
- BaselineStore
- SyntheticProducer (base class) and ValidProducer, DriftProducer
- SyntheticConsumer
- TestHarness
We'll assume the contract is a JSON schema (dict).
We'll also assume the contract is flat.
We'll write the code accordingly.
Due to the complexity, we might not handle all cases, but this is a starting point.
Let's code.</think>
I'll design a comprehensive data contract testing harness with the following capabilities:
Architecture Overview
┌─────────────────────────────────────────────────────────────┐
│ Data Contract Harness │
├─────────────┬─────────────┬─────────────┬─────────────────┤
│ Schema │ Synthetic │ Validation │ Drift │
│ Registry │ Producers │ Engine │ Detection │
└─────────────┴─────────────┴─────────────┴─────────────────┘
Core Components
1. Schema Registry & Contract Definition
from dataclasses import dataclass, field
from typing import Dict, List, Any, Optional
from datetime import datetime
import json
import hashlib
@dataclass
class DataContract:
"""Immutable data contract definition"""
name: str
version: str
schema: Dict[str, Any] # JSON Schema or Avro/Protobuf definition
quality_rules: Dict[str, Any] = field(default_factory=dict)
metadata: Dict[str, Any] = field(default_factory=dict)
def __post_init__(self):
self._hash = self._calculate_hash()
def _calculate_hash(self) -> str:
return hashlib.sha256(
json.dumps({
'schema': self.schema,
'quality_rules': self.quality_rules
}, sort_keys=True).encode()
).hexdigest()[:16]
@property
def contract_id(self) -> str:
return f"{self.name}:{self.version}:{self._hash}"
2. Synthetic Data Generation Engine
import numpy as np
from faker import Faker
from scipy import stats
class SyntheticDataProducer:
"""Generates synthetic data according to contract schema"""
def __init__(self, contract: DataContract, seed: int = None):
self.contract = contract
self.faker = Faker()
if seed:
np.random.seed(seed)
Faker.seed(seed)
# Field generators mapping
self.generators = {
'string': self._generate_string,
'integer': self._generate_integer,
'number': self._generate_number,
'boolean': self._generate_boolean,
'datetime': self._generate_datetime,
'array': self._generate_array,
'object': self._generate_object
}
def generate_record(self,
drift_config: Optional[Dict] = None,
invalid_rate: float = 0.0) -> Dict:
"""Generate single record with optional drift"""
record = {}
schema = self.contract.schema.get('properties', {})
for field, field_schema in schema.items():
if field_schema.get('nullable') and np.random.random() < 0.05:
record[field] = None
continue
try:
generator = self.generators.get(
field_schema.get('type', 'string'),
self._generate_string
)
value = generator(field_schema)
# Apply drift if configured
if drift_config and field in drift_config:
value = self._apply_drift(value, field_schema, drift_config[field])
# Inject invalid data
if np.random.random() < invalid_rate:
value = self._generate_invalid(field_schema)
record[field] = value
except Exception as e:
# Log generation error but continue
pass
return record
def _generate_string(self, schema: Dict) -> str:
min_len = schema.get('minLength', 5)
max_len = schema.get('maxLength', 50)
pattern = schema.get('pattern')
if pattern:
# Simplified pattern matching
return self.faker.bothify(text='?' * min_len)[:max_len]
return self.faker.text(max_n_chars=max_len)[:max_len]
def _generate_integer(self, schema: Dict) -> int:
minimum = schema.get('minimum', 0)
maximum = schema.get('maximum', 1000)
return int(np.random.randint(minimum, maximum + 1))
def _apply_drift(self, value: Any, schema: Dict, drift: Dict) -> Any:
"""Apply controlled drift to value"""
drift_type = drift.get('type', 'mean_shift')
if drift_type == 'mean_shift' and isinstance(value, (int, float)):
shift = drift.get('shift', 0)
return value + shift
elif drift_type == 'distribution_change':
# Change distribution parameters
if isinstance(value, (int, float)):
new_min = drift.get('new_min', value)
new_max = drift.get('new_max', value)
return np.random.uniform(new_min, new_max)
elif drift_type == 'null_increase':
if schema.get('nullable'):
return None
elif drift_type == 'format_change':
# Change string format
if isinstance(value, str):
return value.upper() if drift.get('to_uppercase') else value.lower()
return value
3. Schema Validation Engine
from jsonschema import validate, ValidationError, Draft7Validator
import pandas as pd
class SchemaValidator:
"""Validates data against contract schema"""
def __init__(self, contract: DataContract):
self.contract = contract
self.validator = Draft7Validator(contract.schema)
self.stats = {
'total_validated': 0,
'valid_records': 0,
'invalid_records': 0,
'errors': []
}
def validate_record(self, record: Dict) -> bool:
"""Validate single record"""
self.stats['total_validated'] += 1
try:
validate(instance=record, schema=self.contract.schema)
self.stats['valid_records'] += 1
return True
except ValidationError as e:
self.stats['invalid_records'] += 1
self.stats['errors'].append({
'timestamp': datetime.utcnow().isoformat(),
'field': list(e.path)[0] if e.path else 'root',
'message': e.message,
'validator': e.validator,
'instance': str(e.instance)[:100]
})
return False
def get_validation_report(self) -> Dict:
"""Generate validation summary"""
return {
'contract_id': self.contract.contract_id,
'timestamp': datetime.utcnow().isoformat(),
'stats': {
'total': self.stats['total_validated'],
'valid': self.stats['valid_records'],
'invalid': self.stats['invalid_records'],
'valid_rate': self.stats['valid_records'] / max(1, self.stats['total_validated'])
},
'recent_errors': self.stats['errors'][-10:]
}
4. Data Quality Metrics Engine
class QualityMetricsCollector:
"""Collects and analyzes data quality metrics"""
def __init__(self, contract: DataContract, window_size: int = 1000):
self.contract = contract
self.window_size = window_size
self.windows = [] # Sliding windows of metrics
self.current_window = {
'record_count': 0,
'fields': {}
}
self.baseline_metrics = None
def process_record(self, record: Dict):
"""Process record and update metrics"""
self.current_window['record_count'] += 1
for field, value in record.items():
if field not in self.current_window['fields']:
self._init_field_metrics(field)
metrics = self.current_window['fields'][field]
metrics['count'] += 1
if value is None:
metrics['null_count'] += 1
elif isinstance(value, (int, float)):
metrics['sum'] += value
metrics['sum_sq'] += value * value
metrics['min'] = min(metrics['min'], value) if metrics['min'] is not None else value
metrics['max'] = max(metrics['max'], value) if metrics['max'] is not None else value
metrics['values'].append(value)
elif isinstance(value, str):
metrics['distinct_values'].add(value)
metrics['lengths'].append(len(value))
# Check if window is full
if self.current_window['record_count'] >= self.window_size:
self._finalize_window()
self._reset_window()
def _init_field_metrics(self, field: str):
"""Initialize metrics for a field"""
self.current_window['fields'][field] = {
'count': 0,
'null_count': 0,
'sum': 0,
'sum_sq': 0,
'min': None,
'max': None,
'distinct_values': set(),
'lengths': [],
'values': []
}
def _finalize_window(self):
"""Calculate derived metrics for current window"""
window_metrics = {'record_count': self.current_window['record_count']}
for field, metrics in self.current_window['fields'].items():
field_metrics = {'null_rate': metrics['null_count'] / max(1, metrics['count'])}
if metrics['values']: # Numeric field
values = np.array(metrics['values'])
field_metrics.update({
'mean': float(np.mean(values)),
'std': float(np.std(values)),
'median': float(np.median(values)),
'q25': float(np.percentile(values, 25)),
'q75': float(np.percentile(values, 75)),
'min': metrics['min'],
'max': metrics['max'],
'distinct_count': len(metrics['distinct_values']),
'distinct_ratio': len(metrics['distinct_values']) / len(values)
})
elif metrics['lengths']: # String field
lengths = np.array(metrics['lengths'])
field_metrics.update({
'avg_length': float(np.mean(lengths)),
'length_std': float(np.std(lengths)),
'distinct_count': len(metrics['distinct_values']),
'distinct_ratio': len(metrics['distinct_values']) / len(lengths)
})
window_metrics[field] = field_metrics
self.windows.append(window_metrics)
def _reset_window(self):
"""Reset current window"""
self.current_window = {
'record_count': 0,
'fields': {}
}
def set_baseline(self, metrics: Dict):
"""Set baseline metrics for drift detection"""
self.baseline_metrics = metrics
def detect_drift(self,
threshold: float = 0.1,
method: str = 'ks_test') -> List[Dict]:
"""Detect drift in current metrics vs baseline"""
if not self.baseline_metrics or not self.windows:
return []
drifts = []
latest = self.windows[-1]
for field in latest:
if field == 'record_count':
continue
if field not in self.baseline_metrics:
continue
baseline = self.baseline_metrics[field]
current = latest[field]
# Compare null rates
if 'null_rate' in baseline and 'null_rate' in current:
null_drift = abs(current['null_rate'] - baseline['null_rate'])
if null_drift > threshold:
drifts.append({
'field': field,
'metric': 'null_rate',
'baseline': baseline['null_rate'],
'current': current['null_rate'],
'drift_amount': null_drift,
'severity': 'HIGH' if null_drift > 0.2 else 'MEDIUM'
})
# Compare distributions for numeric fields
if 'mean' in baseline and 'mean' in current:
drift_score = self._calculate_drift_score(
baseline, current, method
)
if drift_score > threshold:
drifts.append({
'field': field,
'metric': 'distribution',
'drift_score': drift_score,
'severity': 'HIGH' if drift_score > 0.3 else 'MEDIUM'
})
return drifts
def _calculate_drift_score(self, baseline: Dict, current: Dict, method: str) -> float:
"""Calculate drift score between distributions"""
# Simplified KL divergence approximation using moments
if method == 'moment_comparison':
mean_diff = abs(current['mean'] - baseline['mean']) / (baseline['std'] + 1e-10)
std_diff = abs(current['std'] - baseline['std']) / baseline['std']
return (mean_diff + std_diff) / 2
# Could implement KS test, PSI, etc.
return 0.0
def get_metrics_report(self) -> Dict:
"""Generate comprehensive metrics report"""
if not self.windows:
return {}
latest = self.windows[-1]
return {
'contract_id': self.contract.contract_id,
'timestamp': datetime.utcnow().isoformat(),
'window_size': self.window_size,
'window_metrics': latest,
'drift_detected': bool(self.detect_drift())
}
5. Test Harness & Orchestrator
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
from typing import Tuple
class DataContractHarness:
"""Main orchestrator for data contract testing"""
def __init__(self,
contract: DataContract,
producer_config: Dict,
consumer_config: Dict,
drift_threshold: float = 0.1):
self.contract = contract
self.producer_config = producer_config
self.consumer_config = consumer_config
self.drift_threshold = drift_threshold
# Components
self.producer = SyntheticDataProducer(contract, seed=42)
self.validator = SchemaValidator(contract)
self.metrics_collector = QualityMetricsCollector(contract)
# Results
self.results = {
'contract_id': contract.contract_id,
'start_time': None,
'end_time': None,
'records_processed': 0,
'validation_rate': 0.0,
'drifts_detected': [],
'quality_metrics': {}
}
def run_baseline_test(self,
num_records: int = 10000,
batch_size: int = 100) -> Dict:
"""Run baseline test (no drift)"""
print(f"Running baseline test for {num_records} records...")
return self._run_test(
num_records=num_records,
batch_size=batch_size,
drift_config=None,
invalid_rate=0.0,
is_baseline=True
)
def run_drift_test(self,
num_records: int = 10000,
batch_size: int = 100,
drift_rules: Optional[Dict] = None) -> Dict:
"""Run test with configured drift"""
print(f"Running drift test for {num_records} records...")
return self._run_test(
num_records=num_records,
batch_size=batch_size,
drift_config=drift_rules or self.producer_config.get('drift_rules'),
invalid_rate=self.producer_config.get('invalid_rate', 0.01),
is_baseline=False
)
def _run_test(self,
num_records: int,
batch_size: int,
drift_config: Optional[Dict],
invalid_rate: float,
is_baseline: bool) -> Dict:
"""Core test execution"""
self.results['start_time'] = datetime.utcnow().isoformat()
records_processed = 0
# Process in batches
for batch_start in range(0, num_records, batch_size):
batch_end = min(batch_start + batch_size, num_records)
batch = []
# Generate batch
for _ in range(batch_start, batch_end):
record = self.producer.generate_record(
drift_config=drift_config,
invalid_rate=invalid_rate if not is_baseline else 0.0
)
batch.append(record)
# Process batch
for record in batch:
# Validate
is_valid = self.validator.validate_record(record)
# Collect metrics only for valid records
if is_valid:
self.metrics_collector.process_record(record)
records_processed += 1
# Finalize metrics
if is_baseline:
baseline_metrics = self.metrics_collector.get_metrics_report()
self.results['quality_metrics']['baseline'] = baseline_metrics
self.metrics_collector.set_baseline(baseline_metrics)
else:
current_metrics = self.metrics_collector.get_metrics_report()
self.results['quality_metrics']['current'] = current_metrics
# Detect drift
drifts = self.metrics_collector.detect_drift(
threshold=self.drift_threshold
)
self.results['drifts_detected'] = drifts
# Update results
self.results['end_time'] = datetime.utcnow().isoformat()
self.results['records_processed'] = records_processed
self.results['validation_rate'] = (
self.validator.stats['valid_records'] /
max(1, self.validator.stats['total_validated'])
)
return self.results
def generate_report(self, format: str = 'json') -> str:
"""Generate test report in specified format"""
report = {
'summary': {
'contract': self.contract.name,
'version': self.contract.version,
'contract_id': self.contract.contract_id,
'total_runtime': (
datetime.fromisoformat(self.results['end_time']) -
datetime.fromisoformat(self.results['start_time'])
).total_seconds() if self.results['start_time'] else 0
},
'validation': {
'records_processed': self.results['records_processed'],
'valid_rate': self.results['validation_rate'],
'invalid_count': self.validator.stats['invalid_records'],
'sample_errors': self.validator.stats['errors'][:5]
},
'drift_analysis': {
'drifts_detected': len(self.results['drifts_detected']),
'details': self.results['drifts_detected']
},
'quality_metrics': self.results['quality_metrics']
}
if format == 'json':
return json.dumps(report, indent=2, default=str)
elif format == 'html':
return self._generate_html_report(report)
else:
return str(report)
6. Usage Example
# Example contract
sales_contract = DataContract(
name="sales_transactions",
version="1.0",
schema={
"type": "object",
"properties": {
"transaction_id": {"type": "string"},
"amount": {"type": "number", "minimum": 0, "maximum": 10000},
"currency": {"type": "string", "enum": ["USD", "EUR", "GBP"]},
"timestamp": {"type": "string", "format": "date-time"},
"customer_id": {"type": "string"},
"product_category": {"type": "string"}
},
"required": ["transaction_id", "amount", "currency"]
},
quality_rules={
"amount": {"min": 0, "max": 10000, "null_rate_threshold": 0.01},
"currency": {"allowed_values": ["USD", "EUR", "GBP"]}
}
)
# Configure harness
harness = DataContractHarness(
contract=sales_contract,
producer_config={
'num_records': 5000,
'invalid_rate': 0.02,
'drift_rules': {
'amount': {'type': 'mean_shift', 'shift': 500} # Shift average by 500
}
},
consumer_config={},
drift_threshold=0.15
)
# Run baseline
baseline_results = harness.run_baseline_test(num_records=5000)
print("Baseline complete:", harness.generate_report())
# Run drift test
drift_results = harness.run_drift_test(
num_records=5000,
drift_rules={
'amount': {'type': 'mean_shift', 'shift': 1000},
'currency': {'type': 'null_increase'}
}
)
print("Drift test complete:", harness.generate_report())
7. Advanced Features (Optional)
class StatisticalDriftDetector:
"""Advanced statistical drift detection"""
@staticmethod
def ks_test(baseline_values: List, current_values: List, alpha: float = 0.05) -> Dict:
"""Kolmogorov-Smirnov test for distribution drift"""
from scipy.stats import ks_2samp
stat, p_value = ks_2samp(baseline_values, current_values)
return {
'statistic': stat,
'p_value': p_value,
'drift_detected': p_value < alpha
}
@staticmethod
def psi(baseline_counts: Dict, current_counts: Dict, bins: int = 10) -> float:
"""Population Stability Index"""
# Convert to bins and calculate PSI
pass
class ContractMonitor:
"""Continuous monitoring of data contracts"""
def __init__(self, contract: DataContract, check_interval: int = 3600):
self.contract = contract
self.check_interval = check_interval
self.history = []
async def monitor_stream(self,
message_queue,
window_size: int = 1000):
"""Monitor streaming data"""
batch = []
while True:
message = await message_queue.get()
batch.append(message)
if len(batch) >= window_size:
await self._analyze_batch(batch)
batch = []
await asyncio.sleep(self.check_interval)
Key Features
- Schema Validation: JSON Schema-based validation with detailed error reporting
- Synthetic Data Generation: Faker-based with configurable distributions
- Drift Simulation: Controlled drift injection (mean shift, null increase, etc.)
- Quality Metrics: Null rates, distributions, distinct counts, statistical moments
- Statistical Tests: KS-test, moment comparison, threshold-based detection
- Sliding Windows: Metrics calculated over configurable windows
- Baseline Comparison: Establish and compare against baselines
- Comprehensive Reporting: JSON/HTML reports with drill-down capabilities
- Extensible: Add new generators, validators, and drift detectors
Deployment Options
# docker-compose.yml for standalone service
version: '3.8'
services:
contract-harness:
image: contract-harness:latest
ports:
- "8080:8080"
volumes:
- ./contracts:/app/contracts
- ./reports:/app/reports
environment:
- CONTRACT_REGISTRY_URL=http://registry:8080
- KAFKA_BOOTSTRAP=kafka:9092
CI/CD Integration
# GitHub Actions example
- name: Run Data Contract Tests
run: |
python -m contract_harness \
--contract ./contracts/sales_v1.json \
--test-type drift \
--threshold 0.1 \
--output reports/sales_drift_$(date +%Y%m%d).json
env:
DATA_SOURCE: ${{ secrets.TEST_DATA_SOURCE }}
This harness provides:
- Producers: Synthetic data generation with drift simulation
- Consumers: Validation + metrics collection
- Schema Verification: JSON Schema validation
- Drift Measurement: Statistical comparison against baseline
- Reporting: Detailed JSON/HTML reports with drift alerts
The design is modular, extensible, and suitable for both batch and streaming scenarios. You can extend it with additional statistical tests, integrate with schema registries (Confluent, AWS Glue), and add monitoring dashboards.