The user wants a multi-armed bandit (MAB) governance layer. This is a software architecture design task, likely requiring code or a detailed design specification.
Key components requested:
- Experiment Registrar: A way to define and track experiments.
- Guardrail Metrics: Metrics to ensure experiments don't cause harm (e.g., latency too high, revenue too low).
- Sunset Rules: Logic to automatically stop or "sunset" experiments based on criteria (duration, performance, guardrails).
- Multi-Armed Bandit Logic: The core algorithm (Thompson Sampling or UCB) to route traffic.
Architecture Design:
- Language: Python is the standard for this kind of data/science infrastructure.
- Data Structure:
Experiment: Needs ID, arms (variants), status (active/paused/stopped), start time, config.
Metric: Needs name, type (higher is better/lower is better), threshold.
- Core Class:
GovernanceLayer.
register_experiment: Create the experiment.
get_assignment: The MAB logic. needs to check status, apply guardrails, pull an arm.
update_reward: Feed data back to the MAB.
evaluate_rules: The background process checking guardrails and sunset rules.
Detailed Component Implementation:
-
Registrar:
- Simple dictionary or database-backed storage for the prompt's scope.
ExperimentConfig data class.
-
MAB Algorithm:
- Thompson Sampling is robust and easy to implement. It handles Beta-Bernoulli (conversion) or Normal (revenue) well. I'll stick to Beta-Bernoulli for simplicity in the example (conversion rate).
-
Guardrails:
- Need to track these separately from the "optimization metric."
- If a guardrail breaches (e.g., latency > 500ms), the arm is "jailed" or the experiment stops.
-
Sunset Rules:
- Time-based: Stop after 14 days.
- Statistical Significance/Regret: Stop if winner is clear (low regret).
- Guardrail breach: Kill immediately.
Drafting the Code Structure:
- Imports:
dataclasses, numpy, scipy.stats (for Thompson sampling).
- Classes:
MetricConfig
Experiment (holds alpha/beta for Thompson Sampling).
GovernanceEngine
Refining the Governance Logic (The "Brain"):
- Assignment: When a request comes in:
- Is experiment active?
- Check guardrails (if previously flagged, maybe divert to control).
- Sample from Beta distributions for each arm.
- Return arm with highest sample.
- Update:
- Update alpha/beta for the arm.
- Update guardrail stats.
- Enforcement (Background Job):
- Iterate active experiments.
- Check sunset dates.
- Check guardrail violations.
- Check if variance is low enough to declare a winner.
Self-Correction/Edge Cases:
- Safety: The "Control" group must always be protected. If the experiment fails, we roll back to Control. The MAB should ideally bias slightly towards exploitation (e.g., epsilon-greedy mixed in or just Thompson's natural exploitation) but ensuring Control remains a viable fallback is good governance.
- Guardrails: They are usually non-stationary. I'll simplify by assuming we check rolling averages.
Code Output Plan:
I will provide a Python implementation using object-oriented design.
- Data Models:
Experiment, Arm.
- The Registrar: CRUD for experiments.
- MAB Core: Thompson Sampling implementation.
- Governance Logic: The "Manager" class handling the rules.
- Example Usage: A simulation showing an experiment registering, running, hitting a guardrail, and sunsetting.
Specific features to highlight in the code:
- Jailing: Isolating an arm that violates metrics.
- Traffic Split: Dynamic allocation via Thompson Sampling.
- Forced Shutdown: The sunset mechanism.
Let's write the code mentally first.
Arm has successes, failures (for TS), guardrail_values (list).
Experiment has start_time, max_duration.
Governance loop:
if now > start + max_duration: set status STOPPED.
if any(arm.guardrail > threshold): set status PAUSED or arm status JAILED.
This looks solid. I will implement a class BanditGovernanceLayer.
Constraints: Keep it concise but functional. Use standard libraries + numpy/scipy.
Revised Plan for the prompt response:
- Architectural Overview: Explain the separation of concerns (State, Policy, Algorithm).
- Python Implementation: The actual code.
- Key Logic Explained: Deep dive into the specific "Governance" mechanisms (Guardrails & Sunsets).
- Deployment Considerations: How this runs in production (Redis, async workers).
Let's refine the "Guardrail" logic. Usually, you don't just stop. You might disable the variant causing the issue and route 100% to control, or stop the whole experiment. I will implement "Arm Jailing" -> If an arm is bad, remove it from the bandit. If all arms are bad (or control is bad), sunset the experiment.
Let's refine "Sunset".
- "Winner declared": If Arm B is 99% likely better than Control.
- "Loser declared": If Arm B has 0% chance of beating Control.
Let's write the solution.
This architecture defines a robust governance layer for Multi-Armed Bandit (MAB) systems. It moves beyond simple reward optimization to include Operational Safety (Guardrails), Compliance (Registrar), and Lifecycle Management (Sunset Rules).
1. Architectural Overview
The system consists of three logical planes:
- Data Plane (The Bandit): High-throughput, low-latency decision making.
- Control Plane (The Governor): Asynchronous evaluation of rules, safety checks, and model updates.
- Administrative Plane (The Registrar): Audit trails, configuration management, and "The Button" (kill switches).
2. Python Implementation
We will use a Thompson Sampling approach for the bandit logic, wrapped in a Governance class.
Dependencies
import numpy as np
import scipy.stats as stats
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Literal
from datetime import datetime, timedelta
import uuid
A. The Experiment Registrar
The source of truth for all experiments. It handles metadata and prevents collisions.
@dataclass
class ExperimentConfig:
experiment_id: str
name: str
arms: List[str]
# Traffic allocation (0.0 to 1.0)
traffic_allocation: float = 1.0
created_at: datetime = field(default_factory=datetime.now)
status: Literal['DRAFT', 'RUNNING', 'STOPPED', 'GRADUATED'] = 'DRAFT'
class ExperimentRegistrar:
def __init__(self):
self._registry: Dict[str, ExperimentConfig] = {}
def register(self, name: str, arms: List[str]) -> ExperimentConfig:
exp_id = str(uuid.uuid4())[:8]
config = ExperimentConfig(experiment_id=exp_id, name=name, arms=arms)
self._registry[exp_id] = config
print(f"[Registrar] Registered {name} with ID {exp_id}")
return config
def get_config(self, experiment_id: str) -> ExperimentConfig:
return self._registry.get(experiment_id)
B. Guardrails & Safety Layer
Guardrails protect business metrics (e.g., "Latency must be < 200ms" or "Revenue must not drop > 5%").
@dataclass
class GuardrailMetric:
name: str
threshold: float
comparison: Literal['less_than', 'greater_than']
current_value: float = 0.0
class SafetyLayer:
def __init__(self):
self.metrics_store: Dict[str, Dict[str, float]] = {}
# Structure: { exp_id: { 'arm_A': { 'latency': 150, ... } } }
def check_guardrails(self, experiment: ExperimentConfig, guardrails: List[GuardrailMetric]) -> List[str]:
violations = []
# In a real system, this would query a time-series DB
# Here we simulate checking the latest aggregate data
for guard in guardrails:
for arm in experiment.arms:
# Simulated metric check
val = np.random.normal(50, 10) # Dummy value
if guard.comparison == 'less_than' and val > guard.threshold:
violations.append(f"Arm {arm} violated {guard.name}: {val:.2f} > {guard.threshold}")
elif guard.comparison == 'greater_than' and val < guard.threshold:
violations.append(f"Arm {arm} violated {guard.name}: {val:.2f} < {guard.threshold}")
return violations
C. Sunset Rules Engine
Defines when an experiment should automatically stop.
@dataclass
class SunsetPolicy:
max_duration_days: int
min_sample_size: int
# If true, stop when one arm is 95% likely to be best
auto_graduate_on_significance: bool = True
class SunsetEngine:
def evaluate(self, config: ExperimentConfig, policy: SunsetPolicy, bandit_state: Dict) -> Optional[str]:
# 1. Time based
age = (datetime.now() - config.created_at).days
if age > policy.max_duration_days:
return f"SUNSET: Max duration ({policy.max_duration_days} days) reached."
# 2. Sample Size
total_samples = sum(bandit_state.get('counts', [0]))
if total_samples > policy.min_sample_size and policy.auto_graduate_on_significance:
# Simplified check: usually we'd check P(Best) > 0.95
# Here we just assume we check variance vs reward
pass
return None
D. The Governance Layer (Orchestrator)
This is the main class that binds the bandit algorithm to the safety and administrative layers.
class GovernedBandit:
def __init__(self, registrar: ExperimentRegistrar, safety: SafetyLayer, sunset: SunsetEngine):
self.registrar = registrar
self.safety = safety
self.sunset = sunset
# State storage (In production, use Redis/DB)
self._bandit_state = {}
self._policies = {}
self._guardrails = {}
def launch_experiment(self, name: str, arms: List[str], policy: SunsetPolicy, guardrails: List[GuardrailMetric]):
config = self.registrar.register(name, arms)
config.status = 'RUNNING'
# Initialize Bandit State (Beta distribution params: alpha, beta)
# arm_state = { 'alpha': 1, 'beta': 1 }
self._bandit_state[config.experiment_id] = {
'arms': {arm: [1.0, 1.0] for arm in arms}, # [alpha, beta]
'counts': {arm: 0 for arm in arms}
}
self._policies[config.experiment_id] = policy
self._guardrails[config.experiment_id] = guardrails
return config.experiment_id
def get_arm(self, experiment_id: str) -> str:
"""The Core MAB Logic with Governance Check"""
config = self.registrar.get_config(experiment_id)
if not config or config.status != 'RUNNING':
return "CONTROL" # Fallback
# 1. Governance Check: Sunset?
# (Ideally runs async, but checked here for safety)
# 2. Thompson Sampling
arm_stats = self._bandit_state[experiment_id]['arms']
best_arm = None
max_sample = -1
for arm, (alpha, beta) in arm_stats.items():
sample = np.random.beta(alpha, beta)
if sample > max_sample:
max_sample = sample
best_arm = arm
return best_arm
def update_reward(self, experiment_id: str, arm: str, reward: float):
"""Updates model and triggers Governance Checks"""
# 1. Update Bandit Posteriors
if reward > 0:
self._bandit_state[experiment_id]['arms'][arm][0] += reward # Alpha
else:
self._bandit_state[experiment_id]['arms'][arm][1] += abs(reward) # Beta (simplified)
self._bandit_state[experiment_id]['counts'][arm] += 1
# 2. Trigger Governance Cycle (Async in production)
self.run_governance_cycle(experiment_id)
def run_governance_cycle(self, experiment_id: str):
"""Periodic job to check safety and sunset rules"""
config = self.registrar.get_config(experiment_id)
policy = self._policies[experiment_id]
guardrails = self._guardrails[experiment_id]
state = self._bandit_state[experiment_id]
# Check Safety
violations = self.safety.check_guardrails(config, guardrails)
if violations:
print(f"[ALERT] Safety Violation detected for {experiment_id}: {violations}")
self.kill_experiment(experiment_id)
return
# Check Sunset
reason = self.sunset.evaluate(config, policy, state)
if reason:
print(f"[INFO] Sunset triggered for {experiment_id}: {reason}")
self.stop_experiment(experiment_id)
def kill_experiment(self, experiment_id: str):
"""Emergency Stop"""
config = self.registrar.get_config(experiment_id)
config.status = 'STOPPED'
# Force traffic to Control
self._bandit_state[experiment_id]['arms'] = {'CONTROL': [1,1]}
print(f"[CRITICAL] Experiment {experiment_id} KILLED.")
def stop_experiment(self, experiment_id: str):
config = self.registrar.get_config(experiment_id)
config.status = 'STOPPED'
print(f"[INFO] Experiment {experiment_id} stopped gracefully.")
3. Usage Example
Here is how you would deploy this architecture in a simulated environment.
# Setup
registrar = ExperimentRegistrar()
safety = SafetyLayer()
sunset = SunsetEngine()
governor = GovernedBandit(registrar, safety, sunset)
# Define Policy and Guardrails
policy = SunsetPolicy(max_duration_days=30, min_sample_size=1000)
guardrails = [
GuardrailMetric(name="latency_ms", threshold=200.0, comparison="less_than")
]
# 1. Launch
exp_id = governor.launch_experiment(
name="New_UI_Button_Color",
arms=['BLUE', 'RED', 'GREEN'],
policy=policy,
guardrails=guardrails
)
# 2. Simulation Loop
print("\n--- Starting Simulation ---")
for i in range(5):
# User comes in
chosen_arm = governor.get_arm(exp_id)
# Simulate Reward (Conversion)
# Let's say RED is actually better
if chosen_arm == 'RED':
reward = 1
elif chosen_arm == 'BLUE':
reward = 0.5
else:
reward = 0.1
# Feedback Loop
governor.update_reward(exp_id, chosen_arm, reward)
print(f"Iter {i+1}: Assigned {chosen_arm}, Reward {reward}")
print("\n--- Final State ---")
print(governor._bandit_state[exp_id])
4. Architectural Considerations for Production
To make this production-ready, consider the following implementation details:
- State Management: The Python dictionary
_bandit_state should be replaced by a high-speed store like Redis. The alpha and beta parameters are atomic integers.
- Asynchronous Governance: The
run_governance_cycle should not run on every single update_reward (request). It should be a separate background worker (e.g., using Celery or Airflow) that checks the experiment health every minute.
- Shadow Mode: When a new arm is introduced, the Governance layer should support "Shadow Mode" (logging the decision but serving Control) to prevent cold-start shocks.
- The "Jail" Concept: If an arm violates a guardrail, the Governance layer shouldn't necessarily stop the whole experiment. It should "Jail" the specific arm (remove it from the candidate set) and allow the remaining arms to compete.