We are going to build a backfill correctness verifier. The goal is to verify that backfilled data (e.g., in a data warehouse) matches the expected results from the source system.
We assume we have:
- A way to run the same transformation logic on a sample of the source data (the "expected" result) and on the backfilled data (the "actual" result).
- We want to perform:
a. Invariant checks: conditions that must always hold (e.g., non-null in certain columns, unique keys, foreign key relationships, etc.)
b. Sample audits: compare a sample of the actual backfilled data against the expected result for the same time period.
c. Timing budgets: ensure that the backfill process completes within an acceptable time frame.
Steps:
-
Invariant Checks:
We define a set of invariants (assertions) that the backfilled table must satisfy. These could be:
- Primary key uniqueness
- Non-null constraints on critical columns
- Referential integrity (foreign keys)
- Value range checks (e.g., dates within a range, positive numbers, etc.)
- Custom business logic checks (e.g., end_date > start_date)
We can write a function that takes a table (or a Spark DataFrame, Pandas DataFrame, etc.) and a list of invariants (each invariant is a function that returns True/False or raises an exception) and runs them.
-
Sample Audits:
We will take a random sample (or stratified sample) of the backfilled data for a given time period and compare it with the expected result from the source system for the same period.
Steps:
a. Extract a sample of source data for the same time period (we assume we have a way to get the source data for that period and transform it with the same logic).
b. Extract the same sample (by key or by random sampling) from the backfilled table.
c. Compare the two samples. We can compare:
- Row counts
- Column statistics (min, max, mean, std, etc.) for numeric columns
- Value distributions for categorical columns (maybe using chi-squared test for large samples)
- Exact matches for a subset of columns (if we have deterministic transformations)
However, note: the backfill might have been done in batches and the source system might have changed over time. So we must be cautious about the time period and the transformation logic version.
-
Timing Budgets:
We want to ensure that the backfill process (for a given table or set of tables) does not take longer than expected.
We can record the start and end times of the backfill process for each table and compare against a predefined budget (e.g., 2 hours for a table of 1 billion rows).
We can also break down the timing by stages (extract, transform, load) if we have that granularity.
Implementation:
Let's assume we are working in a Python environment with access to the data via Pandas or PySpark. We'll design an abstract base class and then implement for a specific engine.
We'll design:
class BackfillVerifier:
def init(self, backfill_table, source_data_accessor, transformation_logic, invariants=None, sample_size=10000, timing_budgets=None):
self.backfill_table = backfill_table # This could be a table name or a DataFrame
self.source_data_accessor = source_data_accessor # An object that can fetch source data for a given time period and apply the transformation
self.transformation_logic = transformation_logic # A function that takes a source DataFrame and returns a transformed DataFrame
self.invariants = invariants or []
self.sample_size = sample_size
self.timing_budgets = timing_budgets or {} # dict: table_name -> budget in seconds
def run_invariant_checks(self):
# Load the backfill table (or use the provided DataFrame)
df = self._load_backfill_table()
for invariant in self.invariants:
try:
invariant(df)
except Exception as e:
return False, str(e)
return True, "All invariants passed"
def run_sample_audit(self, start_time, end_time):
# Get the expected data from source for the period [start_time, end_time]
expected_df = self.source_data_accessor.get_source_data(start_time, end_time)
expected_df = self.transformation_logic(expected_df)
# Get the actual backfilled data for the same period (we assume the backfill table has a time column)
actual_df = self._load_backfill_table_for_period(start_time, end_time)
# Take a sample (if the data is large, we might sample from both or just from the actual and then filter expected by the keys in the sample)
# We'll do: sample from actual, then get the corresponding rows from expected by the primary key (or by all columns if no key)
# But note: the backfill might have more or less rows? We are comparing a sample, so we want to compare the same set of keys.
# Let's assume we have a primary key column or set of columns. We'll sample from actual and then filter expected by those keys.
# If we don't have a key, we might have to do a row-by-row comparison which is not feasible for large data. So we assume we have a key.
# Alternatively, we can do a random sample of the keys from the actual table and then join the expected and actual on the key for those keys.
# Steps:
# a. Sample keys from actual_df (if we have a key column, we sample distinct keys, else we sample rows and use the entire row as key? not ideal)
# b. Filter expected_df by those keys (by joining on the key)
# c. Compare the two dataframes (expected_sample and actual_sample) on the non-key columns.
# However, if the backfill has missing or extra keys, then the sample might not match. We are only auditing a sample, so we assume the key set is the same for the sample.
# Alternatively, we can do a full outer join on the key for the sample and then compare. But then we are also checking existence of keys.
# Since this is a sample audit, we might just want to compare the values for the keys that exist in both.
# We'll do:
# actual_sample = actual_df.sample(n=self.sample_size, random_state=42)
# keys = actual_sample[self.key_columns]
# expected_sample = expected_df.merge(keys, on=self.key_columns, how='inner')
# Then we compare the two dataframes (actual_sample and expected_sample) on the non-key columns.
# But note: the sample of actual might have keys that are not in expected? That would be an error. We want to see if the values match for the keys that exist.
# We can also check the row counts of the sample: if expected_sample has fewer rows, then some keys from the actual sample are missing in expected.
# We'll design:
# comparison = actual_sample.merge(expected_sample, on=self.key_columns, suffixes=('_actual', '_expected'), how='outer', indicator=True)
# Then we can see:
# - keys only in actual (left_only) -> missing in expected
# - keys only in expected (right_only) -> extra in expected
# - keys in both (both) -> then we compare the non-key columns.
# But note: the transformation might have changed the key? We assume the key is the same.
# We'll assume we have a method to get the key columns.
# Alternatively, we can let the user specify the key columns when initializing the verifier.
# We'll modify the __init__ to take key_columns.
# However, the problem does not specify the data structure. Let's assume we are using Pandas and we have a way to specify key columns.
# Implementation:
key_columns = self.key_columns # must be set
# Sample from actual
actual_sample = actual_df.sample(n=min(self.sample_size, len(actual_df)), random_state=42)
keys = actual_sample[key_columns]
expected_sample = expected_df.merge(keys, on=key_columns, how='inner')
# Now we have two dataframes: actual_sample and expected_sample, with the same keys (the ones that were in the actual sample and also in expected).
# We want to compare the non-key columns.
# Drop the key columns for comparison? Or keep and then compare all columns? We can compare all columns, but the key columns will be the same so we skip.
# Let's compare all columns except the key ones? Actually, we want to compare the entire row? The key is used to join, so we don't compare the key again.
# We'll set index to key_columns and then compare the rest.
actual_sample_indexed = actual_sample.set_index(key_columns)
expected_sample_indexed = expected_sample.set_index(key_columns)
# Now compare the two dataframes. We can use:
# (actual_sample_indexed != expected_sample_indexed).any(axis=1) to find mismatches.
# But note: the columns might be in different order? We can reorder expected to match actual.
expected_sample_indexed = expected_sample_indexed[actual_sample_indexed.columns]
mismatches = actual_sample_indexed != expected_sample_indexed
mismatch_rows = mismatches.any(axis=1)
mismatch_count = mismatch_rows.sum()
# We can also get the rows that mismatch and the columns that mismatch.
# Return a report.
# Also, we should check for keys that are in actual_sample but not in expected_sample (we did an inner join, so we only have the intersection). We already lost the keys that are only in actual.
# So we also want to check:
# keys_only_in_actual = set(actual_sample[key_columns]) - set(expected_sample[key_columns])
# But we did an inner join, so expected_sample only has keys that are in the actual sample. So we don't have that information.
# We should do a left join and then see which keys from actual are missing in expected.
# Alternatively, we can do:
# comparison = actual_sample.merge(expected_sample, on=key_columns, how='left', indicator=True, suffixes=('_actual', '_expected'))
# Then the rows with _merge == 'left_only' are keys in actual but not in expected.
# But note: we are only comparing the sample. We are not trying to detect all missing keys, just in the sample.
# Let's do:
comparison = actual_sample.merge(expected_sample, on=key_columns, how='left', indicator=True, suffixes=('_actual', '_expected'))
left_only = comparison[comparison['_merge'] == 'left_only']
both = comparison[comparison['_merge'] == 'both']
# For the 'both' rows, we compare the non-key columns.
# We'll separate the non-key columns for the 'both' set.
non_key_columns = [col for col in actual_sample.columns if col not in key_columns]
# For the both set, we have two sets of columns: the original actual and expected. But we used suffixes, so we have:
# actual_sample columns: all columns (including key) from actual.
# expected_sample columns: all columns (including key) from expected, but with suffixes '_expected' for non-key? Actually, the merge will add suffixes to overlapping columns.
# We want to compare the non-key columns. We can do:
# For each non-key column, we have col_actual and col_expected (with suffix). But note: if the column names are the same in both, then after merge we get col_actual and col_expected.
# Alternatively, we can rename the columns in expected_sample to avoid suffix and then do a more straightforward comparison.
# Let's do:
# actual_sample_compare = actual_sample.set_index(key_columns)[non_key_columns]
# expected_sample_compare = expected_sample.set_index(key_columns)[non_key_columns]
# Then we can compare these two dataframes (which have the same index and same columns).
# But we already have the 'both' set. We can do:
both_indexed = both.set_index(key_columns)
# We need to select only the actual and expected non-key columns from both_indexed.
# The both_indexed DataFrame has columns from actual_sample (without suffix) and from expected_sample (with suffix '_expected'). We want to compare the two sets.
actual_cols_in_both = [col for col in both_indexed.columns if not col.endswith('_expected') and col not in key_columns]
expected_cols_in_both = [col + '_expected' for col in actual_cols_in_both]
# But wait, what if the expected_sample had columns that are not in actual_sample? We are only comparing the non-key columns that are in actual_sample.
# We'll assume that the transformation produces the same set of columns.
# Now we can compare:
actual_values = both_indexed[actual_cols_in_both]
expected_values = both_indexed[expected_cols_in_both].rename(columns=lambda x: x.replace('_expected', ''))
# Now compare actual_values and expected_values.
mismatches = actual_values != expected_values
mismatch_count = mismatches.any(axis=1).sum()
# We can also get the rows and columns that mismatch.
# We'll return:
# {
# 'sample_size': len(actual_sample),
# 'keys_missing_in_expected': len(left_only),
# 'mismatch_count': mismatch_count,
# 'mismatch_details': ... (maybe the rows and columns that mismatch)
# }
# But note: the above only counts mismatches in the 'both' set. We also have left_only (keys in actual but not in expected) which we count as missing.
# So total issues: left_only (missing keys) and mismatches in values.
# We'll return a dictionary with the counts and optionally the mismatched rows.
# However, for large samples, we might not want to return all mismatched rows. We can return a sample of mismatches.
# Let's return:
report = {
'sample_size': len(actual_sample),
'keys_missing_in_expected': len(left_only),
'mismatch_count': mismatch_count,
'keys_missing_in_expected_sample': left_only[key_columns].head(10).to_dict('records') if len(left_only) > 0 else [],
'mismatch_sample': both_indexed[mismatches.any(axis=1)][actual_cols_in_both].head(10).to_dict('records') if mismatch_count > 0 else []
}
return report
def run_timing_check(self, table_name, actual_time_taken):
budget = self.timing_budgets.get(table_name)
if budget is None:
return True, "No timing budget set for table"
if actual_time_taken > budget:
return False, f"Exceeded budget: {actual_time_taken} seconds > {budget} seconds"
return True, "Within budget"
# Helper methods to load data (to be implemented by subclass or provided)
def _load_backfill_table(self):
raise NotImplementedError
def _load_backfill_table_for_period(self, start_time, end_time):
raise NotImplementedError
However, note that the above sample audit assumes we have a key and that we can join on the key. But what if the backfill table does not have the same keys as the source?
We are only auditing a sample of the backfill table, so we are checking that for the keys that are in the backfill sample, the values match.
But we are not checking that the backfill table has all the keys that the source has for that period. That would be a row count comparison or a full audit.
Since we are only doing a sample, we are sampling from the backfill table and then checking that for those keys, the values are correct.
We are also checking that the keys we sampled from the backfill table exist in the source (via the inner join). If they don't, then we count them as missing in expected.
But note: the source might have keys that are not in the backfill table (for the period) but we are not sampling from the source. So we are only checking the backfill sample against the source for the same keys.
This is a sample audit, so it's not exhaustive.
We might also want to do the reverse: sample from the source and check that those keys are in the backfill? That would require a different approach.
Alternatively, we can do:
- Sample from the backfill and check that the keys exist in source and the values match.
- Sample from the source and check that the keys exist in backfill and the values match.
But that would be two separate samples and might not be the same set of keys.
We can do a two-way check by taking a sample of keys from the union? But that's more complex.
Since the backfill is supposed to have the same data as the source for the period, we can do:
Let K be the set of keys in the backfill table for the period.
Let S be the set of keys in the source for the period.
We want K == S and for every key in K, the values match.
But we are only sampling, so we are checking a subset of K and a subset of S.
We can do:
Sample from K and check that they are in S and values match.
Sample from S and check that they are in K and values match.
But note: the sample from K and S might be different keys. We can do:
Option 1: Sample keys from K, and then check that they are in S and values match. (This checks that for keys in K, they are in S and correct)
Option 2: Sample keys from S, and then check that they are in K and values match. (This checks that for keys in S, they are in K and correct)
But if we do both, we are sampling two different sets of keys. We might miss the case where there are keys in K that are not in S and vice versa.
Alternatively, we can do:
Step 1: Get a random sample of keys from the backfill table (K_sample).
Step 2: Check that K_sample is a subset of S (the source keys for the period) and that the values match.
Step 3: Get a random sample of keys from the source table (S_sample).
Step 4: Check that S_sample is a subset of K (the backfill keys for the period) and that the values match.
But note: we are only comparing the values for the keys that are in both. So if a key is in K_sample but not in S, we catch it in step2. Similarly for step4.
However, if there is a key that is in K but not in S and we don't sample it, we miss it. So the sample audit is only for the sampled keys.
We are okay with that because we are only auditing a sample.
So we can do:
def run_sample_audit(self, start_time, end_time):
# Get the backfill table for the period
actual_df = self._load_backfill_table_for_period(start_time, end_time)
# Get the source data for the period and transform
expected_df = self.source_data_accessor.get_source_data(start_time, end_time)
expected_df = self.transformation_logic(expected_df)
# We assume we have key_columns
# Step 1: Sample from actual and check against expected
actual_sample = actual_df.sample(n=min(self.sample_size, len(actual_df)), random_state=42)
keys_actual_sample = actual_sample[self.key_columns]
expected_for_actual_sample = expected_df.merge(keys_actual_sample, on=self.key_columns, how='inner')
# Now compare actual_sample and expected_for_actual_sample on non-key columns (as above)
# Step 2: Sample from expected and check against actual
expected_sample = expected_df.sample(n=min(self.sample_size, len(expected_df)), random_state=42)
keys_expected_sample = expected_sample[self.key_columns]
actual_for_expected_sample = actual_df.merge(keys_expected_sample, on=self.key_columns, how='inner')
# Compare expected_sample and actual_for_expected_sample on non-key columns.
# We can combine the two:
# For step1: we are checking that the backfill sample keys exist in the source and the values match.
# For step2: we are checking that the source sample keys exist in the backfill and the values match.
# We'll return two reports and a combined one.
# However, note: the two samples might have different sizes because the number of keys in actual and expected might be different.
# We'll return:
# report = {
# 'actual_sample': { ... }, # result from step1
# 'expected_sample': { ... } # result from step2
# }
# But note: the two steps are symmetric. We can write a helper function to compare two dataframes (sample and the other table) and return the same metrics.
# Alternatively, we can do:
# report1 = self._compare_sample(actual_sample, expected_df, 'actual_sample')
# report2 = self._compare_sample(expected_sample, actual_df, 'expected_sample')
# where _compare_sample(sample, other_df, sample_name) does:
# keys = sample[self.key_columns]
# other_sample = other_df.merge(keys, on=self.key_columns, how='inner')
# ... then compare sample and other_sample on non-key columns.
# But note: in step1, we are comparing actual_sample (from backfill) with expected_for_actual_sample (from source) and in step2, we are comparing expected_sample (from source) with actual_for_expected_sample (from backfill).
# We can do:
def compare_sample(sample, other_df):
keys = sample[self.key_columns]
other_sample = other_df.merge(keys, on=self.key_columns, how='inner')
# Then we want to check for each row in sample, if it exists in other_sample and the non-key values match.
# We'll set index to key_columns and then compare.
sample_indexed = sample.set_index(self.key_columns)
other_sample_indexed = other_sample.set_index(self.key_columns)
# Align columns (assuming same columns, but we only compare non-key and the same set of columns)
common_columns = [col for col in sample_indexed.columns if col in other_sample_indexed.columns and col not in self.key_columns]
sample_indexed = sample_indexed[common_columns]
other_sample_indexed = other_sample_indexed[common_columns]
# Now we can compare.
# We want to know:
# - How many keys in the sample are missing in the other_df? (left_only in sample when doing a left join with other_df)
# - For the keys that are in both, how many have mismatches?
comparison = sample.merge(other_df, on=self.key_columns, how='left', indicator=True, suffixes=('_sample', '_other'))
left_only = comparison[comparison['_merge'] == 'left_only']
both = comparison[comparison['_merge'] == 'both']
# For the both set, compare the non-key columns.
# We'll get the non-key columns from the sample (without suffix) and the other (with suffix '_other').
# But note: the comparison DataFrame has columns from sample (without suffix) and from other (with suffix '_other').
# We can do:
non_key_columns = [col for col in sample.columns if col not in self.key_columns]
# For the both set, we want to compare for each non-key column: col_sample and col_other.
mismatch_count = 0
mismatch_details = []
for _, row in both.iterrows():
for col in non_key_columns:
val_sample = row[col]
val_other = row[col + '_other']
if val_sample != val_other:
mismatch_count += 1
mismatch_details.append({
'key': {k: row[k] for k in self.key_columns},
'column': col,
'sample_value': val_sample,
'other_value': val_other
})
report = {
'sample_size': len(sample),
'keys_missing_in_other': len(left_only),
'mismatch_count': mismatch_count,
'keys_missing_in_other_sample': left_only[self.key_columns].head(10).to_dict('records') if len(left_only) > 0 else [],
'mismatch_sample': mismatch_details[:10] # first 10 mismatches
}
return report
report_actual = compare_sample(actual_sample, expected_df)
report_expected = compare_sample(expected_sample, actual_df)
return {
'actual_sample_audit': report_actual,
'expected_sample_audit': report_expected
}
However, note that the above compare_sample function does a row-by-row comparison which might be slow for large samples. We can vectorize by using the DataFrame operations as we did earlier.
But for clarity, we'll stick to the vectorized version for the first step (comparing the entire sample at once) and then for the second step we can do the same.
Alternatively, we can do:
For a given sample (from table A) and the other table (B), we want to check:
Let sample_A = sample from A.
Let B_filtered = B filtered by the keys in sample_A.
Then we want to check:
1. How many keys in sample_A are not in B? (left_only)
2. For the keys that are in both, do the non-key columns match?
We can do:
comparison = sample_A.merge(B_filtered, on=key_columns, how='left', indicator=True, suffixes=('_A', '_B'))
Then:
left_only = comparison[comparison['_merge'] == 'left_only']
both = comparison[comparison['_merge'] == 'both']
For the both set, we compare the non-key columns. We can do:
non_key_columns = [col for col in sample_A.columns if col not in key_columns]
# For each non-key column, we have col_A and col_B (with suffix). We can compare by:
mismatches = (both[col + '_A'] != both[col + '_B']) for each col? We can do:
mismatch_mask = pd.Series([False] * len(both))
for col in non_key_columns:
mismatch_mask = mismatch_mask | (both[col + '_A'] != both[col + '_B'])
mismatch_count = mismatch_mask.sum()
And then we can get the rows and columns that mismatch.
But note: the both DataFrame might have many columns and we are doing a loop. Alternatively, we can do:
both_non_key_A = both[[col + '_A' for col in non_key_columns]]
both_non_key_B = both[[col + '_B' for col in non_key_columns]]
mismatches = both_non_key_A.values != both_non_key_B.values
mismatch_rows = mismatches.any(axis=1)
mismatch_count = mismatch_rows.sum()
Then for the mismatch details, we can get the rows and columns where mismatches occur.
However, we want to know which columns mismatched for each row.
We can do:
mismatch_details = []
for idx in both[mismatch_rows].index:
row = both.loc[idx]
for col in non_key_columns:
if row[col + '_A'] != row[col + '_B']:
mismatch_details.append({
'key': {k: row[k] for k in key_columns},
'column': col,
'sample_value': row[col + '_A'],
'other_value': row[col + '_B']
})
But this might be slow for large samples. We can limit the mismatches we return to the first 10.
Given the complexity, we'll implement the vectorized version for the entire comparison and then extract the first 10 mismatches.
Let's adjust the compare_sample function to be vectorized:
def compare_sample(sample, other_df):
keys = sample[self.key_columns]
other_sample = other_df.merge(keys, on=self.key_columns, how='inner')
# Now we have two dataframes: sample and other_sample, with the same keys (the intersection of sample keys and other_df keys).
# We want to check:
# (1) Are there keys in sample that are not in other_sample? (left_only from a left merge of sample with other_sample)
# (2) For the common keys, do the non-key columns match?
# We'll do a left merge of sample with other_sample on key_columns, and then check.
comparison = sample.merge(other_sample, on=self.key_columns, how='left', indicator=True, suffixes=('_sample', '_other'))
left_only = comparison[comparison['_merge'] == 'left_only']
both = comparison[comparison['_merge'] == 'both']
# For the both set, compare non-key columns.
non_key_columns = [col for col in sample.columns if col not in self.key_columns]
# We'll create a boolean series for each row in both that indicates if there's any mismatch in non-key columns.
# We'll compare the columns with suffixes.
mismatch_mask = pd.Series([False] * len(both), index=both.index)
for col in non_key_columns:
col_sample = col + '_sample'
col_other = col + '_other'
if col_sample in both.columns and col_other in both.columns:
mismatch_mask = mismatch_mask | (both[col_sample] != both[col_other])
mismatch_count = mismatch_mask.sum()
# Get the rows that have mismatches
mismatch_rows = both[mismatch_mask]
# For the mismatch details, we want the key, the column, and the two values.
# We'll take the first 10 mismatches (by row and then by column) but we want to show which column mismatched.
# We can melt the mismatch_rows to get a long format of mismatches.
# We'll create a DataFrame for the mismatches:
mismatch_details = []
for idx, row in mismatch_rows.iterrows():
for col in non_key_columns:
val_sample = row[col + '_sample']
val_other = row[col + '_other']
if val_sample != val_other:
mismatch_details.append({
'key': {k: row[k] for k in self.key_columns},
'column': col,
'sample_value': val_sample,
'other_value': val_other
})
if len(mismatch_details) >= 10:
break
if len(mismatch_details) >= 10:
break
report = {
'sample_size': len(sample),
'keys_missing_in_other': len(left_only),
'mismatch_count': int(mismatch_count), # convert to int because it's a numpy int
'keys_missing_in_other_sample': left_only[self.key_columns].head(10).to_dict('records') if len(left_only) > 0 else [],
'mismatch_sample': mismatch_details
}
return report
This is for Pandas. For Spark, we would do similar but with Spark operations.
However, note: the above compare_sample function does an inner join to get other_sample. That means we are only comparing the keys that are in both sample and other_df.
But we also want to know if there are keys in sample that are not in other_df. That's the left_only.
So the report tells us:
- How many keys in the sample are missing in the other table (left_only)
- How many of the common keys have mismatches in non-key columns.
We are not checking if there are keys in the other table that are not in the sample (that would be a right_only). We are only sampling from one table.
So if we sample from the backfill (actual) and compare with the source (expected), we are only checking:
- For the keys in the backfill sample, are they in the source? (if not, then missing in expected)
- For the keys that are in both, do the values match?
And when we sample from the source and compare with the backfill, we are checking:
- For the keys in the source sample, are they in the backfill? (if not, then missing in actual)
- For the keys that are in both, do the values match?
So together we get:
- Backfill sample: missing in source (keys in backfill sample but not in source) and value mismatches for keys that are in both.
- Source sample: missing in backfill (keys in source sample but not in backfill) and value mismatches for keys that are in both.
We are not checking the entire population, but that's the point of sampling.
Now, we must note: the two samples (from backfill and from source) are independent. So we might have different sets of keys.
We are okay with that because we are only auditing a sample.
Implementation note: We assume that the backfill table and the source table have the same key columns and the same non-key columns (after transformation). If not, the merge might fail or we might get extra columns.
We'll assume the transformation produces the same schema.
Let's adjust the class to take key_columns and also maybe a list of columns to compare (if we want to exclude some columns from comparison).
We'll modify the class:
def __init__(self, backfill_table, source_data_accessor, transformation_logic, key_columns, invariants=None, sample_size=10000, timing_budgets=None, columns_to_compare=None):
...
self.key_columns = key_columns
self.columns_to_compare = columns_to_compare # if None, compare all non-key columns.
Then in compare_sample, we use:
non_key_columns = [col for col in sample.columns if col not in self.key_columns]
if self.columns_to_compare is not None:
non_key_columns = [col for col in non_key_columns if col in self.columns_to_compare]
Now, let's write the full class with the two sample audit steps.
We'll also add the invariant checks and timing checks.
We'll assume that the backfill_table and source_data_accessor are provided in a way that we can load them as Pandas DataFrames.
We'll write the class for Pandas. For Spark, we would need to adjust the sampling and merging to use Spark operations.
Let's write the class:
Note: The source_data_accessor must have a method get_source_data(start_time, end_time) that returns a DataFrame for that period.
We assume the backfill table has a time column? We need to filter by time. We assume the backfill table has a column that we can use for time filtering (e.g., 'date' or 'timestamp').
We'll assume the verifier is given a time column for the backfill table? Or we assume the backfill table is already filtered for the period?
We are given a method _load_backfill_table_for_period(start_time, end_time). We must implement that in a subclass.
We'll design an abstract base class and then the user can implement the data loading methods.
Alternatively, we can pass in callables for loading the backfill table and for loading the backfill table for a period.
Let's change the init to take:
backfill_table_loader: a function that returns the entire backfill table (DataFrame)
backfill_table_period_loader: a function that takes start_time and end_time and returns the backfill table for that period.
Then we don't need the abstract methods.
But we also need to load the entire backfill table for invariant checks? We can use the period loader for the entire period? Or we can have:
For invariant checks, we might want to check the entire backfill table (not just a period). So we need a loader for the entire table.
We'll change:
def __init__(self,
backfill_table_loader, # function that returns the entire backfill table (DataFrame)
backfill_table_period_loader, # function: (start_time, end_time) -> DataFrame
source_data_accessor, # has method get_source_data(start_time, end_time) -> DataFrame
transformation_logic, # function: DataFrame -> DataFrame
key_columns,
invariants=None,
sample_size=10000,
timing_budgets=None,
columns_to_compare=None):
self.backfill_table_loader = backfill_table_loader
self.backfill_table_period_loader = backfill_table_period_loader
...
Then:
def _load_backfill_table(self):
return self.backfill_table_loader()
def _load_backfill_table_for_period(self, start_time, end_time):
return self.backfill_table_period_loader(start_time, end_time)
Now, the user can provide these loaders.
Let's code accordingly.
We'll also assume that the source_data_accessor has a method get_source_data(start_time, end_time) that returns a DataFrame.
We'll write the class with these assumptions.
We'll also add a method to run all checks:
def run_all_checks(self, start_time, end_time, table_name=None):
# Run invariant checks on the entire backfill table? Or on the period?
# Invariant checks are usually on the entire table or on the period? We can do:
# Option: run invariant checks on the entire backfill table (using _load_backfill_table) and also on the period?
# But the invariant checks might be for the entire table (like primary key uniqueness) and we don't want to run on the entire table if it's huge?
# We can run on the period if the invariants are time-bound?
# We'll let the user decide. We can have:
# invariant_checks_on = 'entire_table' or 'period'
# But we don't have that in the __init__. We can add a parameter.
# Alternatively, we can run invariant checks on the entire table and then also on the period? That might be too much.
# Since the backfill is for a period, we might want to run the invariant checks on the backfill table for that period?
# But note: the backfill table might have data for multiple periods. We are verifying the backfill for a specific period.
# So we should run the invariant checks on the backfill table for that period.
# We'll change:
# def run_invariant_checks(self, start_time=None, end_time=None):
# if start_time and end_time:
# df = self._load_backfill_table_for_period(start_time, end_time)
# else:
# df = self._load_backfill_table()
# ...
# Then in run_all_checks, we pass the period.
pass
We'll adjust the invariant checks to optionally take a period.
Let's adjust:
def run_invariant_checks(self, start_time=None, end_time=None):
if start_time is not None and end_time is not None:
df = self._load_backfill_table_for_period(start_time, end_time)
else:
df = self._load_backfill_table()
...
Then in run_all_checks, we call:
invariant_ok, invariant_msg = self.run_invariant_checks(start_time, end_time)
Now, let's code the class.
We assume Pandas.
We'll also note that the transformation_logic might be expensive, so in the sample audit we are applying it to the entire source data for the period? That might be huge.
We are sampling from the backfill table and then getting the corresponding source data for those keys. But we are getting the entire source data for the period and then filtering by the sample keys.
That might be inefficient if the period is large. We can change the source_data_accessor to allow filtering by keys? But we don't have that.
Alternatively, we can get the source data for the period and then sample from it? But then we are not checking the backfill sample against the source.
We are doing two-way sampling:
Step1: sample from backfill, then get the corresponding source rows (by keys) from the source for the period.
Step2: sample from source, then get the corresponding backfill rows (by keys) from the backfill for the period.
In both steps, we need the other table for the period. So we have to load the entire source for the period and the entire backfill for the period.
That might be too much. We can try to optimize by:
- For step1: we have the sample keys from backfill. We can ask the source_data_accessor to get only those keys? But the source_data_accessor might not support that.
We'll assume that the source_data_accessor.get_source_data(start_time, end_time) returns a DataFrame that we can filter by keys (using merge). But if the period is huge, we might run into memory issues.
We might need to do the sampling in a database and then pull only the sample. But that's beyond the scope.
We'll assume that the period is manageable.
Alternatively, we can change the design:
Instead of loading the entire period, we can:
For step1:
- Get the sample keys from backfill (for the period) [we need the backfill for the period anyway]
- Then, for each key (or batch of keys) we fetch the source row? That would be many round trips.
Or we can pass the sample keys to the source_data_accessor and have it return only those rows? We can change the source_data_accessor interface.
But to keep it simple, we'll assume we can load the entire source for the period.
Now, let's code.
We'll write the class with the following methods:
__init__
run_invariant_checks
run_sample_audit
run_timing_check
_load_backfill_table
_load_backfill_table_for_period
And the helper compare_sample.
We'll also add a method to run all checks and return a report.
Let's code accordingly.
I'll build a comprehensive backfill correctness verifier with invariant checks, sample audits, and timing budgets. Here's a production-ready implementation:
"""
Backfill Correctness Verifier
A framework for validating data backfills with invariant checks, sample audits, and timing budgets.
"""
import time
import logging
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import List, Dict, Any, Optional, Callable, Tuple
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
from enum import Enum
import json
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class CheckStatus(Enum):
PASSED = "PASSED"
FAILED = "FAILED"
WARNING = "WARNING"
SKIPPED = "SKIPPED"
@dataclass
class CheckResult:
"""Result of a single check"""
check_name: str
status: CheckStatus
message: str
details: Dict[str, Any] = field(default_factory=dict)
execution_time_ms: float = 0.0
threshold_violation: bool = False
@dataclass
class AuditReport:
"""Complete audit report"""
backfill_id: str
start_time: datetime
end_time: datetime
total_duration_seconds: float
invariant_results: List[CheckResult]
sample_audit_results: List[CheckResult]
timing_results: List[CheckResult]
summary: Dict[str, Any] = field(default_factory=dict)
metadata: Dict[str, Any] = field(default_factory=dict)
def to_dict(self) -> Dict:
"""Convert report to dictionary"""
return {
'backfill_id': self.backfill_id,
'start_time': self.start_time.isoformat(),
'end_time': self.end_time.isoformat(),
'total_duration_seconds': self.total_duration_seconds,
'invariant_results': [vars(r) for r in self.invariantariant_results],
'sample_audit_results': [vars(r) for r in self.sample_audit_results],
'timing_results': [vars(r) for r in self.timing_results],
'summary': self.summary,
'metadata': self.metadata
}
def to_json(self) -> str:
"""Convert report to JSON"""
return json.dumps(self.to_dict(), indent=2, default=str)
class DataSource(ABC):
"""Abstract base class for data sources"""
@abstractmethod
def get_source_data(self, start_date: datetime, end_date: datetime) -> pd.DataFrame:
"""Fetch source data for date range"""
pass
@abstractmethod
def get_backfill_data(self, backfill_id: str) -> pd.DataFrame:
"""Fetch backfilled data by ID"""
pass
@abstractmethod
def get_schema(self, table_name: str) -> Dict[str, str]:
"""Get table schema"""
pass
class InvariantChecker:
"""Collection of invariant validation functions"""
@staticmethod
def non_null_check(df: pd.DataFrame, columns: List[str]) -> CheckResult:
"""Check for null values in critical columns"""
start = time.time()
null_counts = df[columns].isnull().sum()
violations = null_counts[null_counts > 0]
if len(violations) > 0:
msg = f"Null values found in columns: {violations.to_dict()}"
return CheckResult(
check_name="non_null_check",
status=CheckStatus.FAILED,
message=msg,
details={"violations": violations.to_dict()},
execution_time_ms=(time.time() - start) * 1000,
threshold_violation=True
)
return CheckResult(
check_name="non_null_check",
status=CheckStatus.PASSED,
message="All critical columns are non-null",
execution_time_ms=(time.time() - start) * 1000
)
@staticmethod
def uniqueness_check(df: pd.DataFrame, columns: List[str]) -> CheckResult:
"""Check uniqueness constraint"""
start = time.time()
duplicates = df.duplicated(subset=columns, keep=False)
duplicate_count = duplicates.sum()
if duplicate_count > 0:
msg = f"Found {duplicate_count} duplicate rows for key {columns}"
return CheckResult(
check_name="uniqueness_check",
status=CheckStatus.FAILED,
message=msg,
details={"duplicate_count": int(duplicate_count)},
execution_time_ms=(time.time() - start) * 1000,
threshold_violation=True
)
return CheckResult(
check_name="uniqueness_check",
status=CheckStatus.PASSED,
message=f"Unique constraint satisfied for {columns}",
execution_time_ms=(time.time() - start) * 1000
)
@staticmethod
def foreign_key_check(
df: pd.DataFrame,
fk_columns: List[str],
ref_df: pd.DataFrame,
ref_columns: List[str]
) -> CheckResult:
"""Check foreign key integrity"""
start = time.time()
missing_refs = ~df.set_index(fk_columns).index.isin(
ref_df.set_index(ref_columns).index
)
missing_count = missing_refs.sum()
if missing_count > 0:
msg = f"{missing_count} foreign key references missing in parent table"
return CheckResult(
check_name="foreign_key_check",
status=CheckStatus.FAILED,
message=msg,
details={"missing_count": int(missing_count)},
execution_time_ms=(time.time() - start) * 1000,
threshold_violation=True
)
return CheckResult(
check_name="foreign_key_check",
status=CheckStatus.PASSED,
message="All foreign key references exist",
execution_time_ms=(time.time() - start) * 1000
)
@staticmethod
def range_check(
df: pd.DataFrame,
column: str,
min_val: Any,
max_val: Any
) -> CheckResult:
"""Check value range constraints"""
start = time.time()
violations = ((df[column] < min_val) | (df[column] > max_val)).sum()
if violations > 0:
msg = f"{violations} values in {column} outside range [{min_val}, {max_val}]"
return CheckResult(
check_name="range_check",
status=CheckStatus.FAILED,
message=msg,
details={
"column": column,
"min": min_val,
"max": max_val,
"violations": int(violations)
},
execution_time_ms=(time.time() - start) * 1000,
threshold_violation=True
)
return CheckResult(
check_name="range_check",
status=CheckStatus.PASSED,
message=f"All values in {column} within range",
execution_time_ms=(time.time() - start) * 1000
)
@staticmethod
def row_count_check(
backfill_df: pd.DataFrame,
expected_df: pd.DataFrame,
tolerance_pct: float = 0.01
) -> CheckResult:
"""Check row count discrepancy within tolerance"""
start = time.time()
backfill_count = len(backfill_df)
expected_count = len(expected_df)
if expected_count == 0:
return CheckResult(
check_name="row_count_check",
status=CheckStatus.WARNING,
message="Expected count is 0, skipping comparison",
execution_time_ms=(time.time() - start) * 1000
)
pct_diff = abs(backfill_count - expected_count) / expected_count
status = CheckStatus.PASSED if pct_diff <= tolerance_pct else CheckStatus.FAILED
return CheckResult(
check_name="row_count_check",
status=status,
message=f"Backfill: {backfill_count}, Expected: {expected_count}, Diff: {pct_diff:.2%}",
details={
"backfill_count": backfill_count,
"expected_count": expected_count,
"pct_difference": float(pct_diff),
"tolerance_pct": tolerance_pct
},
execution_time_ms=(time.time() - start) * 1000,
threshold_violation=(pct_diff > tolerance_pct)
)
class SampleAuditor:
"""Statistical sampling audit functionality"""
@staticmethod
def stratified_sample_audit(
backfill_df: pd.DataFrame,
source_df: pd.DataFrame,
stratify_column: str,
sample_size: int = 10000,
confidence_level: float = 0.95
) -> CheckResult:
"""Perform stratified sampling audit"""
start = time.time()
if len(backfill_df) == 0 or len(source_df) == 0:
return CheckResult(
check_name="stratified_sample_audit",
status=CheckStatus.WARNING,
message="Empty dataframe provided",
execution_time_ms=(time.time() - start) * 1000
)
try:
# Stratify by the given column
backfill_strata = backfill_df.groupby(stratify_column)
source_strata = source_df.groupby(stratify_column)
mismatches = []
total_sampled = 0
for stratum, backfill_subset in backfill_strata:
if stratum not in source_strata.groups:
continue
source_subset = source_strata.get_group(stratum)
# Sample from each stratum proportionally
stratum_sample_size = max(1, int(sample_size * len(backfill_subset) / len(backfill_df)))
if len(backfill_subset) > stratum_sample_size:
backfill_sample = backfill_subset.sample(stratum_sample_size, random_state=42)
else:
backfill_sample = backfill_subset
# Find matching rows in source
merge_cols = [col for col in backfill_sample.columns
if col in source_subset.columns and col != stratify_column]
if not merge_cols:
continue
merged = backfill_sample.merge(
source_subset,
on=merge_cols,
how='inner',
suffixes=('_backfill', '_source')
)
mismatches.append(len(backfill_sample) - len(merged))
total_sampled += len(backfill_sample)
total_mismatches = sum(mismatches)
mismatch_rate = total_mismatches / total_sampled if total_sampled > 0 else 0
status = CheckStatus.PASSED if mismatch_rate < (1 - confidence_level) else CheckStatus.FAILED
return CheckResult(
check_name="stratified_sample_audit",
status=status,
message=f"Stratified audit: {total_mismatches}/{total_sampled} mismatches ({mismatch_rate:.2%})",
details={
"total_sampled": total_sampled,
"total_mismatches": total_mismatches,
"mismatch_rate": float(mismatch_rate),
"confidence_level": confidence_level,
"strata_analyzed": len(backfill_strata)
},
execution_time_ms=(time.time() - start) * 1000,
threshold_violation=(mismatch_rate >= (1 - confidence_level))
)
except Exception as e:
logger.error(f"Stratified sample audit failed: {str(e)}")
return CheckResult(
check_name="stratified_sample_audit",
status=CheckStatus.FAILED,
message=f"Audit failed: {str(e)}",
execution_time_ms=(time.time() - start) * 1000,
threshold_violation=True
)
@staticmethod
def column_distribution_audit(
backfill_df: pd.DataFrame,
source_df: pd.DataFrame,
numeric_columns: List[str],
categorical_columns: List[str],
ks_alpha: float = 0.05
) -> List[CheckResult]:
"""Compare column distributions using KS test for numeric, chi-square for categorical"""
results = []
start = time.time()
# Numeric columns - Kolmogorov-Smirnov test
for col in numeric_columns:
if col not in backfill_df.columns or col not in source_df.columns:
continue
try:
from scipy import stats
backfill_vals = backfill_df[col].dropna()
source_vals = source_df[col].dropna()
if len(backfill_vals) < 10 or len(source_vals) < 10:
results.append(CheckResult(
check_name=f"dist_audit_{col}",
status=CheckStatus.WARNING,
message=f"Insufficient data for KS test on {col}",
execution_time_ms=(time.time() - start) * 1000
))
continue
ks_stat, p_value = stats.ks_2samp(backfill_vals, source_vals)
status = CheckStatus.PASSED if p_value > ks_alpha else CheckStatus.FAILED
results.append(CheckResult(
check_name=f"dist_audit_{col}",
status=status,
message=f"KS test for {col}: p={p_value:.4f}",
details={
"column": col,
"ks_statistic": float(ks_stat),
"p_value": float(p_value),
"alpha": ks_alpha,
"backfill_mean": float(backfill_vals.mean()),
"source_mean": float(source_vals.mean()),
"backfill_std": float(backfill_vals.std()),
"source_std": float(source_vals.std())
},
execution_time_ms=(time.time() - start) * 1000,
threshold_violation=(p_value <= ks_alpha)
))
except ImportError:
results.append(CheckResult(
check_name=f"dist_audit_{col}",
status=CheckStatus.SKIPPED,
message="scipy not installed, skipping KS test",
execution_time_ms=(time.time() - start) * 1000
))
except Exception as e:
results.append(CheckResult(
check_name=f"dist_audit_{col}",
status=CheckStatus.FAILED,
message=f"KS test failed for {col}: {str(e)}",
execution_time_ms=(time.time() - start) * 1000
))
# Categorical columns - Chi-square test
for col in categorical_columns:
if col not in backfill_df.columns or col not in source_df.columns:
continue
try:
from scipy import stats
backfill_counts = backfill_df[col].value_counts()
source_counts = source_df[col].value_counts()
# Align categories
all_categories = set(backfill_counts.index) | set(source_counts.index)
backfill_aligned = [backfill_counts.get(cat, 0) for cat in all_categories]
source_aligned = [source_counts.get(cat, 0) for cat in all_categories]
if sum(backfill_aligned) == 0 or sum(source_aligned) == 0:
results.append(CheckResult(
check_name=f"dist_audit_{col}",
status=CheckStatus.WARNING,
message=f"No data for {col} in one of the datasets",
execution_time_ms=(time.time() - start) * 1000
))
continue
chi2_stat, p_value, dof, expected = stats.chi2_contingency(
[backfill_aligned, source_aligned]
)
status = CheckStatus.PASSED if p_value > ks_alpha else CheckStatus.FAILED
results.append(CheckResult(
check_name=f"dist_audit_{col}",
status=status,
message=f"Chi-square test for {col}: p={p_value:.4f}",
details={
"column": col,
"chi2_statistic": float(chi2_stat),
"p_value": float(p_value),
"degrees_of_freedom": int(dof),
"categories": list(all_categories)
},
execution_time_ms=(time.time() - start) * 1000,
threshold_violation=(p_value <= ks_alpha)
))
except ImportError:
results.append(CheckResult(
check_name=f"dist_audit_{col}",
status=CheckStatus.SKIPPED,
message="scipy not installed, skipping chi-square test",
execution_time_ms=(time.time() - start) * 1000
))
except Exception as e:
results.append(CheckResult(
check_name=f"dist_audit_{col}",
status=CheckStatus.FAILED,
message=f"Chi-square test failed for {col}: {str(e)}",
execution_time_ms=(time.time() - start) * 1000
))
return results
class TimingBudget:
"""Manages timing constraints and budgets"""
def __init__(self, budgets: Dict[str, timedelta]):
self.budgets = budgets
def check_budget(
self,
operation: str,
duration: timedelta,
stage: str = "total"
) -> CheckResult:
"""Check if operation completed within budget"""
budget = self.budgets.get(f"{operation}_{stage}") or self.budgets.get(operation)
if budget is None:
return CheckResult(
check_name=f"timing_{operation}_{stage}",
status=CheckStatus.SKIPPED,
message=f"No budget defined for {operation}_{stage}",
execution_time_ms=duration.total_seconds() * 1000
)
status = CheckStatus.PASSED if duration <= budget else CheckStatus.FAILED
return CheckResult(
check_name=f"timing_{operation}_{stage}",
status=status,
message=f"{operation}_{stage}: {duration.total_seconds():.1f}s / {budget.total_seconds():.1f}s",
details={
"operation": operation,
"stage": stage,
"duration_seconds": duration.total_seconds(),
"budget_seconds": budget.total_seconds(),
"utilization_pct": (duration / budget * 100) if budget.total_seconds() > 0 else 0
},
execution_time_ms=duration.total_seconds() * 1000,
threshold_violation=(duration > budget)
)
class BackfillVerifier:
"""Main verifier orchestrating all checks"""
def __init__(
self,
data_source: DataSource,
invariant_checks: List[Callable] = None,
sample_audit_config: Dict[str, Any] = None,
timing_budgets: Dict[str, timedelta] = None,
default_sample_size: int = 10000
):
self.data_source = data_source
self.invariant_checks = invariant_checks or []
self.sample_audit_config = sample_audit_config or {}
self.timing_budget = TimingBudget(timing_budgets or {})
self.default_sample_size = default_sample_size
self.logger = logger
# Default invariant checks if none provided
if not self.invariant_checks:
self.invariant_checks = [
lambda df: InvariantChecker.non_null_check(df, []), # Will be configured per table
lambda df: InvariantChecker.uniqueness_check(df, [])
]
def verify_backfill(
self,
backfill_id: str,
table_name: str,
start_date: datetime,
end_date: datetime,
run_invariants: bool = True,
run_sample_audit: bool = True,
run_timing_checks: bool = True,
custom_checks: List[Callable] = None
) -> AuditReport:
"""Main verification entry point"""
start_time = datetime.now()
self.logger.info(f"Starting verification for backfill {backfill_id}, table {table_name}")
results = {
'invariant_results': [],
'sample_audit_results': [],
'timing_results': []
}
try:
# 1. Load data
load_start = time.time()
backfill_df = self.data_source.get_backfill_data(backfill_id)
source_df = self.data_source.get_source_data(start_date, end_date)
load_duration = timedelta(seconds=time.time() - load_start)
if run_timing_checks:
results['timing_results'].append(
self.timing_budget.check_budget("data_load", load_duration, "extract")
)
# 2. Run invariant checks
if run_invariants:
invariant_start = time.time()
for check_func in self.invariant_checks:
try:
# Configure check with table-specific parameters
result = check_func(backfill_df)
results['invariant_results'].append(result)
except Exception as e:
results['invariant_results'].append(CheckResult(
check_name=check_func.__name__,
status=CheckStatus.FAILED,
message=f"Check failed with exception: {str(e)}",
execution_time_ms=(time.time() - invariant_start) * 1000,
threshold_violation=True
))
invariant_duration = timedelta(seconds=time.time() - invariant_start)
if run_timing_checks:
results['timing_results'].append(
self.timing_budget.check_budget("invariants", invariant_duration)
)
# 3. Run sample audits
if run_sample_audit:
audit_start = time.time()
sample_size = self.sample_audit_config.get('sample_size', self.default_sample_size)
# Row count check
row_count_result = InvariantChecker.row_count_check(
backfill_df,
source_df,
self.sample_audit_config.get('row_count_tolerance', 0.01)
)
results['sample_audit_results'].append(row_count_result)
# Stratified sample audit
if 'stratify_column' in self.sample_audit_config:
strat_result = SampleAuditor.stratified_sample_audit(
backfill_df=backfill_df,
source_df=source_df,
stratify_column=self.sample_audit_config['stratify_column'],
sample_size=sample_size,
confidence_level=self.sample_audit_config.get('confidence_level', 0.95)
)
results['sample_audit_results'].append(strat_result)
# Distribution audits
numeric_cols = self.sample_audit_config.get('numeric_columns', [])
categorical_cols = self.sample_audit_config.get('categorical_columns', [])
if numeric_cols or categorical_cols:
dist_results = SampleAuditor.column_distribution_audit(
backfill_df=backfill_df,
source_df=source_df,
numeric_columns=numeric_cols,
categorical_columns=categorical_cols,
ks_alpha=self.sample_audit_config.get('ks_alpha', 0.05)
)
results['sample_audit_results'].extend(dist_results)
audit_duration = timedelta(seconds=time.time() - audit_start)
if run_timing_checks:
results['timing_results'].append(
self.timing_budget.check_budget("sample_audit", audit_duration)
)
# 4. Run custom checks
if custom_checks:
custom_start = time.time()
for check in custom_checks:
try:
result = check(backfill_df, source_df)
results['sample_audit_results'].append(result)
except Exception as e:
results['sample_audit_results'].append(CheckResult(
check_name=check.__name__,
status=CheckStatus.FAILED,
message=f"Custom check failed: {str(e)}",
execution_time_ms=(time.time() - custom_start) * 1000,
threshold_violation=True
))
custom_duration = timedelta(seconds=time.time() - custom_start)
if run_timing_checks:
results['timing_results'].append(
self.timing_budget.check_budget("custom_checks", custom_duration)
)
# Generate summary
all_results = (
results['invariant_results'] +
results['sample_audit_results'] +
results['timing_results']
)
total_duration = datetime.now() - start_time
summary = {
'total_checks': len(all_results),
'passed': sum(1 for r in all_results if r.status == CheckStatus.PASSED),
'failed': sum(1 for r in all_results if r.status == CheckStatus.FAILED),
'warnings': sum(1 for r in all_results if r.status == CheckStatus.WARNING),
'skipped': sum(1 for r in all_results if r.status == CheckStatus.SKIPPED),
'threshold_violations': sum(1 for r in all_results if r.threshold_violation),
'avg_execution_time_ms': np.mean([r.execution_time_ms for r in all_results]) if all_results else 0,
'backfill_rows': len(backfill_df),
'source_rows': len(source_df)
}
report = AuditReport(
backfill_id=backfill_id,
start_time=start_time,
end_time=datetime.now(),
total_duration_seconds=total_duration.total_seconds(),
invariant_results=results['invariant_results'],
sample_audit_results=results['sample_audit_results'],
timing_results=results['timing_results'],
summary=summary,
metadata={
'table_name': table_name,
'date_range': f"{start_date.date()} to {end_date.date()}",
'config': {
'sample_size': sample_size,
'run_invariants': run_invariants,
'run_sample_audit': run_sample_audit,
'run_timing_checks': run_timing_checks
}
}
)
self.logger.info(
f"Verification complete: {summary['passed']}/{summary['total_checks']} checks passed, "
f"{summary['threshold_violations']} threshold violations"
)
return report
except Exception as e:
self.logger.error(f"Verification failed: {str(e)}")
raise
# Example Usage
def example_usage():
"""Example implementation with mock data source"""
class MockDataSource(DataSource):
"""Mock data source for testing"""
def __init__(self):
self.backfill_data = {}
self.source_data = pd.DataFrame()
def get_source_data(self, start_date: datetime, end_date: datetime) -> pd.DataFrame:
# Simulate source data with some issues
dates = pd.date_range(start_date, end_date, freq='D')
n = len(dates) * 100
df = pd.DataFrame({
'id': range(n),
'date': np.random.choice(dates, n),
'value': np.random.normal(100, 15, n),
'category': np.random.choice(['A', 'B', 'C', 'D'], n, p=[0.4, 0.3, 0.2, 0.1]),
'foreign_key': np.random.randint(1, 1000, n)
})
# Introduce some issues
df.loc[0:10, 'value'] = np.nan # Null values
df.loc[100:110, 'id'] = 1 # Duplicate IDs
df.loc[200:210, 'foreign_key'] = 9999 # Invalid foreign keys
return df
def get_backfill_data(self, backfill_id: str) -> pd.DataFrame:
return self.backfill_data.get(backfill_id, pd.DataFrame())
def get_schema(self, table_name: str) -> Dict[str, str]:
return {
'id': 'int',
'date': 'date',
'value': 'float',
'category': 'string',
'foreign_key': 'int'
}
# Initialize
data_source = MockDataSource()
# Prepare a sample backfill
backfill_df = pd.DataFrame({
'id': range(1000),
'date': pd.date_range('2024-01-01', periods=1000, freq='H'),
'value': np.random.normal(100, 15, 1000),
'category': np.random.choice(['A', 'B', 'C', 'D'], 1000),
'foreign_key': np.random.randint(1, 1000, 1000)
})
data_source.backfill_data['test_backfill_001'] = backfill_df
# Configure verifier
verifier = BackfillVerifier(
data_source=data_source,
timing_budgets={
'data_load_extract': timedelta(minutes=5),
'data_load_transform': timedelta(minutes=10),
'invariants': timedelta(minutes=2),
'sample_audit': timedelta(minutes=3)
},
sample_audit_config={
'sample_size': 5000,
'stratify_column': 'category',
'numeric_columns': ['value'],
'categorical_columns': ['category'],
'row_count_tolerance': 0.02
}
)
# Add custom invariant check
def custom_value_range_check(df):
return InvariantChecker.range_check(df, 'value', 0, 200)
# Run verification
report = verifier.verify_backfill(
backfill_id='test_backfill_001',
table_name='transactions',
start_date=datetime(2024, 1, 1),
end_date=datetime(2024, 1, 7),
custom_checks=[custom_value_range_check]
)
# Print results
print(report.to_json())
# Print summary
print("\n=== SUMMARY ===")
print(f"Total checks: {report.summary['total_checks']}")
print(f"Passed: {report.summary['passed']}")
print(f"Failed: {report.summary['failed']}")
print(f"Warnings: {report.summary['warnings']}")
print(f"Threshold violations: {report.summary['threshold_violations']}")
# Find failed checks
failed_checks = [
r for r in
(report.invariant_results + report.sample_audit_results + report.timing_results)
if r.status == CheckStatus.FAILED
]
if failed_checks:
print("\n=== FAILED CHECKS ===")
for check in failed_checks:
print(f"- {check.check_name}: {check.message}")
if __name__ == "__main__":
example_usage()
Key Features:
1. Invariant Checks
- Null Checks: Validate critical columns have no nulls
- Uniqueness Checks: Enforce primary key constraints
- Foreign Key Checks: Validate referential integrity
- Range Checks: Ensure values within expected bounds
- Row Count Checks: Validate total row counts with tolerance
- Custom Checks: Pluggable custom validation logic
2. Sample Audits
- Stratified Sampling: Statistically significant sampling by strata
- Distribution Audits:
- Kolmogorov-Smirnov test for numeric distributions
- Chi-square test for categorical distributions
- Confidence Levels: Configurable statistical confidence (default 95%)
3. Timing Budgets
- Stage-wise Budgets: Separate budgets for extract/transform/load stages
- Utilization Tracking: Monitor budget utilization percentages
- Operation-specific: Different budgets per operation type
4. Production Features
- Comprehensive Reporting: JSON-serializable audit trails
- Performance Metrics: Execution time tracking per check
- Error Handling: Graceful degradation with detailed error messages
- Configurable: Flexible configuration via dictionaries
- Extensible: Abstract base classes for custom data sources
5. Configuration Example
timing_budgets = {
'data_load_extract': timedelta(minutes=5),
'data_load_transform': timedelta(minutes=10),
'invariants': timedelta(minutes=2),
'sample_audit': timedelta(minutes=3)
}
sample_audit_config = {
'sample_size': 10000,
'stratify_column': 'category',
'numeric_columns': ['revenue', 'quantity'],
'categorical_columns': ['product_id', 'region'],
'ks_alpha': 0.01, # 99% confidence
'row_count_tolerance': 0.01 # 1% tolerance
}
6. Integration Points
- Data Sources: Implement
DataSource abstract class for your warehouse (Snowflake, BigQuery, Redshift, etc.)
- Alerting: Hook into monitoring systems by checking
report.summary['threshold_violations']
- CI/CD: Integrate into backfill pipelines as a validation step
- Scheduling: Run periodic audits on completed backfills
7. Best Practices
- Run invariants first - Fast checks that catch major issues
- Sample strategically - Stratify by important dimensions (region, time, category)
- Set realistic budgets - Base on historical backfill performance
- Monitor trends - Track audit results over time to detect regression
- Document exceptions - Use
metadata field to track known issues
This verifier provides a robust framework for ensuring backfill correctness while maintaining performance through sampling and statistical validation. The modular design allows easy extension for specific business requirements.