import pandas as pd
import numpy as np
from datetime import datetime, timedelta
class ResilienceRegressionTracker:
def __init__(self):
self.chaos_results = []
self.incidents = []
self.changes = []
# --- Data Ingestion Methods ---
def log_chaos(self, exp_id, service, fault_type, passed, timestamp):
"""Log a chaos experiment result."""
self.chaos_results.append({
'exp_id': exp_id,
'service': service,
'fault_type': fault_type,
'passed': passed,
'timestamp': timestamp
})
def log_incident(self, inc_id, service, fault_type, duration_mins, timestamp):
"""Log a production incident."""
self.incidents.append({
'inc_id': inc_id,
'service': service,
'fault_type': fault_type,
'duration': duration_mins,
'timestamp': timestamp
})
def log_change(self, change_id, service, description, timestamp):
"""Log a deployment or config change."""
self.changes.append({
'change_id': change_id,
'service': service,
'description': description,
'timestamp': timestamp
})
# --- Analysis Engine ---
def calculate_regression(self, time_window_days=30):
"""
The core logic:
1. Correlate Incidents with nearest prior Chaos Runs.
2. Correlate Incidents with nearest prior Changes.
3. Calculate MTTR trends.
"""
df_chaos = pd.DataFrame(self.chaos_results)
df_inc = pd.DataFrame(self.incidents)
df_change = pd.DataFrame(self.changes)
if df_inc.empty or df_chaos.empty:
return "Insufficient data for regression tracking."
# Ensure timestamps are datetime objects
for df in [df_chaos, df_inc, df_change]:
df['timestamp'] = pd.to_datetime(df['timestamp'])
# Sort by time
df_chaos = df_chaos.sort_values('timestamp')
df_inc = df_inc.sort_values('timestamp')
df_change = df_change.sort_values('timestamp')
report = []
print(f"\n--- RESILIENCE REGRESSION TRACKER: {datetime.now().strftime('%Y-%m-%d')} ---")
print(f"Analyzing window: Last {time_window_days} days\n")
for index, incident in df_inc.iterrows():
# 1. Find closest Chaos experiment of the SAME type and service BEFORE the incident
mask = (
(df_chaos['service'] == incident['service']) &
(df_chaos['fault_type'] == incident['fault_type']) &
(df_chaos['timestamp'] <= incident['timestamp'])
)
relevant_chaos = df_chaos[mask]
chaos_status = "NO_COVERAGE"
days_since_test = "N/A"
if not relevant_chaos.empty:
last_chaos = relevant_chaos.iloc[-1]
days_since_test = (incident['timestamp'] - last_chaos['timestamp']).days
if last_chaos['passed']:
chaos_status = "PASSED_BUT_FAILED_PROD" # Critical Regression
else:
chaos_status = "EXPECTED_FAILURE" # Known Weakness
# 2. Find closest Change BEFORE the incident (Root Cause Candidate)
change_mask = (
(df_change['service'] == incident['service']) &
(df_change['timestamp'] <= incident['timestamp'])
)
relevant_changes = df_change[change_mask]
suspected_change = "NO_RECENT_CHANGE"
change_proximity = "N/A"
if not relevant_changes.empty:
last_change = relevant_changes.iloc[-1]
change_proximity = (incident['timestamp'] - last_change['timestamp']).total_seconds() / 3600 # Hours
suspected_change = last_change['change_id']
if change_proximity < 24:
suspected_change += " (HIGH_SUSPICION)"
# 3. Calculate Velocity Score (Normalized 0-1, 1 being fast recovery)
# Arbitrary scale: < 30 mins is perfect (1.0), > 4 hours is terrible (0.1)
velocity_score = max(0.1, min(1.0, 1 - (incident['duration'] / 240)))
report.append({
'Incident': incident['inc_id'],
'Service': incident['service'],
'Fault': incident['fault_type'],
'Remediation_Velocity': velocity_score,
'Chaos_Coverage': chaos_status,
'Days_Since_Last_Test': days_since_test,
'Suspected_Change': suspected_change,
'Hours_Before_Incident': round(change_proximity, 2) if isinstance(change_proximity, float) else "N/A"
})
return pd.DataFrame(report)
# --- Usage Simulation ---
def run_simulation():
tracker = ResilienceRegressionTracker()
now = datetime.now()
# 1. Seed Chaos History (The Hypotheses)
# We tested DB failures on Payment service 2 days ago, it passed.
tracker.log_chaos("EXP-101", "PaymentService", "DB_Latency", passed=True, timestamp=now - timedelta(days=2))
# We tested Network loss on Auth service 10 days ago.
tracker.log_chaos("EXP-102", "AuthService", "Network_Loss", passed=False, timestamp=now - timedelta(days=10))
# 2. Seed Change History (The Variables)
# We deployed a new caching layer to Payment Service 4 hours ago
tracker.log_change("CHG-501", "PaymentService", "Update Redis Client", timestamp=now - timedelta(hours=4))
# 3. Seed Production Incidents (The Reality)
# A. Payment Service DB latency incident happened 1 hour ago.
# This is a REGRESSION because Chaos passed 2 days ago, but it failed in prod after a change.
tracker.log_incident("INC-900", "PaymentService", "DB_Latency", duration_mins=45, timestamp=now - timedelta(hours=1))
# B. Auth Service Network Loss happened today.
# This is NOT a regression (we knew it would fail), but velocity is slow.
tracker.log_incident("INC-901", "AuthService", "Network_Loss", duration_mins=180, timestamp=now - timedelta(hours=12))
# 4. Generate Report
df_report = tracker.calculate_regression()
# Formatting output
if isinstance(df_report, pd.DataFrame):
print(df_report.to_string(index=False))
print("\n--- ANALYSIS SUMMARY ---")
# Logic to interpret the dataframe results dynamically
for index, row in df_report.iterrows():
if row['Chaos_Coverage'] == "PASSED_BUT_FAILED_PROD":
print(f"🚨 CRITICAL REGRESSION DETECTED on {row['Service']}. "
f"Resilience test passed recently, but system broke after change {row['Suspected_Change']}.")
elif row['Remediation_Velocity'] < 0.5:
print(f"⚠️ VELOCITY WARNING on {row['Service']}. Remediation is slow ({row['Remediation_Velocity']}). "
f"Update runbooks.")
else:
print(f"✅ {row['Incident']} handled within expected parameters.")
if __name__ == "__main__":
run_simulation()