The user wants a "canary DB verifier." This sounds like a system for testing database changes (schema, data, query logic) in a production-like environment before fully rolling them out. The core idea is "shadowing" or "parallel running" where traffic is sent to both the old and new DBs, and the results are compared.
Key components requested:
- Shadow diffs: Comparing results between the primary (stable) DB and the secondary (canary/candidate) DB.
- Automated aborts: Stopping the canary process if discrepancies exceed a threshold.
- Dashboards: Visualizing the metrics and diffs.
Architecture:
- Traffic Interception/Mirroring: We need a way to capture live queries or transactions. This usually happens at the application layer (e.g., a "Dual Write" or "Read Shadow" pattern) or via a proxy. Let's assume an application-layer interceptor for maximum flexibility and ease of demonstration (as setting up a DB proxy is complex).
- The "Verifier" Service:
- Input: A query/transaction context.
- Execution: Runs against both DBs (Primary and Canary).
- Comparison: Logic to compare results (set-based for reads, status codes/affected rows for writes).
- Latency Measurement: Tracks speed.
- Diff Store & Analyzer: Where do we put the discrepancies? A log? A time-series DB? We need to count them and sample specific diffs for debugging.
- Controller/Decision Engine: Monitors the metrics. If
diff_rate > threshold, trigger abort.
- Dashboard: A frontend (React/Streamlit) or just a nice console output/text-based UI to visualize health.
Implementation Plan (Python approach):
- Language: Python is great for this logic.
- Libraries:
asyncpg or sqlalchemy (for DB), pandas (for diffing), FastAPI (for the dashboard/API), Redis (for metrics/pub-sub).
Step-by-Step Design:
Refining the Code Structure:
Let's build a complete, runnable Python application.
- Mock Databases: I can't ask the user to spin up two Postgres instances. I'll create a
MockDatabase class to simulate behavior and inject faults.
- The Verifier Class: The brain.
- The Dashboard: A FastAPI endpoint returning HTML/JSON.
Detailed Logic for "Shadow Diff":
- Time drift: Canary might be slower.
- Non-determinism:
SELECT NOW() or RANDOM() will always fail. I need to mention that the user needs to sanitize queries or allow-list functions.
- Comparison: Deep equality check on sorted results.
Automated Abort:
- A decorator or context manager.
- Checks a global state or shared memory (like Redis, but for a simple script, in-memory is fine).
Dashboard:
- Live charts (using Chart.js or simple HTML). Metrics: Latency P99, Diff Rate, Traffic Volume.
Drafting the Code:
- Imports: asyncio, random, time, json.
- Mock DB:
execute(query) -> results.
- Comparator:
compare(result1, result2) -> bool.
- Orchestrator:
run_verification_loop.
Let's add a specific twist: Schema Validation.
Before shadowing data, verify schema (column names/types) match.
The Output:
I will provide a comprehensive Python script that includes:
- The
CanaryVerifier Class: Handles the logic of dual-execution and diffing.
- Configuration: Settings for thresholds.
- Mock DB Layer: To make it runnable immediately.
- FastAPI Dashboard: To visualize the state.
- CLI Control: To trigger faults and see the abort in action.
Self-Correction during drafting: Real-world shadow traffic is asynchronous. The app shouldn't wait for the canary DB to respond to serve the user. However, for a verifier tool specifically (often run as a batch job or a sidecar analysis tool), synchronous comparison is often used to generate reports. I will implement it as an asynchronous sidecar pattern: it accepts queries, fires them off, and records diffs without blocking the main thread (simulated).
Diffing Strategy:
Simply == is bad for floats or JSON order.
I'll use a robust deep_diff function.
Safety Feature:
"Automated Abort" implies killing the canary deployment. In a real k8s setting, this is an API call. In this script, it sets a flag CANARY_HEALTHY = False.
Let's structure the solution:
- Concept & Architecture (Brief explanation).
- Core Implementation (Python).
- The Dashboard (HTML/JS embedded in Python).
- How to Run & Test.
Let's write the code.
Key features to implement:
- Exponential Backoff/Jitter for polling? No, it's push-based.
- Tolerance: Allow N% diffs.
- Drift: Allow time difference tolerance.
Let's produce a single file solution if possible, or cleanly separated files. I'll stick to a modular Python structure.
The "Shadow" logic:
We need to capture the result of Stable, capture result of Canary.
Compare.
Log diff.
The "Abort" logic:
If diff_count / total_count > threshold in the last 100 queries:
raise CanaryAbortException (or toggle a Circuit Breaker).
The "Dashboard":
Simple metrics endpoints.
(Self-Correction): Make sure to handle non-deterministic columns (like last_updated). I'll add a config option ignore_columns.
Let's assemble.
Plan:
mock_db.py: Simulates production vs canary.
verifier.py: The logic.
dashboard.py: The UI.
main.py: The runner.
Actually, a single robust script is better for a "build this" prompt so the user can copy-paste-run.
Script structure:
MockDB: One returns correct data, one might return buggy data (after a trigger).
Verifier:
check_query(query, params): Runs on both.
_diff(left, right): Comparison logic.
_analyze(): Updates metrics.
CircuitBreaker: Tracks failure rate.
FastAPI: Exposes metrics.
Let's go.
Building a robust Canary Database Verifier (often called a "Shadow Reader" or "Dark Traffic Tester") requires three distinct layers:
- The Interceptor: Captures live traffic (Read queries) and replays it against the new DB without affecting the user.
- The Diff Engine: Asynchronously compares results (handling ordering and floating-point drift) and calculates a "diff score."
- The Governor: Monitors the diff score and automatically triggers an abort (circuit breaker) if thresholds are breached.
Here is a complete, runnable implementation in Python using asyncio for concurrency and a simple in-memory dashboard.
1. Architecture Overview
- Language: Python 3.9+
- Concurrency:
asyncio (to query Primary and Shadow in parallel).
- Data Diffing: Deep comparison with tolerance for floats and list ordering.
- Dashboard: A simple HTTP server exposing JSON metrics (can be hooked up to Grafana).
2. The Implementation
Save this code as canary_verifier.py.
import asyncio
import random
import time
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from threading import Thread
from dataclasses import dataclass, field
from typing import Any, List, Dict, Optional
from collections import deque
import math
# ==========================================
# 1. CONFIGURATION & DATA STRUCTURES
# ==========================================
@dataclass
class CanaryConfig:
diff_threshold_percent: float = 1.0 # Abort if > 1% diffs
sample_rate: float = 0.1 # Sample 10% of traffic
latency_threshold_ms: float = 200.0 # Alert if shadow is slow
window_size: int = 1000 # Sliding window for metrics
@dataclass
class MetricStore:
total_requests: int = 0
successful_verifications: int = 0
mismatches: int = 0
errors: int = 0
aborted: bool = False
recent_latencies: deque = field(default_factory=lambda: deque(maxlen=100))
# Sliding window for diff rate calculation
recent_results: deque = field(default_factory=lambda: deque(maxlen=CanaryConfig.window_size))
# Global metrics state
METRICS = MetricStore()
CONFIG = CanaryConfig()
# ==========================================
# 2. MOCK DATABASE ADAPTERS
# ==========================================
class Database:
def __init__(self, name: str, is_buggy=False):
self.name = name
self.is_buggy = is_buggy
async def execute_query(self, query: str, params: tuple) -> List[Dict]:
# Simulate Network IO
await asyncio.sleep(random.uniform(0.001, 0.020))
# Simulate a result set based on params
# Pretend params[0] is a user_id
user_id = params[0] if params else 0
data = [
{"id": user_id, "username": f"user_{user_id}", "balance": 100.0 + user_id}
]
# Introduce a bug in the "Canary" DB for specific IDs to simulate a migration issue
if self.is_buggy and user_id % 10 == 0:
# Bug: Float precision error or missing field
data[0]["balance"] = 99.999
if user_id == 50:
data[0]["username"] = "CORRUPTED_NAME"
return data
# ==========================================
# 3. DIFFING ENGINE (Shadow Logic)
# ==========================================
class DiffEngine:
@staticmethod
def compare(val1: Any, val2: Any) -> bool:
# 1. Float comparison (handle precision drift)
if isinstance(val1, float) and isinstance(val2, float):
return math.isclose(val1, val2, rel_tol=1e-5)
# 2. List/Dict comparison (recursive)
if isinstance(val1, dict) and isinstance(val2, dict):
if val1.keys() != val2.keys():
return False
return all(DiffEngine.compare(val1[k], val2[k]) for k in val1)
if isinstance(val1, list) and isinstance(val2, list):
# Naive list comparison (order matters).
# For DB sets, you might want to sort by ID first.
if len(val1) != len(val2): return False
return all(DiffEngine.compare(v1, v2) for v1, v2 in zip(val1, val2))
# 3. Exact match
return val1 == val2
@staticmethod
def verify_rows(primary_rows: List, shadow_rows: List) -> bool:
# Quick length check
if len(primary_rows) != len(shadow_rows):
return False
# Sort rows by 'id' if present to ensure order-agnostic comparison
# (SQL queries without ORDER BY can return same data in different order)
if primary_rows and 'id' in primary_rows[0]:
primary_rows = sorted(primary_rows, key=lambda x: x['id'])
shadow_rows = sorted(shadow_rows, key=lambda x: x['id'])
return DiffEngine.compare(primary_rows, shadow_rows)
# ==========================================
# 4. THE VERIFIER SERVICE (Controller)
# ==========================================
class CanaryVerifier:
def __init__(self, primary_db: Database, shadow_db: Database):
self.primary = primary_db
self.shadow = shadow_db
self.engine = DiffEngine()
async def verify_read(self, query: str, params: tuple):
if METRICS.aborted:
return # System is halted
METRICS.total_requests += 1
# Throttling: Only sample a percentage of traffic
if random.random() > CONFIG.sample_rate:
return
start_time = time.time()
# Run both queries concurrently
try:
primary_task = self.primary.execute_query(query, params)
shadow_task = self.shadow.execute_query(query, params)
primary_res, shadow_res = await asyncio.gather(*[primary_task, shadow_task])
# Diff Logic
is_match = self.engine.verify_rows(primary_res, shadow_res)
latency = (time.time() - start_time) * 1000
METRICS.recent_latencies.append(latency)
METRICS.recent_results.append(is_match)
if not is_match:
METRICS.mismatches += 1
self._log_diff(query, params, primary_res, shadow_res)
self._check_abort_condition()
else:
METRICS.successful_verifications += 1
except Exception as e:
METRICS.errors += 1
print(f"[CRITICAL] Shadow Query Failed: {e}")
def _check_abort_condition(self):
# Calculate diff rate over sliding window
if len(METRICS.recent_results) < 10: return # Warm up
failures = sum(1 for x in METRICS.recent_results if not x)
rate = (failures / len(METRICS.recent_results)) * 100
if rate > CONFIG.diff_threshold_percent:
METRICS.aborted = True
print(f"\n[!!! ABORT !!!] Diff rate {rate:.2f}% exceeded threshold {CONFIG.diff_threshold_percent}%")
def _log_diff(self, query, params, p_res, s_res):
print(f"\n[DIFF DETECTED] Query: {query[:20]}...")
print(f" Primary: {p_res}")
print(f" Shadow : {s_res}")
# ==========================================
# 5. DASHBOARD & METRICS SERVER
# ==========================================
class DashboardServer(BaseHTTPRequestHandler):
def do_GET(self):
if METRICS.aborted:
status_color = "red"
status_text = "ABORTED (Canary Stopped)"
elif METRICS.mismatches > 0:
status_color = "orange"
status_text = "WARNING (Diffs Detected)"
else:
status_color = "green"
status_text = "HEALTHY"
avg_latency = sum(METRICS.recent_latencies) / len(METRICS.recent_latencies) if METRICS.recent_latencies else 0
# Calculate current window diff %
failures = sum(1 for x in METRICS.recent_results if not x)
diff_pct = (failures / len(METRICS.recent_results)) * 100 if METRICS.recent_results else 0
metrics_json = {
"status": status_text,
"color": status_color,
"total_traffic_sampled": METRICS.total_requests,
"mismatches_total": METRICS.mismatches,
"current_diff_percent": round(diff_pct, 2),
"avg_shadow_latency_ms": round(avg_latency, 2),
"abort_threshold": CONFIG.diff_threshold_percent
}
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(metrics_json, indent=2).encode('utf-8'))
def run_dashboard_server():
server = HTTPServer(('localhost', 8080), DashboardServer)
print("Dashboard running on http://localhost:8080")
server.serve_forever()
# ==========================================
# 6. MAIN SIMULATION LOOP
# ==========================================
async def simulate_production_traffic(verifier: CanaryVerifier):
print("Starting production traffic simulation...")
while True:
if METRICS.aborted:
print("Traffic simulation paused due to ABORT.")
await asyncio.sleep(5)
continue
# Simulate random user ID
user_id = random.randint(1, 200)
# App code calls the verifier wrapper
await verifier.verify_read("SELECT * FROM users WHERE id = %s", (user_id,))
await asyncio.sleep(0.01) # High throughput simulation
if __name__ == "__main__":
# Setup
primary = Database("Primary_Postgres")
# The 'Shadow' is our new DB. Let's make it buggy for user_id % 10 == 0
shadow = Database("Canary_MySQL", is_buggy=True)
verifier = CanaryVerifier(primary, shadow)
# Start Dashboard in background thread
t = Thread(target=run_dashboard_server, daemon=True)
t.start()
# Start Traffic Simulation
try:
asyncio.run(simulate_production_traffic(verifier))
except KeyboardInterrupt:
print("Stopped.")
How it works
-
Dual Execution:
The CanaryVerifier runs the same query against both primary and shadow databases simultaneously using asyncio.gather. This ensures that verifying the shadow DB doesn't slow down the actual application response time (the app returns the primary data immediately, while the verifier works in the background).
-
Diff Engine (The Brain):
The DiffEngine class compares two database results.
- Order Agnostic: It sorts results by ID before comparing. In SQL,
SELECT * without ORDER BY can return rows in different orders on different engines. We want to treat these as identical.
- Float Tolerance: It uses
math.isclose to ignore minor floating-point differences (common when moving between Postgres and MySQL).
-
Automated Abort (Circuit Breaker):
The system maintains a sliding window of the last 1,000 verification results.
- If the percentage of mismatches in this window exceeds
diff_threshold_percent (1% by default), it flips METRICS.aborted to True.
- When aborted, the system stops processing shadow traffic. In a real production environment, you would hook this boolean to a Feature Flag system to automatically turn off the "Write Shadow" or "Read Shadow" configuration.
-
The Dashboard:
A lightweight HTTP server runs on port 8080.
- Access
http://localhost:8080 to see a JSON dump of the state.
- You can feed this JSON into Grafana or a simple HTML frontend.
How to Run and Test
- Run the script:
python canary_verifier.py
- Watch the console. You will see
[DIFF DETECTED] logs appearing.
- Check the Dashboard: Open your browser to
http://localhost:8080.
- You will see
"current_diff_percent" rising.
- In the Mock DB, I programmed a bug for every user ID divisible by 10.
- Once the diff rate hits > 1%, the status changes to
ABORTED.
Integration Guide (How to use this in production)
Do not run this as a standalone script. Integrate the CanaryVerifier class into your application layer (API or Service Layer).
Pseudocode for a Python Web App (FastAPI/Django):
# Inside your User Service
def get_user(user_id):
# 1. Get real data
user_data = primary_db.query("SELECT * FROM users WHERE id=?", (user_id,))
# 2. Fire-and-forget verification (Non-blocking)
# Note: You must pass the query string and params to the verifier
background_tasks.add_task(
canary_verifier.verify_read,
"SELECT * FROM users WHERE id=?",
(user_id,)
)
return user_data