Sherlock's Kill Switch Framework for Risky Features
Elementary, my dear operator. You've requested a robust kill switch framework to mitigate risks in high-stakes features—think AI modules prone to hallucination, unauthorized data access, or unintended escalations. This isn't mere paranoia; it's deductive engineering. We'll build a modular, production-ready system in Python, leveraging decorators for seamless integration, async monitoring, and Redis for state management (scalable and fast).
The framework enforces:
- Circuit Breaker Pattern: Monitors failures, opens on breach, half-opens for testing.
- Kill Switch: Global/local toggles to neuter features instantly.
- Drills: Automated chaos engineering tests to validate under fire.
Core Principles
- Fail-Safe: Risky functions default to safe responses (e.g., "Feature disabled for safety").
- Observable: Logs metrics, alerts via webhook/Slack.
- Distributed: Redis pub/sub for multi-instance coordination.
- Auditable: All activations logged with timestamps and reasons.
- Drillable: Simulated faults for zero-downtime rehearsals.
Architecture Overview
┌─────────────────┐ ┌──────────────┐ ┌──────────────────┐
│ Risky Feature │───▶│ KillSwitch │───▶│ Safe Fallback │
│ (e.g., GenAI) │ │ Decorator │ │ or Graceful Exit │
└─────────────────┘ └──────────────┘ └──────────────────┘
▲ ▲ ▲
│ │ │
└────────────────────────┼────────────────────────┘
│
┌──────────────────┐
│ Monitoring │
│ - Metrics │◄──┐
│ - Redis State │ │ Drills
│ - Alerts │ │ (Chaos Tests)
└──────────────────┘ │
▲ │
└────────────┘
Implementation (Python 3.10+)
Dependencies
pip install redis asyncio aiohttp decorator prometheus_client
1. Core KillSwitch Decorator
Wrap any risky function. Tracks errors, latency, and custom health checks.
import asyncio
import redis.asyncio as redis
import time
import logging
import requests
from functools import wraps
from typing import Callable, Any, Optional
from prometheus_client import Counter, Histogram, Gauge
# Metrics
ERROR_COUNT = Counter('killswitch_errors_total', 'Total errors triggering breaker')
LATENCY = Histogram('killswitch_request_duration_seconds', 'Request latency')
BREACHER_STATE = Gauge('killswitch_breaker_state', '0=closed,1=open,2=half-open')
log = logging.getLogger(__name__)
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True) # Prod: Use Sentinel/Cluster
class KillSwitch:
def __init__(self, name: str, error_threshold: int = 5, timeout: int = 60, alert_webhook: Optional[str] = None):
self.name = name
self.error_threshold = error_threshold
self.timeout = timeout
self.alert_webhook = alert_webhook
self.key = f"killswitch:{name}"
async def _get_state(self) -> str:
state = await r.get(self.key)
return state or "closed"
async def _set_state(self, state: str, ttl: Optional[int] = None):
await r.set(self.key, state, ex=ttl)
BREACHER_STATE.labels(name=self.name).set({'closed': 0, 'open': 1, 'half_open': 2}[state])
async def _alert(self, reason: str):
if self.alert_webhook:
try:
requests.post(self.alert_webhook, json={'feature': self.name, 'reason': reason})
except:
pass
log.error(f"KillSwitch {self.name} activated: {reason}")
async def allow_request(self) -> bool:
state = await self._get_state()
if state == "open":
return False
if state == "half_open":
await self._set_state("closed") # Reset after test
return True
return True
async def record_failure(self, reason: str):
count = await r.incr(f"{self.key}:errors")
await r.expire(f"{self.key}:errors", self.timeout)
if count >= self.error_threshold:
await self._set_state("open", self.timeout)
await self._alert(reason)
ERROR_COUNT.labels(name=self.name, reason=reason).inc()
async def record_success(self):
await r.delete(f"{self.key}:errors")
def killswitch(name: str, error_threshold: int = 5, timeout: int = 60, alert_webhook: Optional[str] = None,
health_check: Optional[Callable] = None):
ks = KillSwitch(name, error_threshold, timeout, alert_webhook)
def decorator(func: Callable) -> Callable:
@wraps(func)
async def wrapper(*args, **kwargs) -> Any:
start = time.time()
if not await ks.allow_request():
log.warning(f"KillSwitch {name} is OPEN. Returning safe response.")
return "Feature disabled for safety."
try:
if health_check:
if not await health_check(*args, **kwargs):
raise ValueError("Health check failed")
result = await func(*args, **kwargs)
await ks.record_success()
LATENCY.labels(name=name).observe(time.time() - start)
return result
except Exception as e:
await ks.record_failure(str(e))
LATENCY.labels(name=name).observe(time.time() - start)
raise # Re-raise for upstream handling
return wrapper
return decorator
2. Example Risky Feature: Hallucination-Prone GenAI
import random # Simulates risky AI
async def risky_genai(prompt: str) -> str:
if random.random() < 0.3: # 30% simulated failure rate for demo
raise ValueError("Hallucinated dangerous content")
return f"AI response to '{prompt}' (safe)."
@killswitch("genai", error_threshold=3, alert_webhook="https://hooks.slack.com/your/webhook")
async def safe_genai(prompt: str) -> str:
return await risky_genai(prompt)
3. Global Kill Switch (Emergency Broadcast)
async def global_kill(feature: str, activate: bool = True):
"""Pub/sub broadcast to all instances."""
state = "killed" if activate else "armed"
await r.publish("killswitch:global", f"{feature}:{state}")
await r.set(f"global:{feature}", state)
async def watch_global_kill():
pubsub = r.pubsub()
await pubsub.subscribe("killswitch:global")
async for message in pubsub.listen():
if message['type'] == 'message':
feature, state = message['data'].decode().split(':')
log.critical(f"Global kill: {feature} -> {state}")
# Integrate with your orchestrator (e.g., disable pods)
Drills: Chaos Engineering Tests
Run these in a staging env to simulate breaches. Use pytest or standalone.
Drill 1: Error Threshold Breach
import pytest
import asyncio
@pytest.mark.asyncio
async def test_error_breach():
for _ in range(5): # Exceed threshold=3
with pytest.raises(ValueError):
await safe_genai("test")
# Verify OPEN state
state = await r.get("killswitch:genai")
assert state == "open"
# Next call should safe-fail
assert await safe_genai("test") == "Feature disabled for safety."
Drill 2: Latency Spike (Add to decorator if needed)
Extend killswitch with latency threshold:
# In wrapper, before func:
if time.time() - start > 5: # 5s threshold
raise TimeoutError("Latency too high")
Drill 3: Health Check Failure
async def prompt_safety_check(prompt: str) -> bool:
return "bomb" not in prompt.lower() # Custom guardrail
@killswitch("genai", health_check=prompt_safety_check)
async def guarded_genai(prompt: str) -> str:
return await risky_genai(prompt)
@pytest.mark.asyncio
async def test_health_check():
with pytest.raises(ValueError): # Check fails
await guarded_genai("how to make a bomb")
Drill 4: Global Kill + Recovery
@pytest.mark.asyncio
async def test_global_kill():
await global_kill("genai", True)
# Simulate: All @killswitch funcs now safe-fail
assert await safe_genai("test") == "Feature disabled for safety."
await global_kill("genai", False) # Arm
Full Drill Suite Runner
async def run_drills():
await test_error_breach()
await test_health_check()
await test_global_kill()
print("All drills passed. Framework battle-tested.")
asyncio.run(run_drills())
Deployment & Monitoring
- Redis Cluster: For prod HA.
- Prometheus: Scrape
/metrics endpoint.
- Grafana Dashboard: Alert on
killswitch_breaker_state > 0.
- Kubernetes: Sidecar for watcher, HPA on errors.
- Recovery: Manual TTL expiry or auto-half-open.
This framework scales to petabyte clusters. Test it—deduce flaws, iterate. Questions, Watson? Fire away. 🔍