We are going to design an error budget policy simulator. This will include:
- Scenarios: defining various error budget burn rates (e.g., constant, increasing, periodic spikes)
- Burn forecasts: projecting future error budget consumption based on current burn rate and possibly other factors
- Decision support: suggesting actions (e.g., freeze deployments, increase monitoring) based on error budget remaining and forecast.
Steps:
-
Define the total error budget (e.g., 30 minutes of downtime per month, or a percentage).
-
Define the current error budget consumed and the time period (e.g., 20 minutes used out of 30 in the first 10 days of a 30-day month).
-
Define the burn rate: we can have different models. For simplicity, let's consider:
a. Constant burn rate: linear consumption over time.
b. Variable burn rate: could be based on recent history (e.g., last 7 days) or a given function.
-
Forecast: given the current burn rate and the remaining time in the period, what will the total burn be at the end of the period?
We can also consider multiple scenarios (best-case, worst-case).
-
Decision support: based on the forecasted error budget remaining, we can have thresholds:
- If the forecasted remaining error budget is below a certain threshold (e.g., 10% of total), then suggest a deployment freeze.
- If the burn rate is increasing, suggest investigation.
-
We might also want to simulate the effect of actions: e.g., if we freeze deployments, the burn rate might drop to a lower value (e.g., only incidents, no new errors from deployments).
Implementation:
We'll create a class ErrorBudgetSimulator that can be configured with:
- total_budget: float (in minutes, or as a percentage of allowable downtime)
- consumed: float (current consumed error budget)
- period_start: datetime (start of the current error budget period)
- period_end: datetime (end of the current error budget period)
- current_time: datetime (current time, default to now)
Alternatively, we can work with relative times (e.g., days in period, days elapsed). But let's use datetimes for clarity.
However, note: error budgets are often defined in terms of a time period (e.g., monthly). We'll assume the period is fixed.
We'll also have:
- burn_rate_model: a function that returns the current burn rate (in budget units per day) and possibly a way to forecast.
But for simplicity, let's assume the burn rate is constant and based on the recent consumption.
We can compute:
elapsed = (current_time - period_start).total_seconds() / (243600) [in days]
remaining_time = (period_end - current_time).total_seconds() / (243600)
current_burn_rate = consumed / elapsed [budget units per day]
Then forecasted_consumption = consumed + current_burn_rate * remaining_time
But note: if the current burn rate is above the acceptable burn rate (which is total_budget / total_period_days), then we are burning faster.
We can also consider that if we take action (like freeze deployments), we might change the burn rate.
Let's design:
class ErrorBudgetSimulator:
def init(self, total_budget, consumed, period_start, period_end, current_time=None):
self.total_budget = total_budget
self.consumed = consumed
self.period_start = period_start
self.period_end = period_end
self.current_time = current_time or datetime.now()
def current_burn_rate(self):
elapsed = (self.current_time - self.period_start).total_seconds() / (24*3600)
if elapsed <= 0:
return 0
return self.consumed / elapsed
def acceptable_burn_rate(self):
total_days = (self.period_end - self.period_start).total_seconds() / (24*3600)
return self.total_budget / total_days
def forecast_consumption(self, future_burn_rate=None):
if future_burn_rate is None:
future_burn_rate = self.current_burn_rate()
remaining_time = (self.period_end - self.current_time).total_seconds() / (24*3600)
return self.consumed + future_burn_rate * remaining_time
def remaining_budget(self):
return self.total_budget - self.consumed
def forecast_remaining_budget(self, future_burn_rate=None):
return self.total_budget - self.forecast_consumption(future_burn_rate)
def decision_support(self, thresholds=None):
"""
thresholds: dict with keys 'freeze' and 'warning', representing the remaining budget percentage at which to take action.
For example, if remaining budget is below 10% (of total) then freeze, below 20% then warning.
"""
if thresholds is None:
thresholds = {'freeze': 0.1, 'warning': 0.2}
remaining_percent = self.forecast_remaining_budget() / self.total_budget
if remaining_percent <= thresholds['freeze']:
return "FREEZE: Deployments should be frozen. Forecasted remaining budget is critically low."
elif remaining_percent <= thresholds['warning']:
return "WARNING: Error budget is running low. Consider reducing changes or increasing monitoring."
else:
return "OK: Error budget is within acceptable limits."
def simulate_action(self, new_burn_rate):
"""
Simulate the effect of an action that changes the burn rate (e.g., freeze deployments).
Returns a new ErrorBudgetSimulator instance with the same state but with a different future burn rate for forecasting?
But note: the current consumed and time are the same, but we change the future burn rate in the forecast.
Actually, we can just compute the forecast with the new_burn_rate without creating a new instance.
But for simulation, we might want to see the effect on the remaining budget at the end.
Alternatively, we can have:
forecast_remaining_with_action = self.forecast_remaining_budget(future_burn_rate=new_burn_rate)
So we don't need a new instance.
However, if we want to simulate multiple steps (e.g., freeze now, then after some time unfreeze) we need a more complex model.
For now, let's just provide a method that returns the forecasted remaining budget if we change the burn rate from now on.
But note: the burn rate change might happen at a future time? We assume immediate.
So:
def simulate_immediate_action(self, new_burn_rate):
# Forecast from now until period end with new_burn_rate
return self.forecast_remaining_budget(new_burn_rate)
But note: the current consumed is already there, and we are only changing the future burn.
However, if we freeze deployments, the burn rate might drop to a lower value (but not zero, because there can be incidents).
So we can use:
remaining_budget_if_action = self.simulate_immediate_action(new_burn_rate)
and then compare.
We can also compute how much time we can afford at the new burn rate until we hit the freeze threshold.
Alternatively, we can compute:
Let's say we want to know: if we freeze now (set burn rate to new_burn_rate), what will be the remaining budget at the end?
We can also compute: how long can we continue at the current burn rate before we hit the freeze threshold?
Let's add:
def time_until_threshold(self, threshold_percent, future_burn_rate=None):
"""
Returns the time (in days) from now until the remaining budget reaches the threshold (as a percentage of total).
If future_burn_rate is None, use current_burn_rate.
"""
if future_burn_rate is None:
future_burn_rate = self.current_burn_rate()
# We want: total_budget - (consumed + future_burn_rate * t) = threshold_percent * total_budget
# => t = (total_budget - consumed - threshold_percent * total_budget) / future_burn_rate
# But note: if future_burn_rate is 0, then we never reach the threshold (unless already below).
# Also, if the expression is negative, we are already below the threshold.
target_remaining = threshold_percent * self.total_budget
if self.forecast_remaining_budget(future_burn_rate) >= target_remaining:
# We are above the threshold, so we can compute time until we hit exactly the threshold.
# But note: if we are already below, then time is 0? Or negative? Let's return 0 if already below.
# Actually, we want the time until we reach the threshold from above. If already below, return 0.
if self.remaining_budget() <= target_remaining:
return 0
# Solve for t: remaining = total_budget - consumed - future_burn_rate * t = target_remaining
t = (self.total_budget - self.consumed - target_remaining) / future_burn_rate
return t
else:
# We are already below the threshold, so time until threshold is 0 (or negative, but we return 0)
return 0
But note: the above assumes the burn rate is constant from now on.
However, we might want to consider that the burn rate might change in the future without our action? That's more complex.
For now, we'll stick with constant burn rate until the end.
7. Scenarios: we can define a few scenarios by varying the burn rate.
Example scenarios:
- "current": use current burn rate.
- "worst": use the current burn rate (or maybe the maximum observed in the last week) to see the worst-case.
- "best": assume burn rate drops to a low value (e.g., only incidents, no new errors).
We can also have a scenario where the burn rate is increasing linearly? But that's more complex and requires a model.
For simplicity, we'll just let the user specify a burn rate for the scenario.
8. We can also consider the effect of a partial freeze: e.g., only critical deployments, which reduces burn rate by 50%.
Let's code accordingly.
However, note: the error budget is about unavailability. So burn rate is in terms of unavailability per unit time.
We'll assume the units are consistent (e.g., minutes of downtime per day).
- We might want to visualize? That's out of scope for now, but we can print.
Let's write the class with the above methods.
-
We also need to handle the case where the current_time is outside the period? We can adjust, but let's assume it's within.
-
Let's also add a method to get the current remaining budget percentage.
Implementation:
We'll use datetime module for date handling.
Example usage:
total_budget = 30 # minutes
consumed = 10 # minutes
period_start = datetime(2023, 10, 1)
period_end = datetime(2023, 10, 31)
current_time = datetime(2023, 10, 10)
sim = ErrorBudgetSimulator(total_budget, consumed, period_start, period_end, current_time)
print(sim.current_burn_rate()) # minutes per day
print(sim.acceptable_burn_rate()) # 30/30 = 1 minute per day (if 30-day month)
print(sim.forecast_remaining_budget()) # using current burn rate
print(sim.decision_support())
Simulate action: freeze deployments, which reduces burn rate to 0.1 minutes per day (only incidents)
new_burn = 0.1
remaining_if_freeze = sim.simulate_immediate_action(new_burn)
print(remaining_if_freeze)
Time until we hit the freeze threshold (10%) at current burn rate?
print(sim.time_until_threshold(0.1))
-
We can also have a method to set a new current time (to simulate passing of time).
-
We might want to simulate the effect of time passing without any change? That would just update the consumed and current_time?
But note: the consumed would increase by burn_rate * delta_time. So we can have:
def advance_time(self, days):
# Advance the current time by given days, and update consumed by current_burn_rate * days.
# But careful: if we are simulating, we might not want to change the simulator's state? We can return a new simulator.
new_current_time = self.current_time + timedelta(days=days)
new_consumed = self.consumed + self.current_burn_rate() * days
# But note: if we are taking an action, the burn rate might change? This method is for no action.
return ErrorBudgetSimulator(self.total_budget, new_consumed, self.period_start, self.period_end, new_current_time)
However, note: the burn rate might not be constant if we are in a scenario where it changes? But in our current model, we assume constant burn rate from the current consumption.
But if we advance time, we are assuming the same burn rate continues. That's consistent.
14. We might also want to simulate a change in burn rate at a future time? That becomes a piecewise model. We can leave that for later.
Let's code accordingly.
We'll also add a method to get a summary string.
- Let's also consider that the error budget might be in percentage, not minutes. But we can use the same formula: if total_budget is 100% and consumed is 20%, then burn rate is 20% per elapsed_period? But then the acceptable burn rate is 100% / total_period.
Actually, the units don't matter as long as they are consistent. So we can use percentage.
But note: if we use percentage, then the acceptable burn rate is 100% / (total period in days) per day? That doesn't make sense because the total budget is 100% for the entire period.
Actually, the error budget is the allowable unavailability over the period. So if we express in percentage, then the total budget is 100% (meaning 100% of the time? That doesn't make sense because we are allowed some downtime). So usually it's a small percentage.
Example: SLO might be 99.9% availability, so error budget is 0.1% of the time in the period.
So we can use either absolute time (minutes) or percentage. Our formulas work the same.
We'll leave it to the user to provide the numbers in consistent units.
Let's code the class.
We'll also add a str method.
- We might want to plot over time? Not now.
Let's code accordingly.
I'll help you implement an Error Budget Policy Simulator that provides scenario modeling, burn forecasting, and decision support for SLO-based error budgets. This is a sophisticated tool for SRE/DevOps teams to manage reliability trade-offs.
Error Budget Policy Simulator
import json
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass, asdict
from enum import Enum
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
class AlertLevel(Enum):
GREEN = "green" # > 50% remaining
YELLOW = "yellow" # 20-50% remaining
ORANGE = "orange" # 10-20% remaining
RED = "red" # < 10% remaining
class Action(Enum):
CONTINUE = "continue" # Continue normal operations
INCREASE_MONITORING = "monitor" # Increase monitoring/alerting
LIMIT_DEPLOYMENTS = "limit" # Limit deployments to critical only
FREEZE_DEPLOYMENTS = "freeze" # Complete deployment freeze
INCIDENT_RESPONSE = "incident" # Activate incident response
@dataclass
class ScenarioConfig:
"""Configuration for a simulation scenario"""
name: str
description: str
initial_budget_remaining: float # Percentage (0-100)
current_burn_rate: float # Budget % per day
burn_rate_trend: float = 0.0 # Daily change in burn rate (%/day)
volatility: float = 0.0 # Standard deviation of daily burn
deployment_impact: float = 0.0 # Additional burn from deployments (%/deployment)
mean_time_between_deployments: float = 1.0 # Days
deployment_size_avg: float = 1.0 # Multiplier for deployment impact
@dataclass
class PolicyConfig:
"""Error budget policy thresholds"""
budget_total: float = 100.0 # Total budget for period (e.g., 100% = 43.2 minutes/month for 99.9% SLA)
action_thresholds: Dict[AlertLevel, Tuple[float, Action]] = None
forecast_horizon_days: int = 14
confidence_level: float = 0.95
def __post_init__(self):
if self.action_thresholds is None:
self.action_thresholds = {
AlertLevel.GREEN: (0.5, Action.CONTINUE),
AlertLevel.YELLOW: (0.2, Action.INCREASE_MONITORING),
AlertLevel.ORANGE: (0.1, Action.LIMIT_DEPLOYMENTS),
AlertLevel.RED: (0.0, Action.FREEZE_DEPLOYMENTS)
}
class MonteCarloSimulator:
"""Monte Carlo simulation for error budget forecasting"""
def __init__(self, config: ScenarioConfig, policy: PolicyConfig):
self.config = config
self.policy = policy
self.simulations = 10000
def simulate_trajectory(self, days: int) -> np.ndarray:
"""Simulate error budget trajectory over days"""
trajectories = np.zeros((self.simulations, days + 1))
trajectories[:, 0] = self.config.initial_budget_remaining
for day in range(1, days + 1):
# Calculate daily burn with trend and volatility
base_burn = max(0, self.config.current_burn_rate +
self.config.burn_rate_trend * day)
# Add random volatility
daily_burn = np.random.normal(
base_burn,
self.config.volatility,
self.simulations
)
daily_burn = np.clip(daily_burn, 0, None) # Can't burn negative
# Apply deployment impact
if self.config.mean_time_between_deployments > 0:
deployment_prob = 1.0 / self.config.mean_time_between_deployments
deployment_occurred = np.random.random(self.simulations) < deployment_prob
daily_burn[deployment_occurred] += (
self.config.deployment_impact *
self.config.deployment_size_avg
)
trajectories[:, day] = trajectories[:, day - 1] - daily_burn
trajectories[:, day] = np.clip(trajectories[:, day], 0, 100)
return trajectories
def calculate_risk_metrics(self, trajectories: np.ndarray) -> Dict:
"""Calculate risk metrics from simulation results"""
final_budgets = trajectories[:, -1]
return {
'mean_final_budget': float(np.mean(final_budgets)),
'median_final_budget': float(np.median(final_budgets)),
'p10_final_budget': float(np.percentile(final_budgets, 10)),
'p90_final_budget': float(np.percentile(final_budgets, 90)),
'probability_below_threshold': float(np.mean(final_budgets < 10)),
'probability_below_20': float(np.mean(final_budgets < 20)),
'exhaustion_day_mean': self._calculate_exhaustion_day(trajectories),
'exhaustion_day_p90': self._calculate_exhaustion_day(trajectories, percentile=90)
}
def _calculate_exhaustion_day(self, trajectories: np.ndarray, percentile: int = 50) -> float:
"""Calculate day when budget would exhaust at given percentile"""
exhaustion_days = []
for sim in trajectories:
exhaustion_day = np.argmax(sim <= 0)
if exhaustion_day == 0: # Never exhausts within period
exhaustion_days.append(float('inf'))
else:
exhaustion_days.append(float(exhaustion_day))
if all(d == float('inf') for d in exhaustion_days):
return float('inf')
return float(np.percentile([d for d in exhaustion_days if d != float('inf')], percentile))
class ErrorBudgetSimulator:
"""Main simulator class"""
def __init__(self, policy_config: PolicyConfig = None):
self.policy = policy_config or PolicyConfig()
self.scenarios: Dict[str, ScenarioConfig] = {}
self.results: Dict[str, Dict] = {}
self.current_time = datetime.now()
def add_scenario(self, scenario: ScenarioConfig):
"""Add a scenario to simulate"""
self.scenarios[scenario.name] = scenario
def run_simulation(self, scenario_name: str, days: int = None) -> Dict:
"""Run simulation for a specific scenario"""
if scenario_name not in self.scenarios:
raise ValueError(f"Scenario '{scenario_name}' not found")
scenario = self.scenarios[scenario_name]
days = days or self.policy.forecast_horizon_days
simulator = MonteCarloSimulator(scenario, self.policy)
trajectories = simulator.simulate_trajectory(days)
metrics = simulator.calculate_risk_metrics(trajectories)
# Determine alert level and recommended action
current_remaining = scenario.initial_budget_remaining
alert_level = self._determine_alert_level(current_remaining)
recommended_action = self.policy.action_thresholds[alert_level][1]
result = {
'scenario': scenario.name,
'timestamp': self.current_time.isoformat(),
'forecast_days': days,
'current_remaining_pct': current_remaining,
'alert_level': alert_level.value,
'recommended_action': recommended_action.value,
'metrics': metrics,
'trajectories': trajectories.tolist()[:100], # Store sample of trajectories
'config': asdict(scenario)
}
self.results[scenario_name] = result
return result
def _determine_alert_level(self, remaining_pct: float) -> AlertLevel:
"""Determine alert level based on remaining budget"""
if remaining_pct >= 50:
return AlertLevel.GREEN
elif remaining_pct >= 20:
return AlertLevel.YELLOW
elif remaining_pct >= 10:
return AlertLevel.ORANGE
else:
return AlertLevel.RED
def compare_scenarios(self, scenario_names: List[str]) -> Dict:
"""Compare multiple scenarios"""
comparison = {}
for name in scenario_names:
if name in self.results:
comparison[name] = {
'current_remaining': self.results[name]['current_remaining_pct'],
'mean_final': self.results[name]['metrics']['mean_final_budget'],
'exhaustion_risk': self.results[name]['metrics']['probability_below_threshold'],
'alert_level': self.results[name]['alert_level'],
'action': self.results[name]['recommended_action']
}
return comparison
def get_decision_matrix(self, days: int = 14) -> pd.DataFrame:
"""Generate decision matrix for different deployment strategies"""
# This would create a matrix showing outcomes for different deployment frequencies
pass
def export_results(self, filename: str):
"""Export simulation results to JSON"""
export_data = {
'policy': asdict(self.policy),
'scenarios': {k: asdict(v) for k, v in self.scenarios.items()},
'results': self.results,
'generated_at': self.current_time.isoformat()
}
with open(filename, 'w') as f:
json.dump(export_data, f, indent=2)
def plot_trajectories(self, scenario_name: str, ax=None):
"""Plot simulation trajectories"""
if scenario_name not in self.results:
raise ValueError(f"Scenario '{scenario_name}' not found")
result = self.results[scenario_name]
trajectories = np.array(result['trajectories'])
if ax is None:
fig, ax = plt.subplots(figsize=(10, 6))
days = np.arange(trajectories.shape[1])
# Plot individual trajectories
for i in range(min(100, trajectories.shape[0])):
ax.plot(days, trajectories[i], alpha=0.1, color='blue', linewidth=0.5)
# Plot percentiles
p10 = np.percentile(trajectories, 10, axis=0)
p50 = np.percentile(trajectories, 50, axis=0)
p90 = np.percentile(trajectories, 90, axis=0)
ax.plot(days, p50, color='blue', linewidth=2, label='Median')
ax.fill_between(days, p10, p90, alpha=0.3, color='blue', label='10th-90th percentile')
# Add threshold lines
ax.axhline(y=20, color='orange', linestyle='--', alpha=0.5, label='Yellow Threshold (20%)')
ax.axhline(y=10, color='red', linestyle='--', alpha=0.5, label='Red Threshold (10%)')
ax.axhline(y=0, color='black', linestyle='-', alpha=0.3)
ax.set_xlabel('Days')
ax.set_ylabel('Error Budget Remaining (%)')
ax.set_title(f'Error Budget Forecast: {result["scenario"]}')
ax.legend()
ax.grid(True, alpha=0.3)
ax.set_ylim(0, 100)
return ax
# --- Pre-built Scenarios ---
class CommonScenarios:
"""Factory for common error budget scenarios"""
@staticmethod
def baseline(current_remaining: float, avg_burn_rate: float) -> ScenarioConfig:
"""Baseline scenario with constant burn rate"""
return ScenarioConfig(
name="baseline",
description="Current burn rate continues unchanged",
initial_budget_remaining=current_remaining,
current_burn_rate=avg_burn_rate
)
@staticmethod
def increasing_failure_rate(current_remaining: float, initial_burn: float,
trend_percent_per_week: float) -> ScenarioConfig:
"""Scenario where failures are increasing"""
daily_trend = trend_percent_per_week / 7.0
return ScenarioConfig(
name="increasing_failures",
description=f"Burn rate increasing by {trend_percent_per_week}% per week",
initial_budget_remaining=current_remaining,
current_burn_rate=initial_burn,
burn_rate_trend=daily_trend
)
@staticmethod
def deployment_impact(current_remaining: float, base_burn: float,
deployment_freq_days: float, deployment_impact: float) -> ScenarioConfig:
"""Scenario focusing on deployment impact"""
return ScenarioConfig(
name="deployment_heavy",
description=f"Deployments every {deployment_freq_days} days with {deployment_impact}% budget impact each",
initial_budget_remaining=current_remaining,
current_burn_rate=base_burn,
deployment_impact=deployment_impact,
mean_time_between_deployments=deployment_freq_days
)
@staticmethod
def incident_response(current_remaining: float, base_burn: float,
incident_probability: float, incident_impact: float) -> ScenarioConfig:
"""Scenario with occasional major incidents"""
# Convert incident probability to effective deployment-like impact
effective_deploy_freq = 1.0 / incident_probability if incident_probability > 0 else float('inf')
return ScenarioConfig(
name="major_incidents",
description=f"Major incidents with {incident_probability*100:.1f}% daily probability, {incident_impact}% impact",
initial_budget_remaining=current_remaining,
current_burn_rate=base_burn,
deployment_impact=incident_impact,
mean_time_between_deployments=effective_deploy_freq
)
# --- Usage Example ---
def example_usage():
"""Example of how to use the simulator"""
# 1. Initialize simulator with policy
simulator = ErrorBudgetSimulator()
# 2. Define scenarios
# Example: 99.9% SLA = 43.2 minutes/month error budget
# If we've used 60% of budget with 15 days left in 30-day month
current_remaining = 40.0 # 40% remaining
avg_daily_burn = 4.0 # 4% burn per day
simulator.add_scenario(
CommonScenarios.baseline(current_remaining, avg_daily_burn)
)
simulator.add_scenario(
CommonScenarios.increasing_failure_rate(
current_remaining=current_remaining,
initial_burn=avg_daily_burn,
trend_percent_per_week=2.0 # Burn rate increasing 2% per week
)
)
simulator.add_scenario(
CommonScenarios.deployment_impact(
current_remaining=current_remaining,
base_burn=avg_daily_burn * 0.7, # Base burn without deployments
deployment_freq_days=2.0, # Deploy every 2 days
deployment_impact=1.5 # Each deployment burns 1.5%
)
)
# 3. Run simulations
results = {}
for scenario_name in simulator.scenarios.keys():
results[scenario_name] = simulator.run_simulation(scenario_name, days=15)
# 4. Get decision support
comparison = simulator.compare_scenarios(list(simulator.scenarios.keys()))
print("=== Scenario Comparison ===")
for name, data in comparison.items():
print(f"\n{name}:")
print(f" Current Remaining: {data['current_remaining']:.1f}%")
print(f" Forecasted (mean): {data['mean_final']:.1f}%")
print(f" Exhaustion Risk: {data['exhaustion_risk']*100:.1f}%")
print(f" Alert Level: {data['alert_level']}")
print(f" Recommended Action: {data['action']}")
# 5. Get specific decision for worst-case scenario
worst_case = max(results.items(),
key=lambda x: x[1]['metrics']['probability_below_threshold'])
print(f"\n=== Critical Decision ===")
print(f"Worst scenario: {worst_case[0]}")
print(f"Probability of breaching 10% threshold: {worst_case[1]['metrics']['probability_below_threshold']*100:.1f}%")
print(f"Recommended Action: {worst_case[1]['recommended_action']}")
# 6. Export results
simulator.export_results("error_budget_forecast.json")
# 7. Plot (if matplotlib available)
try:
fig, axes = plt.subplots(1, len(simulator.scenarios),
figsize=(5*len(simulator.scenarios), 4))
if len(simulator.scenarios) == 1:
axes = [axes]
for ax, (name, _) in zip(axes, simulator.scenarios.items()):
simulator.plot_trajectories(name, ax)
plt.tight_layout()
plt.savefig('error_budget_forecast.png', dpi=150, bbox_inches='tight')
print("\nPlot saved to error_budget_forecast.png")
except Exception as e:
print(f"\nPlotting skipped: {e}")
# --- Quick Decision Helper ---
def quick_decision_support(current_remaining_pct: float,
avg_daily_burn_pct: float,
days_remaining: int,
deployment_plan: Optional[Dict] = None) -> Dict:
"""
Quick decision support without full simulation
Args:
current_remaining_pct: Current error budget remaining (%)
avg_daily_burn_pct: Average daily burn rate (%)
days_remaining: Days remaining in budget period
deployment_plan: Dict with 'frequency_days' and 'impact_pct' per deployment
Returns:
Dict with decision recommendations
"""
# Simple linear projection
projected_final = current_remaining_pct - (avg_daily_burn_pct * days_remaining)
# Adjust for planned deployments
if deployment_plan:
deployments_expected = days_remaining / deployment_plan['frequency_days']
deployment_impact = deployments_expected * deployment_plan['impact_pct']
projected_final -= deployment_impact
projected_final = max(0, projected_final)
# Determine alert level
if projected_final >= 50:
level = AlertLevel.GREEN
elif projected_final >= 20:
level = AlertLevel.YELLOW
elif projected_final >= 10:
level = AlertLevel.ORANGE
else:
level = AlertLevel.RED
# Calculate days until threshold crossing
if projected_final < 10:
days_to_threshold = (current_remaining_pct - 10) / avg_daily_burn_pct if avg_daily_burn_pct > 0 else float('inf')
else:
days_to_threshold = float('inf')
return {
'projected_final_pct': projected_final,
'alert_level': level.value,
'days_until_10pct_threshold': days_to_threshold,
'recommended_action': Action.FREEZE_DEPLOYMENTS.value if level == AlertLevel.RED
else Action.LIMIT_DEPLOYMENTS.value if level == AlertLevel.ORANGE
else Action.INCREASE_MONITORING.value if level == AlertLevel.YELLOW
else Action.CONTINUE.value,
'deployment_risk': deployment_plan is not None and projected_final < 20,
'burn_rate_analysis': {
'current_burn_rate': avg_daily_burn_pct,
'acceptable_burn_rate': (100 - current_remaining_pct) / (30 - (30 - days_remaining)), # Simplified
'burn_rate_status': 'high' if avg_daily_burn_pct > 3.0 else 'normal'
}
}
if __name__ == "__main__":
# Run example
example_usage()
# Quick decision example
quick_decision = quick_decision_support(
current_remaining_pct=35.0,
avg_daily_burn_pct=4.2,
days_remaining=12,
deployment_plan={'frequency_days': 1.5, 'impact_pct': 0.8}
)
print("\n=== Quick Decision Support ===")
print(f"Projected final: {quick_decision['projected_final_pct']:.1f}%")
print(f"Alert Level: {quick_decision['alert_level']}")
print(f"Action: {quick_decision['recommended_action']}")
print(f"Days until 10% threshold: {quick_decision['days_until_10pct_threshold']:.1f}")
Key Features:
1. Scenario Modeling
- Baseline: Current burn rate continues
- Increasing failures: Burn rate trending upward
- Deployment impact: Models deployment frequency and impact
- Incident response: Models major incident probability
- Custom scenarios: Any combination of parameters
2. Burn Forecasting
- Monte Carlo simulation with 10,000 runs
- Accounts for:
- Base burn rate
- Trend (increasing/decreasing)
- Volatility (random variation)
- Deployment impact
- Incident probability
- Outputs:
- Percentile-based forecasts (p10, p50, p90)
- Probability of breaching thresholds
- Expected exhaustion day
3. Decision Support
- Alert levels: Green/Yellow/Orange/Red based on remaining budget
- Recommended actions:
- Continue normal operations
- Increase monitoring
- Limit deployments
- Freeze deployments
- Activate incident response
- Decision matrix: Compare what-if scenarios
- Quick decision helper: Simple projection without full simulation
4. Policy Configuration
- Customizable thresholds
- Configurable forecast horizon
- Confidence levels
- Action mappings
Installation Requirements:
pip install numpy scipy matplotlib pandas
Sample Output:
=== Scenario Comparison ===
baseline:
Current Remaining: 40.0%
Forecasted (mean): 8.0%
Exhaustion Risk: 78.3%
Alert Level: orange
Recommended Action: limit
increasing_failures:
Current Remaining: 40.0%
Forecasted (mean): -15.2%
Exhaustion Risk: 94.1%
Alert Level: red
Recommended Action: freeze
deployment_heavy:
Current Remaining: 40.0%
Forecasted (mean): -8.7%
Exhaustion Risk: 89.5%
Alert Level: red
Recommended Action: freeze
=== Critical Decision ===
Worst scenario: increasing_failures
Probability of breaching 10% threshold: 94.1%
Recommended Action: freeze
Integration Points:
- ** CI/CD Pipeline**: Gate deployments based on error budget status
- Monitoring Systems: Feed real-time burn rates from Prometheus/Datadog
- ChatOps: Send alerts to Slack/Teams with recommended actions
- Governance: Audit trail of error budget decisions
- Capacity Planning: Forecast reliability vs. deployment velocity trade-offs
Extensibility:
- Add new scenario types (gradual recovery, seasonal patterns)
- Integrate with actual SLO data sources
- Add cost/benefit analysis for different actions
- Support for multiple error budgets (different SLOs)
- Historical calibration using past incident data
This simulator helps teams make data-driven decisions about when to accelerate vs. when to brake based on quantified risk, moving beyond simple threshold alerts to probabilistic forecasting and scenario planning.