We are going to design a data validation pipeline that uses:
- JSON Schema for structural validation (type checks, required fields, etc.)
- Domain policies (business rules) for logical validation (e.g., age must be between 0 and 120, email format, etc.)
- ML anomaly detectors for outlier detection (we'll use an isolation forest as an example, but note that for a real system we might train on historical data)
Steps:
- We assume the input is a JSON object (or a list of JSON objects for batch processing).
- We'll define a JSON schema for the expected structure.
- We'll define domain policies as functions that take a JSON object and return a boolean or a list of errors.
- We'll train an anomaly detector (or load a pre-trained one) and use it to flag outliers.
However, note that the ML part is typically applied to numerical features and might require the data to be in a fixed format.
We'll have to decide on the feature set for the anomaly detector.
Let's break down:
Step 1: Structural Validation with JSON Schema
- We'll use a library like
jsonschema in Python.
Step 2: Domain Policies
- We'll write a set of functions that check each record against business rules.
Step 3: Anomaly Detection
- We'll use an Isolation Forest (or other) that has been trained on historical normal data.
- We need to extract features from the record that the model expects.
But note: The input JSON might have mixed types. We have to convert it to a feature vector that the model understands.
We'll design the pipeline as:
For each record in the input (or for the single record):
-
Validate against JSON schema.
- If fails, collect errors and mark as invalid.
-
If structural validation passes, run domain policies.
- If any policy fails, collect errors and mark as invalid.
-
If both pass, then convert the record to a feature vector (only for the features the model was trained on) and run the anomaly detector.
- If the model predicts it as an outlier (or with a score beyond a threshold), mark as outlier.
We'll collect:
- Structural errors (from step 1)
- Domain errors (from step 2)
- Outlier flag and score (from step 3)
We can then decide on an overall status: valid, invalid (with reasons), outlier, etc.
Implementation:
We'll create a class DataValidationPipeline that takes:
- json_schema: a dict representing the JSON schema.
- domain_policies: a list of functions, each taking a record and returning (bool, error_message) or raising an exception?
- anomaly_model: a trained model (with a `predict` or `score_samples` method) and a threshold for outlier.
- feature_extractor: a function that takes a record and returns a feature vector (list or array) for the model.
Alternatively, we can design the feature extractor to be part of the model if the model expects a fixed set of features.
Steps in the class:
def __init__(self, json_schema, domain_policies, anomaly_model, feature_extractor, anomaly_threshold=0.5):
...
def validate_record(self, record):
errors = []
# Step 1: JSON Schema validation
try:
validate(instance=record, schema=self.json_schema)
except ValidationError as e:
errors.append(f"Schema validation error: {e.message}")
# Step 2: Domain policies
for policy in self.domain_policies:
try:
policy(record) # if the policy raises an exception, we catch it
except Exception as e:
errors.append(f"Policy violation: {e}")
# Step 3: Anomaly detection (only if no structural or domain errors? or always?)
# We might want to run anomaly detection even if there are errors? But then the features might be missing.
# Let's run it only if there are no errors so far? Or we can run it and note that the record might be invalid and also an outlier.
# We'll run it only if there are no errors to avoid issues with missing features.
outlier_score = None
is_outlier = False
if not errors:
try:
features = self.feature_extractor(record)
# We assume the model has a `score_samples` method that returns an anomaly score (lower means more anomalous for IsolationForest)
# Alternatively, we can use `predict` which returns -1 for outliers and 1 for inliers.
# Let's assume we use `score_samples` and then compare to threshold.
score = self.anomaly_model.score_samples([features])[0]
outlier_score = score
is_outlier = score < self.anomaly_threshold # because IsolationForest returns negative scores for outliers?
# But note: IsolationForest returns the opposite of the anomaly score defined in the original paper.
# The `score_samples` returns the negative of the anomaly score, so the lower, the more abnormal.
# So we set a threshold on the negative score? Actually, the `contamination` parameter sets the threshold.
# Alternatively, we can use `predict` which returns -1 for outliers and 1 for inliers.
# Let's change: we'll use `predict` and then set is_outlier = (prediction == -1)
# But then we don't have a score. We can use the score_samples and then set a threshold.
# However, note: the threshold might be set by the user. We'll let the user set the threshold for the score.
# But the score from IsolationForest is not bounded. So we might need to calibrate.
# Alternatively, we can use the `contamination` parameter to set the threshold automatically?
# But we are using a pre-trained model. So we'll stick to a threshold on the score.
# Let's change the approach: we'll use `predict` and set is_outlier = (prediction == -1)
# and then we don't have a score. But then we cannot adjust the threshold without retraining.
# We'll change the class to use `predict` and then the user can set the `contamination` when training the model.
# Then we don't need a threshold here. But the user might want to adjust the threshold without retraining?
# Given the complexity, let's stick to score_samples and a threshold. We'll document that the threshold is on the negative score.
# But note: the score_samples returns the negative of the average path length. So the lower (more negative) the more anomalous.
# We'll do:
# is_outlier = (score < self.anomaly_threshold)
# However, the threshold must be set appropriately. We can set it by looking at the scores on a validation set.
# We'll leave it as an argument with a default that might be set by the user.
except Exception as e:
errors.append(f"Anomaly detection failed: {e}")
# Return a result object
return {
"errors": errors,
"is_valid": len(errors) == 0,
"is_outlier": is_outlier,
"outlier_score": outlier_score
}
But note: what if the record is invalid? Should we still run the anomaly detector? We skip it because the feature extractor might fail.
We can change:
if not errors:
... run anomaly detection ...
Alternatively, we can run the anomaly detection and if the feature extractor fails, we catch that and add an error.
We'll do:
outlier_score = None
is_outlier = False
try:
features = self.feature_extractor(record)
score = self.anomaly_model.score_samples([features])[0]
outlier_score = score
is_outlier = score < self.anomaly_threshold
except Exception as e:
errors.append(f"Anomaly detection failed: {e}")
But note: if there are already errors, we are appending another error. That's okay.
However, we might want to separate the errors: structural, domain, and anomaly detection errors.
We can change the return to:
{
"structural_errors": [...],
"domain_errors": [...],
"anomaly_error": None or string,
"is_outlier": bool,
"outlier_score": float or None
}
But the problem is that the domain policies are run only after structural validation? We run all domain policies regardless?
Actually, we run:
1. Structural validation: if it fails, we record structural errors and then still run domain policies?
But if the structural validation fails, the record might be missing fields that domain policies check.
We have two options:
Option A: Run structural validation first. If it fails, skip domain policies and anomaly detection?
But then we might miss domain errors? But the domain policies might rely on the structure being correct.
Option B: Run structural validation and collect errors, then run domain policies and collect errors, then run anomaly detection.
We'll do Option B, but note that domain policies might fail because of missing fields due to structural issues.
We can change:
structural_errors = []
try:
validate(instance=record, schema=self.json_schema)
except ValidationError as e:
structural_errors.append(e.message)
domain_errors = []
for policy in self.domain_policies:
try:
policy(record)
except Exception as e:
domain_errors.append(str(e))
anomaly_error = None
outlier_score = None
is_outlier = False
if not structural_errors and not domain_errors:
try:
features = self.feature_extractor(record)
score = self.anomaly_model.score_samples([features])[0]
outlier_score = score
is_outlier = score < self.anomaly_threshold
except Exception as e:
anomaly_error = str(e)
return {
"structural_errors": structural_errors,
"domain_errors": domain_errors,
"anomaly_error": anomaly_error,
"is_outlier": is_outlier,
"outlier_score": outlier_score,
"is_valid": len(structural_errors) == 0 and len(domain_errors) == 0 and anomaly_error is None
}
But note: the anomaly detection might fail even if there are no structural or domain errors, and then we mark the record as invalid?
Actually, the record might be structurally and domain-valid but the feature extractor or model fails. We consider that an error.
However, the user might consider that the record is still valid in terms of structure and domain, but we couldn't check for outliers.
We can change the is_valid to only consider structural and domain, and then have a separate flag for outlier and anomaly detection error.
Let's redefine:
is_structurally_valid = len(structural_errors) == 0
is_domain_valid = len(domain_errors) == 0
anomaly_detection_success = anomaly_error is None
Then we can have:
overall_valid = is_structurally_valid and is_domain_valid and anomaly_detection_success?
But the user might want to know that the record is valid in structure and domain, but outlier detection failed.
We'll return:
{
"structural_errors": ...,
"domain_errors": ...,
"anomaly_error": ...,
"is_structurally_valid": is_structurally_valid,
"is_domain_valid": is_domain_valid,
"is_anomaly_detection_success": anomaly_detection_success,
"is_outlier": is_outlier, # only set if anomaly_detection_success is True
"outlier_score": outlier_score # only set if anomaly_detection_success is True
}
Then the user can decide:
- If structurally valid and domain valid and anomaly_detection_success, then the record is fully validated and we know if it's an outlier.
- If structurally valid and domain valid but anomaly_detection_failed, then we have a record that is valid by our rules but we couldn't check for outliers.
Alternatively, we can consider that the record is not fully validated if anomaly detection fails? But the anomaly detection is an additional check.
We'll leave it to the user to interpret.
However, note that the anomaly detection might be considered a critical part of the pipeline? It depends.
We'll stick to the above.
But note: the domain policies might also be considered part of the validation, so if they fail, the record is invalid.
We'll let the user combine these flags as they wish.
Alternatively, we can have:
is_valid = is_structurally_valid and is_domain_valid
and then separately note the anomaly detection.
That seems more reasonable.
Let's change:
return {
"structural_errors": structural_errors,
"domain_errors": domain_errors,
"anomaly_error": anomaly_error,
"is_valid": is_structurally_valid and is_domain_valid,
"is_outlier": is_outlier if anomaly_detection_success else None,
"outlier_score": outlier_score if anomaly_detection_success else None
}
But then we lose the separate flags for structural and domain? We can keep them too.
We'll return:
{
"structural_errors": structural_errors,
"domain_errors": domain_errors,
"anomaly_error": anomaly_error,
"is_structurally_valid": is_structurally_valid,
"is_domain_valid": is_domain_valid,
"is_valid": is_structurally_valid and is_domain_valid,
"is_anomaly_detection_success": anomaly_detection_success,
"is_outlier": is_outlier if anomaly_detection_success else None,
"outlier_score": outlier_score if anomaly_detection_success else None
}
That's a lot, but it's informative.
However, note that the anomaly detection might be run only when the record is structurally and domain valid?
In our code above, we run it only if there are no structural and domain errors. Why?
Because if there are structural errors, the record might be missing fields that the feature extractor needs.
Similarly, domain errors might indicate that the record is invalid and we might not want to run the anomaly detector on invalid data.
We can change the condition to run anomaly detection regardless? But then the feature extractor might fail.
We'll run the anomaly detection only if there are no structural and domain errors, because we assume that the feature extractor expects a valid record.
Alternatively, we can run the anomaly detection and if the feature extractor fails, we catch that and set anomaly_error.
But if the record is structurally invalid, the feature extractor might not be able to extract features? It depends on the feature extractor.
We'll leave it as:
if not structural_errors and not domain_errors:
... run anomaly detection ...
So that we only run it on records that are valid by our rules.
This is a design choice: we might not trust the anomaly detector on invalid data.
Alternatively, we might want to run it on all records and then if the feature extractor fails, we mark that as an error.
We'll change to:
anomaly_error = None
outlier_score = None
is_outlier = False
try:
features = self.feature_extractor(record)
score = self.anomaly_model.score_samples([features])[0]
outlier_score = score
is_outlier = score < self.anomaly_threshold
except Exception as e:
anomaly_error = str(e)
And remove the condition. Then we run it on every record, but if the record is structurally invalid, the feature extractor might fail.
We'll let the user decide: if they want to run anomaly detection only on valid records, they can check is_valid and then look at is_outlier only when is_valid is True.
But then we are running the feature extractor on invalid records and it might fail, and we record the error.
We'll do:
We run the anomaly detection regardless, and if it fails, we set `anomaly_error`.
But note: the feature extractor might rely on the record being valid. So if the record is invalid, the feature extractor might throw an exception.
We catch that and set `anomaly_error`.
So:
Steps:
1. Structural validation (always)
2. Domain policies (always)
3. Anomaly detection (always)
Then:
is_structurally_valid = no structural errors
is_domain_valid = no domain errors
is_valid = is_structurally_valid and is_domain_valid (without considering anomaly)
anomaly_detection_success = anomaly_error is None
Then, if anomaly_detection_success, we have is_outlier and outlier_score.
But note: if the record is invalid, the anomaly detection might have failed because of missing fields? Then we set anomaly_error.
We'll do:
try:
features = self.feature_extractor(record)
...
except Exception as e:
anomaly_error = str(e)
So the anomaly detection might fail because of invalid record, and that's okay.
We'll change the code accordingly.
Let's code accordingly.
However, note that the user might want to run the anomaly detection only on valid records. But we are running on all.
We can add a flag to the class: run_anomaly_on_invalid? But let's not complicate.
We'll run anomaly detection on every record and let the user decide.
Implementation:
We'll use:
from jsonschema import validate, ValidationError
For the anomaly model, we assume it's an IsolationForest from sklearn, but we'll just use the interface.
Example:
pipeline = DataValidationPipeline(
json_schema={...},
domain_policies=[policy1, policy2, ...],
anomaly_model=isolation_forest, # trained model
feature_extractor=lambda record: [record['age'], record['income']], # example
anomaly_threshold=-0.5 # example, depends on the model
)
Then:
result = pipeline.validate_record(record)
For batch, we can have:
def validate_batch(self, records):
return [self.validate_record(record) for record in records]
But note: the anomaly model's score_samples can take a 2D array, so we might want to batch the anomaly detection for efficiency.
However, the feature extraction might be record-specific. We can change the batch validation to:
Step 1: Validate each record structurally and with domain policies (these are per record).
Step 2: For records that are valid (or all records, depending on design) we extract features and then do a batch score.
But if we are running anomaly detection on invalid records, we might have to run feature extraction on them too, which might fail.
We'll stick to per record for simplicity.
Alternatively, we can do:
results = []
valid_records = []
indices_of_valid = []
for i, record in enumerate(records):
result = self.validate_record(record) # but without anomaly detection? We want to do anomaly in batch.
...
We'll redesign:
We'll split:
Step 1: For each record, do structural and domain validation. Collect errors.
Step 2: For records that are structurally and domain valid (or all records, but we have to handle feature extraction failures) we extract features.
But if we run feature extraction on every record, we might get failures for invalid ones.
We can do:
structural_errors_list = []
domain_errors_list = []
anomaly_errors_list = []
is_outlier_list = []
outlier_score_list = []
for record in records:
# structural and domain
structural_errors = ...
domain_errors = ...
structural_errors_list.append(structural_errors)
domain_errors_list.append(domain_errors)
# Now, if we want to run anomaly detection only on valid records, we check:
if not structural_errors and not domain_errors:
try:
features = self.feature_extractor(record)
...
except Exception as e:
anomaly_errors_list.append(str(e))
is_outlier_list.append(None)
outlier_score_list.append(None)
else:
anomaly_errors_list.append(None) # or we don't run, so we set to None?
is_outlier_list.append(None)
outlier_score_list.append(None)
But then we are not running on invalid records.
Alternatively, we run on every record and catch feature extraction errors.
We'll do:
for record in records:
# structural and domain
...
# anomaly
try:
features = self.feature_extractor(record)
score = self.anomaly_model.score_samples([features])[0]
outlier_score = score
is_outlier = score < self.anomaly_threshold
anomaly_error = None
except Exception as e:
outlier_score = None
is_outlier = None
anomaly_error = str(e)
Then we return per record.
But then we are not batching the anomaly detection. We can batch the feature extraction and scoring for efficiency.
Let's redesign the batch method:
We want to avoid looping for anomaly detection if possible.
Steps:
1. For each record, do structural and domain validation. We have to loop because each record is independent.
2. Then, for the records that we want to run anomaly detection on (say, all records that are structurally and domain valid, or all records regardless) we extract features.
3. Then we run the anomaly model on the entire set of features at once.
But note: if we run on all records, we might have feature extraction failures for some records.
We can do:
valid_indices = [] # indices of records that we will attempt feature extraction (maybe all, or only those without structural/domain errors)
features_list = []
for i, record in enumerate(records):
# structural and domain validation
structural_errors = ...
domain_errors = ...
structural_errors_list.append(structural_errors)
domain_errors_list.append(domain_errors)
# if we want to run anomaly on this record (say, if no structural and domain errors) then we try to extract features.
if not structural_errors and not domain_errors:
try:
features = self.feature_extractor(record)
features_list.append(features)
valid_indices.append(i)
except Exception as e:
# feature extraction failed for a record that was structurally and domain valid?
anomaly_errors_list[i] = str(e)
is_outlier_list[i] = None
outlier_score_list[i] = None
else:
# we skip anomaly detection for this record because it's invalid.
# but we might still want to try if the user wants? We are not.
anomaly_errors_list.append(None) # or we don't set, but we want to have the same length.
is_outlier_list.append(None)
outlier_score_list.append(None)
Then, if we have any features in features_list, we run:
scores = self.anomaly_model.score_samples(features_list)
Then we assign:
for idx, score in zip(valid_indices, scores):
outlier_score_list[idx] = score
is_outlier_list[idx] = score < self.anomaly_threshold
But note: we already set the anomaly_error for the ones that failed feature extraction? We set it in the except.
We have to initialize the lists for the entire batch.
This is getting complex.
Given the complexity, and since the number of records might not be huge, we can stick to per record.
We'll do:
class DataValidationPipeline:
def __init__(self, json_schema, domain_policies, anomaly_model, feature_extractor, anomaly_threshold=0.5):
self.json_schema = json_schema
self.domain_policies = domain_policies
self.anomaly_model = anomaly_model
self.feature_extractor = feature_extractor
self.anomaly_threshold = anomaly_threshold
def validate_record(self, record):
# Step 1: structural
structural_errors = []
try:
validate(instance=record, schema=self.json_schema)
except ValidationError as e:
structural_errors.append(e.message)
# Step 2: domain
domain_errors = []
for policy in self.domain_policies:
try:
policy(record)
except Exception as e:
domain_errors.append(str(e))
# Step 3: anomaly
anomaly_error = None
outlier_score = None
is_outlier = None
try:
features = self.feature_extractor(record)
# We assume the model has a `score_samples` method that returns an array.
# We pass [features] and take the first element.
score = self.anomaly_model.score_samples([features])[0]
outlier_score = score
is_outlier = score < self.anomaly_threshold
except Exception as e:
anomaly_error = str(e)
return {
"structural_errors": structural_errors,
"domain_errors": domain_errors,
"anomaly_error": anomaly_error,
"is_structurally_valid": len(structural_errors) == 0,
"is_domain_valid": len(domain_errors) == 0,
"is_valid": len(structural_errors) == 0 and len(domain_errors) == 0,
"is_anomaly_detection_success": anomaly_error is None,
"is_outlier": is_outlier,
"outlier_score": outlier_score
}
def validate_batch(self, records):
return [self.validate_record(record) for record in records]
But note: the anomaly detection might be run on records that are invalid? Yes, we run it on every record.
However, the user might not want to run anomaly detection on invalid records? We can add a flag:
run_anomaly_on_invalid: bool = False
Then in validate_record:
if not run_anomaly_on_invalid and (structural_errors or domain_errors):
anomaly_error = "Skipped because record is invalid"
is_outlier = None
outlier_score = None
else:
... run anomaly detection ...
But then we are not running the feature extraction on invalid records, which might be good because the feature extractor might expect valid records.
We'll add an option:
def __init__(..., run_anomaly_on_invalid=False):
self.run_anomaly_on_invalid = run_anomaly_on_invalid
Then in validate_record:
if not self.run_anomaly_on_invalid and (structural_errors or domain_errors):
anomaly_error = "Skipped because record is invalid"
is_outlier = None
outlier_score = None
else:
try:
...
except Exception as e:
...
But then we are setting anomaly_error to a string even though we didn't try? That might be confusing.
Alternatively, we can set:
if not self.run_anomaly_on_invalid and (structural_errors or domain_errors):
anomaly_error = None # meaning we didn't run, so no error but also no result.
is_outlier = None
outlier_score = None
else:
...
Then we can have a field anomaly_detection_attempted? We already have is_anomaly_detection_success which is True only if we attempted and succeeded.
We can change:
if we attempted, then `is_anomaly_detection_success` is True if no error, False if error.
if we didn't attempt, then `is_anomaly_detection_success` is False? But then we don't know if we attempted.
We can have:
anomaly_detection_attempted = True/False
But let's not overcomplicate.
We'll stick to:
We run anomaly detection only if the record is valid (by structure and domain) when `run_anomaly_on_invalid` is False.
Otherwise, we run on every record.
And then:
if we run and it succeeds: anomaly_error is None, and we have is_outlier and outlier_score.
if we run and it fails: anomaly_error is set, is_outlier and outlier_score are None.
if we don't run: anomaly_error is None? But we didn't run, so we set:
anomaly_error = "Skipped because record is invalid" only if run_anomaly_on_invalid is False and record is invalid.
But then the user can check:
if anomaly_error is not None and "Skipped" in anomaly_error -> not run.
Alternatively, we can have:
anomaly_status: one of "success", "failed", "skipped"
We'll change the return to:
"anomaly_status": "success" if anomaly_error is None and we attempted,
"failed" if anomaly_error is not None and we attempted,
"skipped" if we didn't attempt.
Then:
if we attempted and succeeded:
anomaly_status = "success"
anomaly_error = None
is_outlier = ...
outlier_score = ...
if we attempted and failed:
anomaly_status = "failed"
anomaly_error = ... (the error message)
is_outlier = None
outlier_score = None
if we didn't attempt:
anomaly_status = "skipped"
anomaly_error = None # or we can set to "Skipped because record is invalid" but then we have two ways to get "skipped"?
is_outlier = None
outlier_score = None
We'll do:
if self.run_anomaly_on_invalid or (not structural_errors and not domain_errors):
# attempt
try:
features = self.feature_extractor(record)
score = self.anomaly_model.score_samples([features])[0]
outlier_score = score
is_outlier = score < self.anomaly_threshold
anomaly_status = "success"
anomaly_error = None
except Exception as e:
anomaly_status = "failed"
anomaly_error = str(e)
is_outlier = None
outlier_score = None
else:
anomaly_status = "skipped"
anomaly_error = None
is_outlier = None
outlier_score = None
Then return:
{
"structural_errors": ...,
"domain_errors": ...,
"anomaly_status": anomaly_status,
"anomaly_error": anomaly_error,
"is_structurally_valid": ...,
"is_domain_valid": ...,
"is_valid": ...,
"is_outlier": is_outlier, # only set if anomaly_status=="success"
"outlier_score": outlier_score # only set if anomaly_status=="success"
}
This is more informative.
Let's code accordingly.
However, note that the user might want to run anomaly detection on invalid records too? Then set run_anomaly_on_invalid=True.
We'll do:
class DataValidationPipeline:
def __init__(self, json_schema, domain_policies, anomaly_model, feature_extractor, anomaly_threshold=0.5, run_anomaly_on_invalid=False):
...
def validate_record(self, record):
# structural and domain as before
# Determine if we should attempt anomaly detection
should_attempt = self.run_anomaly_on_invalid or (len(structural_errors)==0 and len(domain_errors)==0)
if should_attempt:
try:
features = self.feature_extractor(record)
score = self.anomaly_model.score_samples([features])[0]
outlier_score = score
is_outlier = score < self.anomaly_threshold
anomaly_status = "success"
anomaly_error = None
except Exception as e:
anomaly_status = "failed"
anomaly_error = str(e)
outlier_score = None
is_outlier = None
else:
anomaly_status = "skipped"
anomaly_error = None
outlier_score = None
is_outlier = None
return {
"structural_errors": structural_errors,
"domain_errors": domain_errors,
"anomaly_status": anomaly_status,
"anomaly_error": anomaly_error,
"is_structurally_valid": len(structural_errors) == 0,
"is_domain_valid": len(domain_errors) == 0,
"is_valid": len(structural_errors) == 0 and len(domain_errors) == 0,
"is_outlier": is_outlier,
"outlier_score": outlier_score
}
This seems good.
But note: the is_valid does not consider anomaly detection. That's by design: the record can be valid by schema and domain but still be an outlier.
The user can then decide:
if result['is_valid'] and result['anomaly_status'] == 'success' and result['is_outlier']:
... handle outlier ...
Or if they want to reject outliers even if valid, they can.
Let's write an example.
Example:
json_schema = {
"type": "object",
"properties": {
"age": {"type": "number"},
"income": {"type": "number"},
"email": {"type": "string", "format": "email"}
},
"required": ["age", "income", "email"]
}
domain_policies = [
lambda r: (0 <= r['age'] <= 120, "Age must be between 0 and 120"),
lambda r: (r['income'] >= 0, "Income must be non-negative")
]
feature_extractor = lambda r: [r['age'], r['income']]
Then we train an IsolationForest on historical data (only on the valid records?).
But note: the feature extractor might fail if the record is invalid? For example, if 'age' is missing, then r['age'] will throw KeyError.
In our example, if the record is missing 'age', then the structural validation will catch it (because it's required) and then we won't run the feature extractor if run_anomaly_on_invalid=False.
If run_anomaly_on_invalid=True, then we try to extract features and it will fail because of missing key, and then we get anomaly_status='failed'.
That's acceptable.
We'll leave it as is.
Let's code accordingly.
We'll also note that the domain policies are functions that return a tuple (bool, message) and we expect them to not raise?
But we catch any exception. We can change:
for policy in self.domain_policies:
try:
valid, msg = policy(record)
if not valid:
domain_errors.append(msg)
except Exception as e:
domain_errors.append(str(e))
But the policy might not return a tuple? We can design the policy to either:
- return a tuple (bool, str) and we check the bool, and if false we add the str.
- or raise an exception with the error message.
We'll support both? We'll try to unpack, and if it returns a tuple we use it, else if it returns a bool we use a generic message, else we treat as exception?
Alternatively, we can require the policy to return a tuple or raise. Let's require:
The policy function should either:
- return a tuple (bool, str) where the string is the error message if bool is False.
- or raise an exception with the error message.
Then we do:
try:
result = policy(record)
if isinstance(result, tuple) and len(result)==2:
valid, msg = result
if not valid:
domain_errors.append(msg)
else:
# If it returns something else, we consider it valid? Or we treat as error?
# We'll treat as: if it returns a bool and it's False, then we add a generic message.
# But the user might have returned just a bool.
if result is False:
domain_errors.append("Policy failed without message")
# if True, we do nothing.
except Exception as e:
domain_errors.append(str(e))
This is getting messy.
Let's simplify: the policy function must return a tuple (bool, str) or raise an exception.
We'll do:
for policy in self.domain_policies:
try:
valid, msg = policy(record)
if not valid:
domain_errors.append(msg)
except ValueError as e:
# If the policy raises a ValueError, we use its message.
domain_errors.append(str(e))
except Exception as e:
# Any other exception, we also record.
domain_errors.append(str(e))
But what if the policy returns something that is not a tuple? We get a ValueError: too many values to unpack.
We'll catch that and treat as an error.
Alternatively, we can do:
try:
result = policy(record)
if isinstance(result, tuple):
valid, msg = result
if not valid:
domain_errors.append(msg)
else:
# If it's a bool, we use a generic message.
if result is False:
domain_errors.append("Policy failed without message")
# if True, ignore.
except Exception as e:
domain_errors.append(str(e))
We'll do the latter.
But note: the policy might return None? Then we ignore.
We'll change:
try:
result = policy(record)
if isinstance(result, tuple):
if len(result) != 2:
domain_errors.append(f"Policy returned tuple of wrong length: {result}")
else:
valid, msg = result
if not valid:
domain_errors.append(msg)
else:
if result is False:
domain_errors.append("Policy failed without message")
# else: True or None, we ignore.
except Exception as e:
domain_errors.append(str(e))
This is acceptable.
Let's code accordingly.
We'll write the class as described.
Note: The anomaly model's score_samples returns an array of scores. We are taking the first element because we passed a single sample.
But what if the model expects multiple features? We are passing a 1D array. The model expects 2D: (n_samples, n_features). We are doing [features] to make it 2D with one row.
This is correct.
Let's code.
We'll also note that the user might have a different model that uses predict instead of score_samples. We can make it flexible?
We'll assume the model has a score_samples method. If not, we can try predict? But predict returns -1 for outliers and 1 for inliers.
We can check:
if hasattr(anomaly_model, 'score_samples'):
score = anomaly_model.score_samples([features])[0]
is_outlier = score < anomaly_threshold
elif hasattr(anomaly_model, 'predict'):
pred = anomaly_model.predict([features])[0]
is_outlier = pred == -1
score = None # we don't have a score
else:
raise ValueError("Anomaly model must have either 'score_samples' or 'predict' method")
But then the threshold is only used for score_samples.
We'll change:
if hasattr(self.anomaly_model, 'score_samples'):
score = self.anomaly_model.score_samples([features])[0]
is_outlier = score < self.anomaly_threshold
outlier_score = score
elif hasattr(self.anomaly_model, 'predict'):
pred = self.anomaly_model.predict([features])[0]
is_outlier = (pred == -1)
outlier_score = None # we don't have a continuous score
else:
raise ValueError("Anomaly model must have either 'score_samples' or 'predict' method")
Then we adjust: outlier_score might be None.
We'll do that.
Let's code accordingly.
We'll also note that the feature extractor must return a 1D array-like (list or numpy array) of numbers.
We'll assume the feature extractor does that.
Now, we put it all together.
We'll write the class with:
__init__
validate_record
validate_batch
We'll also include a method to set the anomaly threshold? Or we can change it in the constructor only.
We'll leave it as constructor argument.
Let's code.
Here's a comprehensive data validation pipeline that combines JSON Schema validation, domain-specific business rules, and machine learning-based anomaly detection:
Architecture Overview
graph LR
A[Input Data] --> B[JSON Schema Validator]
B --> C[Schema Errors?]
C -->|Yes| D[Reject/Log]
C -->|No| E[Domain Policy Engine]
E --> F[Policy Violations?]
F -->|Yes| D
F -->|No| G[Feature Extractor]
G --> H[ML Anomaly Detector]
H --> I[Anomaly Score]
I --> J{Score > Threshold?}
J -->|Yes| K[Flag as Outlier]
J -->|No| L[Accept as Valid]
K --> M[Quarantine/Review]
L --> N[Pass to Downstream]
Implementation
1. JSON Schema Validator (Structural Validation)
from jsonschema import validate, ValidationError
import json
class JSONSchemaValidator:
def __init__(self, schema_path: str):
with open(schema_path) as f:
self.schema = json.load(f)
def validate(self, record: dict) -> dict:
"""Validate record against JSON schema"""
try:
validate(instance=record, schema=self.schema)
return {"valid": True, "errors": []}
except ValidationError as e:
return {
"valid": False,
"errors": [{
"field": ".".join(str(p) for p in e.path),
"message": e.message,
"validator": e.validator
}]
}
2. Domain Policy Engine (Business Rule Validation)
class DomainPolicyEngine:
def __init__(self, policies: list[callable]):
"""
policies: List of functions that take a record and return (bool, str)
where bool indicates pass/fail and str is error message
"""
self.policies = policies
def validate(self, record: dict) -> dict:
errors = []
for policy in self.policies:
try:
passed, msg = policy(record)
if not passed:
errors.append(msg)
except Exception as e:
errors.append(f"Policy execution error: {str(e)}")
return {"valid": len(errors) == 0, "errors": errors}
# Example policies
def age_policy(record):
age = record.get("age")
if age and (age < 0 or age > 120):
return False, f"Invalid age: {age}"
return True, ""
def transaction_limit_policy(record):
amount = record.get("amount", 0)
if amount > 10000: # Example threshold
return False, f"Transaction amount {amount} exceeds limit"
return True, ""
3. ML Anomaly Detector (Outlier Detection)
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
import numpy as np
import joblib
class MLAnomalyDetector:
def __init__(self, model_path: str = None, scaler_path: str = None,
contamination: float = 0.1, random_state: int = 42):
"""
contamination: Expected proportion of outliers (0.01-0.1 typical)
"""
self.scaler = StandardScaler() if scaler_path is None else joblib.load(scaler_path)
self.model = (IsolationForest(contamination=contamination,
random_state=random_state)
if model_path is None else joblib.load(model_path))
self.feature_columns = None # Set during training
def train(self, training_data: list[dict], feature_columns: list[str]):
"""Train on historical normal data"""
self.feature_columns = feature_columns
X = self._extract_features(training_data, feature_columns)
X_scaled = self.scaler.fit_transform(X)
self.model.fit(X_scaled)
def _extract_features(self, records: list[dict], feature_columns: list[str]) -> np.ndarray:
"""Extract numerical features from records"""
features = []
for record in records:
row = []
for col in feature_columns:
val = record.get(col, 0)
# Handle non-numerical with encoding if needed
row.append(float(val) if isinstance(val, (int, float)) else 0.0)
features.append(row)
return np.array(features)
def predict(self, record: dict) -> dict:
"""Return anomaly score and flag"""
try:
X = self._extract_features([record], self.feature_columns)
X_scaled = self.scaler.transform(X)
# IsolationForest returns -1 for outliers, 1 for inliers
prediction = self.model.predict(X_scaled)[0]
# Get anomaly score (more negative = more anomalous)
score = self.model.decision_function(X_scaled)[0]
return {
"is_outlier": prediction == -1,
"anomaly_score": float(score),
"confidence": abs(score) # Higher absolute value = higher confidence
}
except Exception as e:
return {
"is_outlier": False,
"anomaly_score": None,
"error": f"ML prediction failed: {str(e)}"
}
4. Orchestration Pipeline
from datetime import datetime
import logging
logger = logging.getLogger(__name__)
class DataValidationPipeline:
def __init__(self, schema_validator: JSONSchemaValidator,
policy_engine: DomainPolicyEngine,
anomaly_detector: MLAnomalyDetector,
config: dict = None):
self.schema_validator = schema_validator
self.policy_engine = policy_engine
self.anomaly_detector = anomaly_detector
self.config = config or {
"stop_on_schema_error": True,
"stop_on_policy_error": True,
"anomaly_threshold_confidence": 0.5, # Min confidence to flag
"quarantine_outliers": True
}
def validate_record(self, record: dict, record_id: str = None) -> dict:
"""Validate single record through all stages"""
result = {
"record_id": record_id,
"timestamp": datetime.utcnow().isoformat(),
"schema_validation": None,
"policy_validation": None,
"anomaly_detection": None,
"final_status": "UNKNOWN",
"errors": []
}
# Stage 1: JSON Schema Validation
schema_result = self.schema_validator.validate(record)
result["schema_validation"] = {
"valid": schema_result["valid"],
"errors": schema_result["errors"]
}
if not schema_result["valid"]:
result["errors"].extend([f"Schema: {e['message']}" for e in schema_result["errors"]])
result["final_status"] = "SCHEMA_FAIL"
logger.warning(f"Record {record_id} failed schema validation")
if self.config["stop_on_schema_error"]:
return result
# Continue to policies even with schema errors if configured
# Stage 2: Domain Policies
policy_result = self.policy_engine.validate(record)
result["policy_validation"] = {
"valid": policy_result["valid"],
"errors": policy_result["errors"]
}
if not policy_result["valid"]:
result["errors"].extend([f"Policy: {e}" for e in policy_result["errors"]])
if result["final_status"] != "SCHEMA_FAIL":
result["final_status"] = "POLICY_FAIL"
logger.warning(f"Record {record_id} failed policy validation")
if self.config["stop_on_policy_error"]:
return result
# Stage 3: ML Anomaly Detection (only if schema/policy passed)
if schema_result["valid"] and policy_result["valid"]:
anomaly_result = self.anomaly_detector.predict(record)
result["anomaly_detection"] = anomaly_result
if anomaly_result.get("is_outlier", False):
confidence = anomaly_result.get("confidence", 0)
if confidence >= self.config["anomaly_threshold_confidence"]:
result["final_status"] = "OUTLIER"
result["errors"].append(
f"Anomaly detected (score: {anomaly_result['anomaly_score']:.3f}, "
f"confidence: {confidence:.3f})"
)
logger.warning(f"Record {record_id} flagged as outlier")
else:
result["final_status"] = "LOW_CONFIDENCE_OUTLIER"
else:
result["final_status"] = "VALID"
else:
result["final_status"] = "SKIPPED_ANOMALY"
return result
def validate_batch(self, records: list[dict], batch_id: str = None) -> dict:
"""Validate batch of records and generate summary"""
results = []
summary = {
"batch_id": batch_id,
"total": len(records),
"passed": 0,
"failed_schema": 0,
"failed_policy": 0,
"outliers": 0,
"errors": []
}
for i, record in enumerate(records):
record_id = f"{batch_id}_{i}" if batch_id else str(i)
result = self.validate_record(record, record_id)
results.append(result)
# Update summary
status = result["final_status"]
if status == "VALID":
summary["passed"] += 1
elif status == "SCHEMA_FAIL":
summary["failed_schema"] += 1
elif status == "POLICY_FAIL":
summary["failed_policy"] += 1
elif status == "OUTLIER":
summary["outliers"] += 1
return {
"summary": summary,
"results": results,
"batch_timestamp": datetime.utcnow().isoformat()
}
def quarantine_outliers(self, results: list[dict]) -> list[dict]:
"""Extract outlier records for manual review"""
return [r for r in results if r["final_status"] == "OUTLIER"]
5. Configuration & Deployment Example
# config.yaml
pipeline:
schema_path: "schemas/transaction_schema.json"
policies:
- "policies.age_policy"
- "policies.transaction_limit_policy"
- "policies.merchant_whitelist"
anomaly_detector:
model_path: "models/anomaly_detector.joblib"
scaler_path: "models/scaler.joblib"
feature_columns: ["amount", "hour_of_day", "merchant_category", "location_distance"]
contamination: 0.05
threshold_confidence: 0.7
execution:
stop_on_schema_error: true
stop_on_policy_error: false
quarantine_outliers: true
alert_channels: ["slack", "email"]
# usage.py
def main():
# Initialize components
validator = JSONSchemaValidator("schemas/transaction_schema.json")
policy_engine = DomainPolicyEngine([
age_policy,
transaction_limit_policy,
# ... more policies
])
anomaly_detector = MLAnomalyDetector(
model_path="models/isolation_forest.joblib",
scaler_path="models/minmax_scaler.joblib"
)
pipeline = DataValidationPipeline(
schema_validator=validator,
policy_engine=policy_engine,
anomaly_detector=anomaly_detector,
config={
"anomaly_threshold_confidence": 0.7,
"quarantine_outliers": True
}
)
# Process stream
for record in data_stream:
result = pipeline.validate_record(record)
if result["final_status"] == "VALID":
send_to_downstream(record)
elif result["final_status"] == "OUTLIER":
send_to_quarantine(record, result)
send_alert(result)
else:
log_error(result)
# Or batch processing
batch_results = pipeline.validate_batch(batch_records, batch_id="batch_001")
outliers = pipeline.quarantine_outliers(batch_results["results"])
Key Design Considerations
Schema Design Tips
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"transaction_id": {"type": "string", "pattern": "^[A-Z0-9]{10}$"},
"amount": {"type": "number", "minimum": 0.01, "maximum": 1000000},
"timestamp": {"type": "string", "format": "date-time"},
"user_id": {"type": "string", "minLength": 6}
},
"required": ["transaction_id", "amount", "timestamp", "user_id"],
"additionalProperties": false
}
Feature Engineering for Anomaly Detection
def create_features(record: dict) -> dict:
"""Create features for ML model"""
features = {
"amount": record["amount"],
"hour_sin": np.sin(2 * np.pi * record["hour"]/24),
"hour_cos": np.cos(2 * np.pi * record["hour"]/24),
"day_of_week": record["timestamp"].weekday(),
"location_change": calculate_location_change(record),
"velocity": calculate_velocity(record)
}
return features
Retraining Strategy
class AnomalyDetectorManager:
def __init__(self):
self.detector = MLAnomalyDetector()
self.feedback_log = []
def add_feedback(self, record: dict, is_true_outlier: bool):
"""Collect human feedback for model improvement"""
self.feedback_log.append({
"record": record,
"label": -1 if is_true_outlier else 1 # IsolationForest uses -1 for outliers
})
def periodic_retrain(self, retrain_interval_days: int = 7):
"""Retrain model with new feedback data"""
if len(self.feedback_log) > 1000: # Minimum training samples
training_data = [f["record"] for f in self.feedback_log]
labels = [f["label"] for f in self.feedback_log]
self.detector.train(training_data)
self.feedback_log = [] # Clear after retraining
Monitoring & Alerting
class PipelineMonitor:
def __init__(self, pipeline: DataValidationPipeline):
self.pipeline = pipeline
self.metrics = {
"total_processed": 0,
"validation_rates": {"schema": 0, "policy": 0, "anomaly": 0},
"latency_p50": 0,
"latency_p99": 0
}
def log_metrics(self, result: dict, processing_time_ms: float):
"""Update monitoring metrics"""
self.metrics["total_processed"] += 1
if result["schema_validation"]["valid"]:
self.metrics["validation_rates"]["schema"] += 1
if result["policy_validation"]["valid"]:
self.metrics["validation_rates"]["policy"] += 1
if result["final_status"] == "VALID":
self.metrics["validation_rates"]["anomaly"] += 1
# Update latency metrics (simplified)
# ... implement rolling percentiles
# Alert if anomaly rate spikes
anomaly_rate = (self.metrics["total_processed"] -
self.metrics["validation_rates"]["anomaly"]) / self.metrics["total_processed"]
if anomaly_rate > 0.15: # 15% anomaly threshold
send_alert(f"High anomaly rate detected: {anomaly_rate:.2%}")
Best Practices
- Schema First: Always validate structure before business logic
- Fail Fast: Stop pipeline on critical schema errors unless you have specific recovery logic
- Explainability: Keep detailed error logs with field-level precision
- Model Monitoring: Track false positive/negative rates for anomaly detector
- Feature Store: Maintain versioned feature definitions for reproducibility
- Canary Deployments: Test new policies/models on small data subsets first
- Feedback Loop: Implement human-in-the-loop for outlier verification
- Performance: Cache schema/policy results, batch ML predictions when possible
- Security: Sanitize error messages to avoid information leakage
- Compliance: Maintain audit trail of all validation decisions
Example JSON Schema & Policy
// transaction_schema.json
{
"type": "object",
"properties": {
"transaction_id": {"type": "string", "minLength": 10, "maxLength": 20},
"amount": {"type": "number", "minimum": 0.01, "maximum": 100000},
"currency": {"type": "string", "enum": ["USD", "EUR", "GBP"]},
"timestamp": {"type": "string", "format": "date-time"},
"user_id": {"type": "string", "pattern": "^U[0-9]{8}$"},
"merchant_id": {"type": "string", "minLength": 5}
},
"required": ["transaction_id", "amount", "currency", "timestamp", "user_id"]
}
# Sample policy with context
def velocity_check_policy(record, context):
"""Check transaction velocity (requires stateful context)"""
user_id = record["user_id"]
recent_txns = context.get_recent_transactions(user_id, minutes=1)
if len(recent_txns) >= 10: # More than 10 transactions in 1 minute
return False, f"Velocity check failed: {len(recent_txns)} txns in 1 minute"
return True, ""
This pipeline provides defense-in-depth:
- Schema catches structural issues
- Policies enforce business logic
- ML detects novel anomalies that rules miss
The modular design allows swapping components (e.g., use Protobuf validation instead of JSON Schema, or use autoencoders instead of Isolation Forest).