import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# Step 1: Define sample data for demonstration
# Each row represents a code change/PR/deploy candidate
# Columns: normalized risk scores (0=low risk, 1=high risk) for each factor
np.random.seed(42) # For reproducibility
n_samples = 100
data = pd.DataFrame({
'change_diff_signals': np.random.uniform(0, 1, n_samples), # e.g., % risky lines/churn score
'low_coverage': 1 - np.random.uniform(0.7, 1.0, n_samples), # Inverted coverage (low cov = high risk)
'blast_radius': np.random.uniform(0, 1, n_samples), # e.g., % users/services affected
'weak_guardrails': np.random.uniform(0, 1, n_samples), # e.g., 1 - #safety_measures score
'service': np.random.choice(['auth', 'payments', 'frontend', 'backend', 'api'], n_samples),
'pr_id': [f'PR-{i:03d}' for i in range(1, n_samples + 1)]
})
# Step 2: Compute overall regression risk score (weighted average; adjust weights as needed)
weights = {'change_diff_signals': 0.25, 'low_coverage': 0.30, 'blast_radius': 0.25, 'weak_guardrails': 0.20}
data['risk_score'] = (
data['change_diff_signals'] * weights['change_diff_signals'] +
data['low_coverage'] * weights['low_coverage'] +
data['blast_radius'] * weights['blast_radius'] +
data['weak_guardrails'] * weights['weak_guardrails']
)
# Step 3: Create a pivot for heatmap (e.g., by service and PR batch)
# Group PRs into batches for visualization (e.g., low/med/high risk PRs per service)
data['pr_batch'] = pd.cut(data['pr_id'].str.extract('(\d+)').astype(int)[0], bins=3, labels=['Low PRs', 'Med PRs', 'High PRs'])
pivot = data.pivot_table(values='risk_score', index='service', columns='pr_batch', aggfunc='mean')
# Step 4: Generate the heatmap
plt.figure(figsize=(10, 6))
sns.heatmap(pivot, annot=True, cmap='YlOrRd', center=0.5, fmt='.2f',
cbar_kws={'label': 'Regression Risk Score (0=Low, 1=High)'})
plt.title('Regression Risk Heatmap\n(by Service & PR Batch, incorporating Change Diff, Coverage, Blast Radius, Guardrails)')
plt.xlabel('PR Risk Batches')
plt.ylabel('Service')
plt.tight_layout()
plt.show()
# Optional: Print summary table for text output
print("\nSample Data Summary (Top 10):")
print(data[['pr_id', 'service', 'change_diff_signals', 'low_coverage', 'blast_radius', 'weak_guardrails', 'risk_score']].head(10).round(3).to_markdown(index=False))
# Step 5: Threshold-based alerts
high_risk_threshold = 0.7
high_risk_prs = data[data['risk_score'] > high_risk_threshold][['pr_id', 'service', 'risk_score']]
print(f"\n🚨 High Risk PRs (> {high_risk_threshold}):")
print(high_risk_prs.to_markdown(index=False))
How This Works
Customization
- Real Data: Replace
np.random with your metrics (e.g., from GitHub API, CircleCI coverage, Datadog blast radius).
- Dimensions: Swap axes (e.g., rows=blast_radius bins, cols=coverage bins).
- Deploy Integration: Hook into GitHub Actions/Jenkins: run this script, post heatmap as PR comment.
- Interactive: Use Plotly (
import plotly.express as px; px.imshow(pivot, color_continuous_scale='YlOrRd')).
- Advanced: Add ML (e.g., train on historical regressions) or 3D viz with Plotly.
This gives you a production-ready starting point. Paste into Jupyter/Colab to see the plot! Questions? 🕵️♂️