python
import pandas as pd
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.express as px
from datetime import datetime, timedelta
import json
from typing import Dict, List, Optional
import warnings
warnings.filterwarnings('ignore')
class ResilienceRegressionTracker:
"""
Resilience Regression Tracker
Purpose:
- Correlates chaos experiment outcomes with production incidents, change history, and remediation velocity.
- Detects regressions in system resilience (e.g., rising incident rates post-failed chaos experiments or changes).
- Provides visualizations, correlation scores, and regression alerts.
Key Metrics:
- Chaos Score: % of experiments succeeding without blast radius > threshold.
- Incident Rate: Incidents per day.
- Change Velocity: Deploys/config changes per day.
- Remediation Velocity: Mean Time To Recovery (MTTR) in hours.
Correlations:
- Time-lagged Pearson correlation (e.g., chaos failure -> incident spike).
- Regression Alert: High correlation (>0.7) + incident rate > baseline.
Usage:
tracker = ResilienceRegressionTracker(time_window_days=30)
tracker.ingest_chaos_data(data)
tracker.ingest_incidents(data)
tracker.ingest_changes(data)
tracker.compute_correlations()
tracker.generate_dashboard()
tracker.check_regressions()
"""
def __init__(self, time_window_days: int = 30, lag_days: int = 3):
self.time_window_days = time_window_days
self.lag_days = lag_days
self.df_daily: Optional[pd.DataFrame] = None
self.raw_data = {
'chaos': [],
'incidents': [],
'changes': []
}
self.correlations = {}
self.regressions = []
def ingest_chaos_data(self, chaos_data: List[Dict]):
"""
Ingest chaos experiment outcomes.
Example chaos_data:
[
{'timestamp': '2023-10-01T12:00:00Z', 'experiment_id': 'exp1', 'success': True, 'blast_radius': 0.1, 'recovery_time_min': 5},
...
]
"""
df_chaos = pd.DataFrame(chaos_data)
df_chaos['date'] = pd.to_datetime(df_chaos['timestamp']).dt.date
self.raw_data['chaos'].append(df_chaos)
def ingest_incidents(self, incident_data: List[Dict]):
"""
Ingest production incidents.
Example:
[
{'incident_id': 'inc1', 'start_time': '2023-10-01T12:00:00Z', 'end_time': '2023-10-01T13:30:00Z', 'severity': 'high', 'resolved': True},
...
]
"""
df_inc = pd.DataFrame(incident_data)
df_inc['date'] = pd.to_datetime(df_inc['start_time']).dt.date
df_inc['mttr_hours'] = (pd.to_datetime(df_inc['end_time']) - pd.to_datetime(df_inc['start_time'])).dt.total_seconds() / 3600
self.raw_data['incidents'].append(df_inc)
def ingest_changes(self, change_data: List[Dict]):
"""
Ingest change history (deploys, configs).
Example:
[
{'change_id': 'deploy1', 'timestamp': '2023-10-01T10:00:00Z', 'type': 'deploy', 'service': 'api'},
...
]
"""
df_changes = pd.DataFrame(change_data)
df_changes['date'] = pd.to_datetime(df_changes['timestamp']).dt.date
self.raw_data['changes'].append(df_changes)
def _aggregate_daily_metrics(self) -> pd.DataFrame:
"""Aggregate metrics into daily DataFrame."""
end_date = datetime.now().date()
start_date = end_date - timedelta(days=self.time_window_days)
dates = pd.date_range(start_date, end_date).date
df_daily = pd.DataFrame({'date': dates})
df_daily.set_index('date', inplace=True)
# Chaos metrics
if self.raw_data['chaos']:
df_chaos_agg = pd.DataFrame(self.raw_data['chaos'][0]).groupby('date').agg({
'success': 'mean', # Chaos Score (% success)
'blast_radius': 'max',
'recovery_time_min': 'mean'
}).rename(columns={'success': 'chaos_score', 'blast_radius': 'max_blast_radius'})
df_daily = df_daily.join(df_chaos_agg, how='left').fillna(1.0) # Default success=1 if no data
# Incident metrics
if self.raw_data['incidents']:
df_inc_agg = pd.DataFrame(self.raw_data['incidents'][0]).groupby('date').agg({
'incident_id': 'count',
'mttr_hours': 'mean'
}).rename(columns={'incident_id': 'incident_rate', 'mttr_hours': 'mttr_hours'})
df_daily = df_daily.join(df_inc_agg, how='left').fillna(0)
# Change metrics
if self.raw_data['changes']:
df_change_agg = pd.DataFrame(self.raw_data['changes'][0]).groupby('date').size().to_frame('change_velocity')
df_daily = df_daily.join(df_change_agg, how='left').fillna(0)
df_daily.reset_index(inplace=True)
df_daily['date'] = pd.to_datetime(df_daily['date'])
self.df_daily = df_daily.sort_values('date')
return self.df_daily
def compute_correlations(self):
"""Compute lagged Pearson correlations between metrics."""
if self.df_daily is None:
self._aggregate_daily_metrics()
metrics = ['chaos_score', 'incident_rate', 'change_velocity', 'mttr_hours']
self.correlations = {}
for i, m1 in enumerate(metrics):
for m2 in metrics[i+1:]:
# Lagged correlation (e.g., chaos affects incidents after lag_days)
lagged_m1 = self.df_daily[m1].shift(self.lag_days).dropna()
lagged_m2 = self.df_daily[m2].iloc[self.lag_days:].dropna()
corr = np.corrcoef(lagged_m1, lagged_m2)[0,1]
self.correlations[f'{m1}_vs_{m2}_lag{self.lag_days}'] = corr
def check_regressions(self, incident_threshold: float = 0.5, corr_threshold: float = 0.7):
"""Detect resilience regressions."""
self.regressions = []
recent_inc_rate = self.df_daily['incident_rate'].tail(7).mean()
baseline_inc_rate = self.df_daily['incident_rate'].iloc[:-7].mean()
if recent_inc_rate > baseline_inc_rate + incident_threshold:
# Check negative chaos correlation or high change velocity corr
chaos_inc_corr = self.correlations.get('chaos_score_vs_incident_rate_lag3', 0)
change_inc_corr = self.correlations.get('change_velocity_vs_incident_rate_lag3', 0)
if chaos_inc_corr < -corr_threshold or change_inc_corr > corr_threshold:
self.regressions.append({
'alert': 'RESILIENCE REGRESSION DETECTED',
'reason': f'Incident rate spiked to {recent_inc_rate:.2f} (baseline: {baseline_inc_rate:.2f}). '
f'Chaos corr: {chaos_inc_corr:.2f}, Change corr: {change_inc_corr:.2f}'
})
def generate_dashboard(self):
"""Generate interactive Plotly dashboard."""
if self.df_daily is None:
self._aggregate_daily_metrics()
fig = make_subplots(
rows=2, cols=2,
subplot_titles=('Daily Metrics', 'Correlations Heatmap', 'Incidents vs Chaos (Lagged)', 'MTTR & Changes'),
specs=[[{"secondary_y": False}, px.imshow(pd.DataFrame(list(self.correlations.items()), columns=['Pair', 'Corr']).set_index('Pair').T).data[0]],
[{"secondary_y": True}, {"secondary_y": False}]]
)
# Row 1, Col 1: All metrics
for col in self.df_daily.columns[1:]:
fig.add_trace(go.Scatter(x=self.df_daily['date'], y=self.df_daily[col], name=col, mode='lines'), row=1, col=1)
# Row 1, Col 2: Correlation Heatmap
corr_df = pd.DataFrame(list(self.correlations.items()), columns=['metric_pair', 'correlation'])
corr_df['corr_abs'] = corr_df['correlation'].abs()
heatmap = px.imshow(
pd.DataFrame([self.correlations]).T,
color_continuous_scale='RdBu_r',
aspect="auto"
).data[0]
fig.add_trace(heatmap, row=1, col=2)
# Row 2, Col 1: Lagged Chaos vs Incidents
chaos_lagged = self.df_daily['chaos_score'].shift(self.lag_days)
fig.add_trace(go.Scatter(x=chaos_lagged.dropna(), y=self.df_daily['incident_rate'].iloc[self.lag_days:].values,
mode='markers', name='Chaos vs Incidents (Lag 3d)'), row=2, col=1)
# Row 2, Col 2: MTTR & Changes
fig.add_trace(go.Scatter(x=self.df_daily['date'], y=self.df_daily['mttr_hours'], name='MTTR', mode='lines'), row=2, col=2)
fig.add_trace(go.Scatter(x=self.df_daily['date'], y=self.df_daily['change_velocity'], name='Change Velocity', mode='lines', yaxis='y2'), row=2, col=2)
fig.update_layout(height=800, title_text="Resilience Regression Tracker Dashboard")
fig.update_yaxes(title_text="Change Velocity", secondary_y=True, row=2, col=2)
fig.show()
# Print regressions
if self.regressions:
print("\n🚨 REGRESSIONS:")
for reg in self.regressions:
print(reg['alert'])
print(reg['reason'])
else:
print("✅ No regressions detected.")
# Example Usage with Synthetic Data
if __name__ == "__main__":
tracker = ResilienceRegressionTracker(time_window_days=60, lag_days=3)
# Synthetic Chaos Data (simulate some failures correlating with incidents)
chaos_data = [
{'timestamp': (datetime.now() - timedelta(days=i)).isoformat(), 'experiment_id': f'exp{i}',
'success': np.random.choice([True, False], p=[0.9, 0.1]), 'blast_radius': np.random.uniform(0, 0.5),
'recovery_time_min': np.random.uniform(1, 10)} for i in range(60)
]
tracker.ingest_chaos_data(chaos_data)
# Synthetic Incidents (spike after chaos failures)
np.random.seed(42)
incident_spikes = [10, 20, 30, 40, 50] # Days with higher incidents
incidents = []
for i in range(60):
date = datetime.now() - timedelta(days=i)
num_inc = np.random.poisson(0.5) + (5 if i in incident_spikes else 0)
for _ in range(num_inc):
mttr = np.random.exponential(2)
incidents.append({
'incident_id': f'inc{i}_{_}', 'start_time': date.isoformat(),
'end_time': (date + timedelta(hours=mttr)).isoformat(), 'severity': 'high'
})
tracker.ingest_incidents(incidents)
# Synthetic Changes
changes = [
{'change_id': f'change{i}', 'timestamp': (datetime.now() - timedelta(days=i)).isoformat(), 'type': 'deploy'}
for i in range(60) if np.random.rand() > 0.7 # ~30% days have changes
]
tracker.ingest_changes(changes)
tracker.compute_correlations()
tracker.check_regressions()
tracker.generate_dashboard()
This tracker quantifies resilience debt, enabling proactive chaos-driven improvements. Questions? Let's deduce further. 🕵️♂️