The user wants a "backfill correctness verifier."
The key features requested are:
- Invariant checks: Logic to ensure data properties hold true after the backfill.
- Sample audits: A mechanism to spot-check specific records.
- Timing budgets: Constraints on how long the verification process should take.
I need to design a system or provide a code framework that demonstrates these concepts.
1. High-Level Design:
- Input: Backfilled data (target) and Source data (or a log of operations).
- Process:
- Invariants: Run SQL or code to check counts, sums, distinct values, nullability, etc.
- Sampling: Randomly select IDs from source, check existence and equality in target.
- Timing: Wrap checks in a timer, assert it stays under a limit.
- Output: A report (Pass/Fail) with metrics.
2. Component Breakdown & Code Structure (Python is best for this kind of orchestration):
- Data Structures: Need a way to represent a "Check."
- Database Connector: I'll mock this or use a standard library like
sqlite3 for demonstration so the code is runnable, but I should write it in a way that's adaptable to BigQuery/Snowflake/Postgres.
- The
Verifier Class: The main orchestrator.
3. Feature 1: Invariant Checks
- Definition: These are aggregate checks.
- Count check:
COUNT(*) Source == COUNT(*) Target.
- Metric check:
SUM(revenue) Source ≈ SUM(revenue) Target (handling floating point issues).
- Logic check: No NULLs in a non-nullable column.
- Implementation: A list of SQL queries or Python functions returning boolean + message.
4. Feature 2: Sample Audits
- Definition: Row-level checks.
- Strategy:
- Get N random keys from Source.
- Fetch those keys from Target.
- Compare fields (hash maps or direct value comparison).
- Corner case: What if a key was deleted? (Should have been caught by count check, but good to note).
- Implementation:
get_random_ids(source_table)
fetch_rows(target_table, ids)
compare_row(source_row, target_row)
5. Feature 3: Timing Budgets
- Definition: Ensuring the verification doesn't take longer than X seconds.
- Implementation: A Python context manager or decorator.
- If time > budget -> Warning or Fail? usually Warning for checks (so we don't fail a valid backfill just because the DB was slow), but could be a Fail if it implies data size explosion. Let's stick to "soft fail" or warning for timing, unless specified as a hard SLA.
6. Refining the Output:
I will provide a Python class BackfillVerifier that uses a generic database interface. I'll implement a mock database class so the user can run the code immediately, but structure it so they can swap in psycopg2, snowflake-connector, or pandas.
7. Step-by-Step Implementation Plan:
- Step 1: Setup & Mock Data: Create a fake source and target dataset (using SQLite or in-memory Pandas). Let's use SQLite for realism regarding SQL execution time.
- Step 2: The
BackfillVerifier Class:
__init__(self, source_db, target_db, budget_seconds)
add_invariant(name, query, assertion_fn)
run_sample_audit(sample_size)
run()
- Step 3: Invariant Logic:
- Count Invariant: Check row counts.
- Metric Invariant: Check sum/avg.
- Null Check: Check for unexpected nulls.
- Step 4: Sampling Logic:
- Extract random IDs.
- Verify data parity.
- Step 5: Timing:
- Use
time.perf_counter().
- Raise exception if budget exceeded (or log critical error).
8. Self-Correction/Review during drafting:
- Issue: Running SQL in Python examples can be tricky if the user doesn't have a DB.
- Fix: I will write the solution using Python's built-in
sqlite3 so it runs out-of-the-box. I will add comments on where to swap for Snowflake/BigQuery.
- Complexity: The sampling needs to be efficient. Don't load the whole DB into memory.
- Approach:
SELECT * FROM source ORDER BY RANDOM() LIMIT 100 (SQLite specific, but standard pattern exists elsewhere).
- Invariant Definitions: Instead of hardcoding SQL, I should allow the user to inject a function or a tuple of (query, validation_logic).
9. Structuring the Response:
- Architecture Overview: Explain the three pillars (Invariants, Sampling, Timing).
- The Code Framework: A complete, runnable Python script.
- Detailed Explanation: Break down the code sections.
- Production Considerations: Mention scaling, statistical significance, and alerting.
Let's write the code mentally first.
class Verifier:
def __init__(self, budget=60): ...
def check_invariant(self, query, validator): ...
def audit_samples(self, source_query, target_query, n): ...
def execute(self): ...
Looks solid. I'll ensure the timing budget is a context manager wrapping the whole execution or individual critical checks. Wrapping the whole execution is usually what "budget" implies in pipelines (the SLA).
Let's add a "Statistical Equality" check (Chi-squared or simple diff) in the explanation, but keep the code simple for readability.
Final Polish of the Prompt Requirements:
- Invariant checks: Implemented via generic query runners.
- Sample audits: Implemented via random ID selection and row comparison.
- Timing budgets: Implemented via
time module and a hard stop.
Let's generate the response.
A backfill verifier acts as a quality gate between your data pipeline and production. It must answer three questions: Is the data mathematically sound? (Invariants), Does the actual content look right? (Audits), and Did it arrive on time? (Timing).
Below is a comprehensive framework to build this verifier in Python, designed to be database-agnostic (concepts apply to SQL, Spark, or Pandas).
1. Architecture Overview
We will build a BackfillVerifier class that executes three distinct phases:
- Invariant Checks: Aggregate math (Counts, Sums, Uniqueness).
- Sample Audits: Row-level spot checks (Hash comparisons).
- Timing Budgets: Performance SLAs.
2. The Implementation
This implementation uses Python's standard sqlite3 for demonstration, but the patterns map 1:1 to Postgres, BigQuery, or Snowflake.
import time
import random
import hashlib
import sqlite3
from dataclasses import dataclass
from typing import List, Dict, Any, Callable, Optional
# --- Data Structures for Reporting ---
@dataclass
class CheckResult:
check_name: str
passed: bool
message: str
duration_ms: float
class BackfillVerificationError(Exception):
"""Raised when verification fails critically."""
pass
# --- The Core Verifier Class ---
class BackfillVerifier:
def __init__(self, conn_source: sqlite3.Connection, conn_target: sqlite3.Connection, timing_budget_ms: int = 5000):
self.source = conn_source
self.target = conn_target
self.timing_budget_ms = timing_budget_ms
self.results: List[CheckResult] = []
def _execute_sql(self, conn: sqlite3.Connection, query: str) -> Any:
"""Helper to run a query and fetch a single result."""
cursor = conn.cursor()
cursor.execute(query)
return cursor.fetchone()[0]
# --- PHASE 1: Invariant Checks ---
def check_invariant(self, name: str, query: str, tolerance: float = 0.0):
"""
Executes a query on both Source and Target and compares results.
Use for: Row counts, Sum of revenue, Count of distinct users.
"""
start_time = time.perf_counter()
source_val = self._execute_sql(self.source, query)
target_val = self._execute_sql(self.target, query)
# Handle division by zero or None
if source_val is None and target_val is None:
passed = True
diff = 0
elif source_val is None or target_val is None:
passed = False
diff = float('inf')
else:
diff = abs(source_val - target_val)
# Absolute tolerance for integers (exact match) or percentage for floats
if tolerance == 0.0:
passed = (source_val == target_val)
else:
passed = (diff <= source_val * tolerance)
duration = (time.perf_counter() - start_time) * 1000
msg = f"Source: {source_val}, Target: {target_val}, Diff: {diff}"
self.results.append(CheckResult(name, passed, msg, duration))
if not passed:
print(f"❌ INVARIANT FAILED: {name} | {msg}")
else:
print(f"✅ INVARIANT PASSED: {name}")
# --- PHASE 2: Sample Audits ---
def audit_samples(self, table_name: str, pk_column: str, columns_to_check: List[str], sample_size: int = 100):
"""
Randomly selects IDs from Source, fetches corresponding Target rows,
and compares content hashes.
"""
print(f"\n🔍 Running Sample Audit (Size: {sample_size})...")
start_time = time.perf_counter()
# 1. Get Random IDs from Source
# Note: In production, use TABLESAMPLE (Postgres) or RAND() limit for efficiency
get_ids_query = f"SELECT {pk_column} FROM {table_name} ORDER BY RANDOM() LIMIT {sample_size}"
cursor = self.source.cursor()
cursor.execute(get_ids_query)
sample_ids = [row[0] for row in cursor.fetchall()]
if not sample_ids:
self.results.append(CheckResult("Sample Audit", False, "No rows found in source", 0))
return
# 2. Fetch rows from both sides and compare
failures = 0
cols_str = ", ".join(columns_to_check)
for sid in sample_ids:
# Fetch Source Row
s_row = self.source.execute(f"SELECT {cols_str} FROM {table_name} WHERE {pk_column} = ?", (sid,)).fetchone()
# Fetch Target Row
t_row = self.target.execute(f"SELECT {cols_str} FROM {table_name} WHERE {pk_column} = ?", (sid,)).fetchone()
# Hash comparison (handles floating point precision issues better than raw equality)
s_hash = hashlib.md5(str(s_row).encode('utf-8')).hexdigest()
t_hash = hashlib.md5(str(t_row).encode('utf-8')).hexdigest()
if s_hash != t_hash:
failures += 1
# Log specific mismatch for debugging
# print(f" Mismatch at ID {sid}: Source {s_row} vs Target {t_row}")
duration = (time.perf_counter() - start_time) * 1000
passed = (failures == 0)
msg = f"{failures} / {sample_size} mismatched rows."
self.results.append(CheckResult("Sample Audit", passed, msg, duration))
if passed:
print(f"✅ AUDIT PASSED: {sample_size} rows verified")
else:
print(f"❌ AUDIT FAILED: {msg}")
# --- PHASE 3: Timing & Reporting ---
def verify_timing_budget(self):
"""Checks if the total verification process exceeded time limits."""
total_time = sum(r.duration_ms for r in self.results)
passed = total_time <= self.timing_budget_ms
print(f"\n⏱️ Timing: {total_time:.2f}ms / Budget: {self.timing_budget_ms}ms")
return passed
def generate_report(self):
print("\n--- VERIFICATION REPORT ---")
total_checks = len(self.results)
passed_checks = sum(1 for r in self.results if r.passed)
print(f"Summary: {passed_checks}/{total_checks} Checks Passed")
if passed_checks != total_checks:
raise BackfillVerificationError("Backfill data quality checks failed.")
3. How to Use It
Here is a mock scenario where we verify a users table backfill.
# 1. Setup Mock Data (Source vs Target)
conn_src = sqlite3.connect(':memory:')
conn_tgt = sqlite3.connect(':memory:')
# Source has 1000 users
conn_src.execute("CREATE TABLE users (id INT, revenue REAL, status TEXT)")
mock_data = [(i, float(i * 10), 'active') for i in range(1000)]
conn_src.executemany("INSERT INTO users VALUES (?, ?, ?)", mock_data)
conn_src.commit()
# Target has 1000 users (but let's simulate a bug: one user has wrong revenue)
conn_tgt.execute("CREATE TABLE users (id INT, revenue REAL, status TEXT)")
target_data = [(i, float(i * 10), 'active') for i in range(1000)]
# Introduce Data Corruption:
target_data[500] = (500, 999999.99, 'active') # ID 500 has wrong revenue
conn_tgt.executemany("INSERT INTO users VALUES (?, ?, ?)", target_data)
conn_tgt.commit()
# 2. Configure Verifier
verifier = BackfillVerifier(conn_src, conn_tgt, timing_budget_ms=2000)
# 3. Define Invariants (Math Checks)
verifier.check_invariant("Row Count", "SELECT COUNT(*) FROM users")
verifier.check_invariant("Distinct Statuses", "SELECT COUNT(DISTINCT status) FROM users")
# We expect revenue to match exactly (tolerance 0)
verifier.check_invariant("Total Revenue", "SELECT SUM(revenue) FROM users", tolerance=0.0)
# 4. Run Sample Audit (Content Checks)
# This will likely catch the corrupted row 500
verifier.audit_samples(
table_name="users",
pk_column="id",
columns_to_check=["revenue", "status"],
sample_size=50
)
# 5. Finalize
verifier.verify_timing_budget()
try:
verifier.generate_report()
except BackfillVerificationError as e:
print(f"\n🚨 Pipeline Halted: {e}")
4. Detailed Component Breakdown
1. Invariant Checks (The "Physics")
These ensure that the "shape" of the data remains unchanged. If these fail, the backfill is fundamentally broken.
- Count Invariant:
COUNT(*) must match exactly.
- Uniqueness Invariant:
COUNT(DISTINCT id) should not drop (deduplication failure).
- Referential Integrity: (SQL)
COUNT(*) WHERE user_id NOT IN (SELECT id FROM users) should be 0.
- Numerical Stability: For floats (like
revenue), use a tolerance (e.g., 0.01%) to handle rounding differences between database engines, or cast to integers (cents) before comparing.
2. Sample Audits (The "Reality")
Invariants can pass even if data is corrupted (e.g., a specific user's name is swapped).
- Stratified Sampling: Don't just use
RANDOM(). Ensure you check the "head" (oldest data), "tail" (newest data), and a random middle set.
- Hash Comparison: Instead of comparing
col_a == col_a, concatenate the row and hash it (MD5/SHA256). This makes it easy to spot any difference in a large row with a single equality check.
3. Timing Budgets (The "SLA")
A backfill verifier often runs in a pipeline (e.g., Airflow/Dagster).
- Soft Budget: Log a warning if verification takes too long (indicates data volume grew unexpectedly).
- Hard Budget: Fail the job if verification takes > 10 mins.
- Implementation: The class tracks cumulative duration. If
sum(durations) > budget, raise an alert.
5. Production Enhancements
If you are deploying this in a real data warehouse (Snowflake/BigQuery):
- Galaxy Queries (Joins): Instead of pulling data into Python, run the audit in SQL:
SELECT count(*)
FROM source_table s
FULL OUTER JOIN target_table t ON s.id = t.id
WHERE s.hash != t.hash OR s.id IS NULL OR t.id IS NULL
This returns a single number (0 means success) and is much faster for big data.
- Column-Level Partitioning: Run timing budgets per column. If
user_bio (text) takes 10x longer to verify than user_id (int), you might want to exclude heavy text columns from strict timing budgets.
- Assertion Library: Wrap the
check_invariant calls into a YAML configuration file so non-engineers can define backfill rules.