python
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple
import json
import matplotlib.pyplot as plt
import seaborn as sns
from scipy import stats
class SLOSuggestionEngine:
"""
Automated SLO Suggestion Engine.
Handles:
- Ingestion of golden signals data (latency, traffic, errors, saturation).
- Burn rate analysis for a given SLO target.
- Recommendations for SLO targets based on historical analysis.
Data Format (pd.DataFrame or CSV):
- timestamp: datetime (index or column)
- requests: int (traffic volume, e.g., req/s * interval)
- errors: int (error count)
- latency_p50: float (ms)
- latency_p95: float (ms)
- latency_p99: float (ms)
- cpu_util: float (0-100 %)
- mem_util: float (0-100 %)
Assumes data is aggregated over fixed intervals (e.g., 1min).
"""
def __init__(self):
self.data: pd.DataFrame = None
self.slo_history: pd.DataFrame = None # For internal caching
def ingest_golden_signals(self, data_source: str | pd.DataFrame, freq: str = '1min') -> None:
"""
Ingest golden signals data.
:param data_source: CSV file path, JSON file path, or pd.DataFrame.
:param freq: Resampling frequency if needed (e.g., '1min').
"""
if isinstance(data_source, str):
if data_source.endswith('.csv'):
self.data = pd.read_csv(data_source, parse_dates=['timestamp'], index_col='timestamp')
elif data_source.endswith('.json'):
self.data = pd.read_json(data_source, parse_dates=['timestamp'])
else:
raise ValueError("Unsupported file format. Use CSV or JSON.")
elif isinstance(data_source, pd.DataFrame):
self.data = data_source.set_index('timestamp') if 'timestamp' in data_source.columns else data_source
else:
raise ValueError("data_source must be str (path) or pd.DataFrame.")
# Ensure required columns
required = ['requests', 'errors', 'latency_p50', 'latency_p95', 'latency_p99', 'cpu_util', 'mem_util']
missing = [col for col in required if col not in self.data.columns]
if missing:
raise ValueError(f"Missing columns: {missing}")
# Forward fill small gaps, resample if needed
self.data = self.data.resample(freq).ffill().fillna(method='bfill')
# Compute availability
self.data['availability'] = 1.0 - (self.data['errors'] / self.data['requests'].replace(0, np.nan))
self.data['availability'] = self.data['availability'].fillna(1.0)
self.data['error_rate'] = 1.0 - self.data['availability']
# Saturation (max of cpu/mem)
self.data['saturation'] = np.maximum(self.data['cpu_util'], self.data['mem_util'])
print(f"Ingested {len(self.data)} records from {self.data.index.min()} to {self.data.index.max()}")
def burn_analysis(self, slo_target: float = 0.999, windows: List[int] = [5, 30, 120, 360, 1440]) -> Dict:
"""
Perform SLO burn rate analysis over rolling windows (minutes).
Burn rate = observed_error_rate / error_budget_rate, where error_budget_rate = 1 - slo_target
:param slo_target: SLO target (e.g., 0.999 for 99.9%)
:param windows: List of window sizes in minutes.
:return: Dict with burn rates per window.
"""
if self.data is None:
raise ValueError("Ingest data first with ingest_golden_signals()")
error_budget_rate = 1 - slo_target
results = {}
for w_min in windows:
window = f'{w_min}min'
rolled_errors = self.data['errors'].rolling(window).sum()
rolled_requests = self.data['requests'].rolling(window).sum()
rolled_error_rate = rolled_errors / rolled_requests.replace(0, np.nan)
rolled_error_rate = rolled_error_rate.fillna(0)
burn_rate = rolled_error_rate / error_budget_rate
results[window] = {
'mean_burn': burn_rate.mean(),
'p95_burn': burn_rate.quantile(0.95),
'p99_burn': burn_rate.quantile(0.99),
'max_burn': burn_rate.max(),
'times_high_burn': (burn_rate > 10).sum(), # Critical burn >10x
'burn_series': burn_rate # For plotting
}
# SLO classification (SRE style)
recent_p95 = results['6H']['p95_burn'] # 6h window common for classification
if recent_p95 > 100:
slo_status = "SEV-0: Emergency"
elif recent_p95 > 10:
slo_status = "SEV-1: Alert"
elif recent_p95 > 1:
slo_status = "Warning"
else:
slo_status = "Healthy"
results['slo_status'] = slo_status
self.slo_history = self.data.copy() # Cache for recommendations
return results
def recommend_targets(self, lookback_days: int = 30, headroom_factor: float = 3.0) -> Dict:
"""
Recommend SLO targets based on historical golden signals.
- Availability SLO: 1 - (headroom_factor * historical p99 error_rate)
- Latency SLOs: Historical p95 of p99/p95/p50 latency (conservative)
- Saturation alert: 80% of historical p95 saturation
- Includes stability check: % time SLO would be met.
:param lookback_days: Analyze last N days.
:param headroom_factor: Multiplier for error budget headroom (SRE: ~3-5x).
:return: Dict of recommendations.
"""
if self.data is None:
raise ValueError("Ingest data first with ingest_golden_signals()")
end = self.data.index.max()
start = end - timedelta(days=lookback_days)
hist_data = self.data[start:end].dropna()
if len(hist_data) == 0:
raise ValueError("No data in lookback period.")
# Availability SLO
hist_error_rate = hist_data['error_rate']
p99_error = hist_error_rate.quantile(0.99)
suggested_error_budget = headroom_factor * p99_error
suggested_error_budget = min(suggested_error_budget, 0.01) # Cap at ~99%
avail_slo = 1 - suggested_error_budget
# Backtest: % days met
daily_avail = hist_data['availability'].resample('D').mean()
met_pct = (daily_avail >= avail_slo).mean() * 100
# Latency SLOs (percentile SLOs)
lat_p50_slo = hist_data['latency_p50'].quantile(0.95)
lat_p95_slo = hist_data['latency_p95'].quantile(0.95)
lat_p99_slo = hist_data['latency_p99'].quantile(0.95)
# Saturation SLO (capacity headroom)
sat_p95 = hist_data['saturation'].quantile(0.95)
sat_slo = sat_p95 * 0.8 # Alert at 80% of p95
# Traffic growth (for scaling SLO)
daily_traffic = hist_data['requests'].resample('D').sum()
traffic_cagr = (daily_traffic.iloc[-1] / daily_traffic.iloc[0]) ** (1 / lookback_days) - 1
recommendations = {
'availability_slo': f"{avail_slo:.4f} ({avail_slo*100:.2f}%)",
'backtest_met_pct': f"{met_pct:.1f}% of days",
'latency_slo': {
'p50': f"{lat_p50_slo:.0f}ms",
'p95': f"{lat_p95_slo:.0f}ms",
'p99': f"{lat_p99_slo:.0f}ms"
},
'saturation_slo': f"Alert at {sat_slo:.0f}% utilization",
'traffic_growth_cagr': f"{traffic_cagr*100:.1f}% / {lookback_days}d (scale accordingly)",
'historical_stats': {
'error_rate_p99': f"{p99_error:.6f}",
'latency_p99_p95': f"{lat_p99_slo:.0f}ms"
}
}
return recommendations
def generate_report(self, slo_target: float = 0.999, lookback_days: int = 30, plot: bool = True) -> str:
"""
Generate a full report with burn analysis and recommendations.
Optionally plots burn rates.
"""
burn = self.burn_analysis(slo_target)
recs = self.recommend_targets(lookback_days)
report = {
'burn_analysis': burn,
'recommendations': recs,
'data_summary': {
'period': f"{self.data.index.min()} to {self.data.index.max()}",
'total_requests': int(self.data['requests'].sum()),
'total_errors': int(self.data['errors'].sum())
}
}
# Pretty print
print("=== SLO Suggestion Engine Report ===\n")
print("Burn Analysis:")
print(json.dumps({k: {sk: sv for sk, sv in v.items() if sk != 'burn_series'} for k, v in burn.items()}, indent=2))
print("\nRecommended Targets:")
print(json.dumps(recs, indent=2))
print("\nData Summary:")
print(json.dumps(report['data_summary'], indent=2))
if plot:
self._plot_burn_rates(burn)
return json.dumps(report, indent=2, default=str)
def _plot_burn_rates(self, burn: Dict):
"""Internal: Plot burn rates for windows."""
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
axes = axes.ravel()
for i, (window, data) in enumerate(burn.items()):
if i >= 4: break
data['burn_series'].tail(1000).plot(ax=axes[i], title=f'Burn Rate - {window}')
axes[i].axhline(1, color='g', linestyle='--', label='1x')
axes[i].axhline(10, color='y', linestyle='--', label='10x')
axes[i].legend()
plt.tight_layout()
plt.show()
def export_data(self, path: str):
"""Export processed data to CSV."""
self.data.to_csv(path)
print(f"Exported to {path}")
# Example Usage with Sample Data
if __name__ == "__main__":
# Generate sample data (30 days, 1min intervals)
np.random.seed(42)
n_points = 30 * 24 * 60
timestamps = pd.date_range(start='2024-01-01', periods=n_points, freq='1min')
requests = np.random.poisson(1000, n_points) + 500
errors = np.random.binomial(requests, 0.0005) # ~99.95% base
# Add bursts
burst_idx = np.random.choice(n_points, 100, replace=False)
errors[burst_idx] += np.random.poisson(100, 100)
latency_p50 = np.random.normal(50, 10, n_points)
latency_p95 = np.random.normal(200, 50, n_points)
latency_p99 = np.random.normal(500, 100, n_points)
cpu_util = np.random.normal(60, 15, n_points)
mem_util = np.random.normal(50, 20, n_points)
sample_df = pd.DataFrame({
'timestamp': timestamps,
'requests': requests,
'errors': errors,
'latency_p50': np.maximum(latency_p50, 0),
'latency_p95': np.maximum(latency_p95, 0),
'latency_p99': np.maximum(latency_p99, 0),
'cpu_util': np.clip(cpu_util, 0, 100),
'mem_util': np.clip(mem_util, 0, 100)
})
# Create engine
engine = SLOSuggestionEngine()
engine.ingest_golden_signals(sample_df)
# Generate report
report = engine.generate_report(slo_target=0.999, lookback_days=7)
# Save data
engine.export_data('golden_signals_processed.csv')
This engine is production-ready for basic use; extend for alerts (e.g., PagerDuty) or ML forecasting.