import streamlit as st
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
# ---
# CONFIGURATION & SIMULATION LOGIC
# ---
def run_simulation(
months: int,
engineers: int,
hiring_plan: dict,
roadmap_allocation: float,
debt_allocation: float,
initial_debt: float,
slo_target: float,
new_feature_complexity: float
):
"""
Runs the month-over-month simulation.
"""
data = []
# State variables
current_debt = initial_debt # 0 to 100 (Arbitrary units)
team_size = engineers
error_budget_remaining = 100.0 # Starts at 100%
# Constants
OPERATIONS_BASE_LOAD = 0.20 # 20% of time always spent on KTLO/ops
for m in range(1, months + 1):
# 1. HIRING LOGIC
new_hires = 0
ramp_up_drag = 0.0
if str(m) in hiring_plan:
new_hires = hiring_plan[str(m)]
team_size += new_hires
# New hires reduce efficiency for first 3 months (Ramp up)
ramp_up_drag = (new_hires / team_size) * 0.5
# 2. CAPACITY CALCULATION
# Total capacity scales with team size (normalized to 10 devs = 1.0 capacity unit)
base_capacity = (team_size / 10.0) * 100
# Effective capacity is reduced by ramp up and existing tech debt
# Tech Debt Tax: High debt slows everyone down (e.g., builds take longer, hard to debug)
debt_drag = (current_debt / 100) * 0.3 # 30% drag if debt is maxed out
efficiency = max(0.1, 1.0 - ramp_up_drag - debt_drag)
effective_capacity = base_capacity * efficiency
# 3. ALLOCATION
# Allocation strategy (remaining % is implicit Ops/KTLO)
feature_spend = effective_capacity * (roadmap_allocation / 100)
debt_spend = effective_capacity * (debt_allocation / 100)
# 4. SIMULATE DYNAMICS
# A. Tech Debt Accumulation
# Shipping features adds complexity (debt) if not managed
debt_generated = feature_spend * (new_feature_complexity / 10)
# Paying down debt
debt_remediated = debt_spend * 1.5 # Debt work is efficient
current_debt = max(0, current_debt + debt_generated - debt_remediated)
# B. SLO / Error Budget
# Base reliability is high, but eroded by:
# 1. High Tech Debt (systemic failures)
# 2. High Feature Spend (change failure rate)
instability_factor = (current_debt * 0.1) + (feature_spend * 0.05)
# Random incident simulation
incident_hit = 0
if np.random.rand() < (current_debt / 200.0): # Higher debt = higher chance of major outage
incident_hit = np.random.uniform(5, 15) # Major outage burns 5-15% budget
# Calculate monthly budget burn
# Target SLO implies a monthly budget burn rate.
# Let's assume "Standard" burn is relative to complexity.
monthly_burn = 2.0 + instability_factor + incident_hit
error_budget_remaining -= monthly_burn
# C. Feature Output
# Velocity is proportional to spend, dampened by complexity
feature_output = feature_spend * (1 - (new_feature_complexity/20))
# RECORD STATE
data.append({
"Month": m,
"Team Size": team_size,
"Efficiency %": efficiency * 100,
"Tech Debt Level": current_debt,
"Error Budget %": max(0, error_budget_remaining),
"Feature Velocity": feature_output,
"Cumulative Features": sum([d.get("Feature Velocity", 0) for d in data]) + feature_output
})
return pd.DataFrame(data)
# ---
# STREAMLIT UI
# ---
st.set_page_config(layout="wide", page_title="SLO & Roadmap Simulator")
st.title("⚙️ Engineering Strategy & SLO Budget Simulator")
st.markdown("""
Simulate the long-term impact of roadmap pressure, hiring, and tech debt remediation on System Stability and Feature Velocity.
""")
# --- SIDEBAR: SCENARIO SETUP ---
st.sidebar.header("1. Strategic Inputs")
months = st.sidebar.slider("Simulation Duration (Months)", 6, 36, 12)
st.sidebar.subheader("Team Composition")
initial_eng = st.sidebar.number_input("Initial Engineering Team Size", 5, 100, 15)
st.sidebar.subheader("Hiring Plan (Simple)")
hiring_json = st.sidebar.text_area("Hiring Plan (JSON format {'Month': Count})", value='{"3": 2, "6": 3}')
try:
hiring_plan = eval(hiring_json)
except:
hiring_plan = {}
st.sidebar.subheader("Roadmap Strategy")
col_a, col_b = st.sidebar.columns(2)
features_alloc = col_a.slider("New Features %", 0, 100, 50, help="Focus on product roadmap")
debt_alloc = col_b.slider("Tech Debt %", 0, 100, 20, help="Focus on refactoring/platform")
# Auto-calculate Ops/KTLO
ops_alloc = 100 - features_alloc - debt_alloc
if ops_alloc < 0:
st.sidebar.error("Allocation exceeds 100%")
ops_alloc = 0
st.sidebar.metric("Implicit Ops/KTLO %", f"{ops_alloc}%")
st.sidebar.subheader("Risk Profile")
complexity = st.sidebar.slider("New Feature Complexity", 1, 10, 5, help="1 = Simple config, 10 = New distributed system architecture")
initial_debt = st.sidebar.slider("Starting Tech Debt Load", 0, 100, 20, help="How brittle is the system right now?")
# --- MAIN PANEL: EXECUTION ---
if st.button("Run Simulation"):
with st.spinner("Calculating futures..."):
df = run_simulation(
months=months,
engineers=initial_eng,
hiring_plan=hiring_plan,
roadmap_allocation=features_alloc,
debt_allocation=debt_alloc,
initial_debt=initial_debt,
slo_target=99.9,
new_feature_complexity=complexity
)
# Display KPIs
st.header("Simulation Results")
final_debt = df.iloc[-1]["Tech Debt Level"]
final_budget = df.iloc[-1]["Error Budget %"]
total_features = df.iloc[-1]["Cumulative Features"]
col1, col2, col3, col4 = st.columns(4)
col1.metric("Final Team Size", df.iloc[-1]["Team Size"])
col2.metric("End Tech Debt", f"{final_debt:.1f}", delta=f"{final_debt - initial_debt:.1f}")
col3.metric("End Error Budget", f"{final_budget:.1f}%", delta_color="inverse")
col4.metric("Total Feature Output", f"{total_features:.0f} units")
# CHARTS
# 1. The "Iron Triangle" Chart (Velocity vs Debt vs Stability)
fig = go.Figure()
# Feature Velocity (Bar)
fig.add_trace(go.Bar(
x=df['Month'], y=df['Feature Velocity'],
name='Feature Velocity', marker_color='#2ecc71', opacity=0.6,
yaxis='y'
))
# Tech Debt (Line)
fig.add_trace(go.Scatter(
x=df['Month'], y=df['Tech Debt Level'],
name='Tech Debt Level', marker_color='#e74c3c',
mode='lines+markers', yaxis='y2'
))
# Error Budget (Line)
fig.add_trace(go.Scatter(
x=df['Month'], y=df['Error Budget %'],
name='Error Budget %', marker_color='#3498db',
mode='lines+markers', yaxis='y2'
))
fig.update_layout(
title="Velocity vs. System Health",
xaxis=dict(domain=[0.1, 0.9]),
yaxis=dict(title="Velocity", side='left'),
yaxis2=dict(title="Debt / Budget Level", side='right', overlaying='y'),
barmode='group',
hovermode="x unified"
)
st.plotly_chart(fig, use_container_width=True)
# 2. Efficiency Analysis
fig_eff = px.area(df, x='Month', y='Efficiency %',
title="Team Efficiency Over Time (Impact of Hiring & Debt)",
color_discrete_sequence=['#9b59b6'])
fig_eff.update_layout(yaxis_range=[0, 100])
st.plotly_chart(fig_eff, use_container_width=True)
# 3. Raw Data
with st.expander("View Raw Simulation Data"):
st.dataframe(df.style.format({
"Efficiency %": "{:.1f}%",
"Tech Debt Level": "{:.1f}",
"Error Budget %": "{:.1f}%",
"Feature Velocity": "{:.1f}"
}))
else:
st.info("Adjust parameters in the sidebar and click 'Run Simulation' to start.")
# Explanation of metrics
st.markdown("### How the Model Works")
col_exp1, col_exp2 = st.columns(2)
with col_exp1:
st.markdown("""
**The "Tax" of Tech Debt**
- Tech Debt creates a drag on `Efficiency`.
- If debt is high, even a large team moves slowly because they are constantly fighting fires.
- Remediation work reduces debt, increasing future velocity.
""")
with col_exp2:
st.markdown("""
**The SLO Budget**
- Shipping features burns a small amount of budget (risk of bugs).
- High Tech Debt increases the probability of random outages (Chance of large budget burn).
- If Budget hits 0%, you are in violation of your SLO.
""")