Build a structured data drift detector: template diffs, error clustering, and alert…
- User
Build a structured data drift detector: template diffs, error clustering, and alert routing.
Assistant
Build a structured data drift detector: template diffs, error clustering, and alert routing.
The user wants a "structured data drift detector" that includes three main components:
This sounds like a backend system, likely in Python given its dominance in data science and log analysis, though Go or Rust could work for performance. I'll stick with Python for readability and library support (pandas, scikit-learn, etc.).
Deconstruction of Requirements:
<NUM>, UUIDs with <UUID>, and IPs with <IP>. The resulting string is the "template."Architecture Design:
DataPoint: A simple class/struct for incoming data.TemplateEngine: Normalizes logs into templates.DriftAnalyzer: Compares window A vs. window B.Clusterer: Groups errors.AlertRouter: Dispatches notifications.main: Orchestrator.Drafting the Code (Mental or Scratchpad):
re.sub(r'\d+', '<NUM>', text).TfidfVectorizer.KMeans.AlertManager with methods send_to_slack, send_email.Refining the "Template Diff" concept: The user specifically asked for "Template Diffs". This implies identifying what changed.
Constraints/Assumptions:
Step-by-Step Implementation Plan:
collections, sklearn, numpy, json, dataclasses.LogParser: Simple template extraction logic.DriftDetector:
compute_distribution: Counts templates.compare: Calculates PSI (Population Stability Index) or simple Cosine distance and lists specific diffs.ErrorClusterer:
AlertRouter:
main execution:
Self-Correction during drafting:
k. If I don't know the number of errors, maybe DBSCAN is better? Or just keep KMeans simple for the demo with a fixed k=3. Let's stick to KMeans for simplicity of code explanation.Code Structure:
import re
import json
import numpy as np
from collections import Counter
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
# ... mock classes for alerting ...
Let's refine the Drift Detection. I want to see:
Let's write the solution. I will define a clear Python class structure.
Feature List:
I will provide a single, well-commented Python file structure.
Dependencies: scikit-learn, numpy. (Standard DS stack).
Let's refine the Alert Routing. Routes:
Critical (New Error Patterns): PagerDuty (Mock)Warning (High Drift): Slack (Mock)Info (Low Drift): Dashboard (Print)Final Polish: Ensure the code runs out-of-the-box (with dependencies installed).
Plan:
(Self-Correction): What if the user implies JSON schema drift?
I'll implement the TemplateEngine to handle strings. If the input is a dict, I'll extract the values to form the string for template analysis. This covers both log lines and JSON values.
Let's build it. A robust Data Drift Detector requires three distinct layers: Feature Extraction (to understand structure), Statistical Comparison (to detect drift), and Contextual Routing (to alert the right people).
Below is a complete, modular Python implementation. It uses scikit-learn for clustering/statistics and defines a clear class structure for the pipeline.
You will need scikit-learn and numpy:
pip install scikit-learn numpy
import re
import json
import hashlib
import numpy as np
from collections import Counter, defaultdict
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
from sklearn.metrics import pairwise_distances
from typing import List, Dict, Any, Optional
from dataclasses import dataclass, field
from datetime import datetime
# ==========================================
# 1. Data Structures
# ==========================================
@dataclass
class DriftReport:
"""Container for drift detection results."""
is_drifted: bool
drift_score: float # 0.0 to 1.0
new_patterns: List[str]
disappeared_patterns: List[str]
volume_change_percentage: float
timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
@dataclass
class ClusterReport:
"""Container for error clustering results."""
cluster_id: int
representative_error: str
count: int
severity: str # e.g., 'critical', 'warning'
sample_errors: List[str]
# ==========================================
# 2. Template & Drift Detection Engine
# ==========================================
class StructuredDriftDetector:
"""
Detects schema/log drift by normalizing data into templates
and comparing frequency distributions.
"""
def __init__(self, min_support: int = 10):
self.min_support = min_support
self.baseline_templates: Counter = Counter()
self.baseline_total: int = 0
def _hash_data(self, data: Dict) -> str:
"""
Creates a structural template of the data.
- Sorts keys (schema stability)
- Masks values (to focus on structure, not content)
"""
# Simple recursive function to mask values
def mask(obj):
if isinstance(obj, dict):
return {k: mask(v) for k, v in sorted(obj.items())}
elif isinstance(obj, list):
if len(obj) > 0:
# Represent list structure by its first element type
return [mask(obj[0])]
return []
else:
# Replace actual values with type placeholders
return f"<{type(obj).__name__}>"
normalized = mask(data)
# Return a JSON string representing the structure
return json.dumps(normalized, sort_keys=True)
def train(self, historical_data: List[Dict]):
"""Builds the baseline distribution of templates."""
for item in historical_data:
template = self._hash_data(item)
self.baseline_templates[template] += 1
self.baseline_total = len(historical_data)
print(f"[*] Baseline trained on {self.baseline_total} records.")
print(f"[*] Discovered {len(self.baseline_templates)} unique structural templates.")
def detect(self, current_data: List[Dict], threshold: float = 0.15) -> DriftReport:
"""
Compares current data against baseline using Cosine Similarity
of template frequency vectors.
"""
if not self.baseline_templates:
raise Exception("Model not trained. Call .train() first.")
current_templates = Counter()
for item in current_data:
template = self._hash_data(item)
current_templates[template] += 1
current_total = len(current_data)
# 1. Identify New/Disappeared Patterns
baseline_keys = set(self.baseline_templates.keys())
current_keys = set(current_templates.keys())
new_patterns = list(current_keys - baseline_keys)
disappeared_patterns = list(baseline_keys - current_keys)
# 2. Calculate Statistical Drift (Simplified PSI/Cosine Similarity)
# We construct a vector of all unique keys from both sets
all_keys = list(baseline_keys | current_keys)
vec_baseline = np.array([self.baseline_templates.get(k, 0) for k in all_keys])
vec_current = np.array([current_templates.get(k, 0) for k in all_keys])
# Normalize to probabilities
p = vec_baseline / (self.baseline_total + 1e-9)
q = vec_current / (current_total + 1e-9)
# Cosine Similarity
dot_product = np.dot(p, q)
norm_p = np.linalg.norm(p)
norm_q = np.linalg.norm(q)
similarity = dot_product / (norm_p * norm_q + 1e-9)
drift_score = 1.0 - similarity
# 3. Volume Check
vol_change = ((current_total - self.baseline_total) / (self.baseline_total + 1e-9)) * 100
is_drifted = drift_score > threshold or len(new_patterns) > 0
return DriftReport(
is_drifted=is_drifted,
drift_score=float(drift_score),
new_patterns=[json.loads(p) for p in new_patterns[:3]], # Return top 3 readable
disappeared_patterns=[json.loads(p) for p in disappeared_patterns[:3]],
volume_change_percentage=vol_change
)
# ==========================================
# 3. Error Clustering Module
# ==========================================
class ErrorClusterer:
"""
Groups similar error messages/events using TF-IDF and K-Means.
"""
def __init__(self, num_clusters: int = 5):
self.vectorizer = TfidfVectorizer(max_features=100, stop_words='english')
self.model = KMeans(n_clusters=num_clusters, random_state=42)
def fit_predict(self, error_messages: List[str]) -> List[ClusterReport]:
if not error_messages:
return []
# 1. Vectorize
X = self.vectorizer.fit_transform(error_messages)
# 2. Cluster
clusters = self.model.fit_predict(X)
# 3. Aggregate Results
cluster_groups = defaultdict(list)
for idx, label in enumerate(clusters):
cluster_groups[label].append(error_messages[idx])
reports = []
for cluster_id, messages in cluster_groups.items():
# Find the most central message (closest to centroid)
# This is approximate; we just pick the first one for simplicity in this demo
representative = messages[0]
# Determine severity heuristically
severity = "critical" if "fail" in representative.lower() or "error" in representative.lower() else "warning"
reports.append(ClusterReport(
cluster_id=cluster_id,
representative_error=representative,
count=len(messages),
severity=severity,
sample_errors=messages[:3] # Send 3 samples
))
# Sort by count (most frequent first)
reports.sort(key=lambda x: x.count, reverse=True)
return reports
# ==========================================
# 4. Alert Routing
# ==========================================
class AlertRouter:
"""
Dispatches alerts based on Drift and Cluster reports.
"""
def route(self, drift_report: DriftReport, cluster_reports: List[ClusterReport]):
routes = []
# Route 1: Critical Schema Drift -> Engineering Lead
if drift_report.is_drifted and len(drift_report.new_patterns) > 0:
msg = f"CRITICAL: Data Drift Detected (Score: {drift_report.drift_score:.2f})"
self._send_pagerduty(msg, details=drift_report.new_patterns)
routes.append("PagerDuty::EngineeringLead")
# Route 2: High Volume Change -> Ops Team
if abs(drift_report.volume_change_percentage) > 20:
msg = f"WARNING: Traffic Volume Spike/Drop ({drift_report.volume_change_percentage:.1f}%)"
self._send_slack("#ops-alerts", msg)
routes.append("Slack::#ops-alerts")
# Route 3: Frequent Error Clusters -> Dev Team
for cluster in cluster_reports:
if cluster.count > 10 and cluster.severity == 'critical':
msg = f"High Frequency Error Cluster (Count: {cluster.count})"
self._send_jira("Backend Team", msg, cluster.sample_errors)
routes.append("Jira::BackendTeam")
return routes
# Mock senders
def _send_pagerduty(self, msg, details):
print(f"\n[ALERT][PAGERDUTY] {msg}")
print(f" -> Details: {details}")
def _send_slack(self, channel, msg):
print(f"\n[ALERT][SLACK:{channel}] {msg}")
def _send_jira(self, team, msg, samples):
print(f"\n[ALERT][JIRA:{team}] {msg}")
print(f" -> Samples: {samples[0]}")
# ==========================================
# 5. Main Orchestration
# ==========================================
def generate_mock_data(n=100, drift=False):
data = []
for _ in range(n):
# Standard log
item = {
"user_id": "u_123",
"event": "login",
"metadata": {"ip": "127.0.0.1", "browser": "chrome"}
}
# Introduce Drift (New Schema)
if drift and np.random.rand() > 0.8:
item["new_field"] = "unexpected_value" # New key
item["event"] = "purchase"
# Introduce Errors
if np.random.rand() > 0.9:
item["event"] = "error"
item["error_msg"] = f"Connection refused to DB at {np.random.randint(100)}"
data.append(item)
return data
if __name__ == "__main__":
# 1. Initialize Components
detector = StructuredDriftDetector()
clusterer = ErrorClusterer()
router = AlertRouter()
# 2. Train Baseline (Historical Data)
print("--- Phase 1: Training ---")
historical_data = generate_mock_data(n=1000, drift=False)
detector.train(historical_data)
# 3. Analyze Live Data (With Drift)
print("\n--- Phase 2: Detection ---")
live_data = generate_mock_data(n=1000, drift=True)
# 3a. Detect Drift
drift_report = detector.detect(live_data)
print(f"Drift Score: {drift_report.drift_score:.4f}")
print(f"New Patterns Found: {len(drift_report.new_patterns)}")
# 3b. Cluster Errors (Extracting error messages for clustering)
error_logs = [d.get("error_msg", "") for d in live_data if d.get("event") == "error"]
cluster_reports = clusterer.fit_predict(error_logs)
print(f"Error Clusters Found: {len(cluster_reports)}")
# 4. Route Alerts
print("\n--- Phase 3: Routing ---")
router.route(drift_report, cluster_reports)
Template Extraction (StructuredDriftDetector):
{"user": 1, "val": "a"} into {"user": "<int>", "val": "<str>"}.Drift Calculation:
new_patterns (e.g., a new field appeared in the JSON) vs disappeared_patterns.Error Clustering (ErrorClusterer):
Alert Routing (AlertRouter):