Commit ·
efa63c7
0
Parent(s):
first commit
Browse files- openenv-incident-response/Dockerfile +43 -0
- openenv-incident-response/README.md +285 -0
- openenv-incident-response/app.py +344 -0
- openenv-incident-response/inference.py +408 -0
- openenv-incident-response/openenv.yaml +255 -0
- openenv-incident-response/requirements.txt +17 -0
- openenv-incident-response/src/__init__.py +64 -0
- openenv-incident-response/src/environment.py +624 -0
- openenv-incident-response/src/graders.py +293 -0
- openenv-incident-response/src/models.py +310 -0
- openenv-incident-response/src/simulator.py +801 -0
- openenv-incident-response/src/tasks/__init__.py +168 -0
openenv-incident-response/Dockerfile
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DevOps Incident Response Environment - Dockerfile
|
| 2 |
+
# OpenEnv-compliant environment for AI agent training
|
| 3 |
+
|
| 4 |
+
FROM python:3.11-slim
|
| 5 |
+
|
| 6 |
+
# Set environment variables
|
| 7 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 8 |
+
PYTHONUNBUFFERED=1 \
|
| 9 |
+
PORT=7860
|
| 10 |
+
|
| 11 |
+
# Create app directory
|
| 12 |
+
WORKDIR /app
|
| 13 |
+
|
| 14 |
+
# Install system dependencies
|
| 15 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 16 |
+
curl \
|
| 17 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 18 |
+
|
| 19 |
+
# Copy requirements first for better caching
|
| 20 |
+
COPY requirements.txt .
|
| 21 |
+
|
| 22 |
+
# Install Python dependencies
|
| 23 |
+
RUN pip install --no-cache-dir --upgrade pip && \
|
| 24 |
+
pip install --no-cache-dir -r requirements.txt
|
| 25 |
+
|
| 26 |
+
# Copy application code
|
| 27 |
+
COPY . .
|
| 28 |
+
|
| 29 |
+
# Create non-root user for security
|
| 30 |
+
RUN useradd -m -u 1000 appuser && \
|
| 31 |
+
chown -R appuser:appuser /app
|
| 32 |
+
|
| 33 |
+
USER appuser
|
| 34 |
+
|
| 35 |
+
# Expose port
|
| 36 |
+
EXPOSE 7860
|
| 37 |
+
|
| 38 |
+
# Health check
|
| 39 |
+
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
|
| 40 |
+
CMD curl -f http://localhost:7860/health || exit 1
|
| 41 |
+
|
| 42 |
+
# Run the application
|
| 43 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
|
openenv-incident-response/README.md
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DevOps Incident Response Environment
|
| 2 |
+
|
| 3 |
+
An **OpenEnv-compliant** reinforcement learning environment for training AI agents in production incident response. This environment simulates a realistic microservices infrastructure where agents must diagnose and resolve production incidents.
|
| 4 |
+
|
| 5 |
+
## Overview
|
| 6 |
+
|
| 7 |
+
### What is this?
|
| 8 |
+
|
| 9 |
+
This environment simulates the work of a **Site Reliability Engineer (SRE)** responding to production incidents. Agents interact with a simulated microservices architecture, analyzing logs, metrics, and alerts to identify root causes and take remediation actions.
|
| 10 |
+
|
| 11 |
+
### Why is this useful?
|
| 12 |
+
|
| 13 |
+
- **Real-world applicability**: Incident response is a critical skill at every tech company
|
| 14 |
+
- **Training data scarcity**: Real incident data is sensitive and rare
|
| 15 |
+
- **Evaluation benchmark**: Standardized tasks to measure AI agent capabilities
|
| 16 |
+
- **Safe experimentation**: Learn from failures without impacting production
|
| 17 |
+
|
| 18 |
+
### Key Features
|
| 19 |
+
|
| 20 |
+
- Full **OpenEnv spec compliance** with typed Pydantic models
|
| 21 |
+
- **3 difficulty levels** from simple OOM fixes to complex multi-factor incidents
|
| 22 |
+
- **Realistic simulation** of microservices, logs, metrics, and alerts
|
| 23 |
+
- **Programmatic graders** with deterministic 0.0-1.0 scoring
|
| 24 |
+
- **Shaped rewards** with partial progress signals
|
| 25 |
+
|
| 26 |
+
## Quick Start
|
| 27 |
+
|
| 28 |
+
### Installation
|
| 29 |
+
|
| 30 |
+
```bash
|
| 31 |
+
# Clone the repository
|
| 32 |
+
git clone https://huggingface.co/spaces/openenv/devops-incident-response
|
| 33 |
+
cd devops-incident-response
|
| 34 |
+
|
| 35 |
+
# Install dependencies
|
| 36 |
+
pip install -r requirements.txt
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
### Run the Server
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
# Start the FastAPI server
|
| 43 |
+
python -m uvicorn app:app --host 0.0.0.0 --port 7860
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
### Run Inference
|
| 47 |
+
|
| 48 |
+
```bash
|
| 49 |
+
# Set your API credentials
|
| 50 |
+
export API_BASE_URL="https://api.openai.com/v1"
|
| 51 |
+
export MODEL_NAME="gpt-4o-mini"
|
| 52 |
+
export OPENAI_API_KEY="your-api-key"
|
| 53 |
+
|
| 54 |
+
# Run the baseline agent
|
| 55 |
+
python inference.py
|
| 56 |
+
```
|
| 57 |
+
|
| 58 |
+
### Docker
|
| 59 |
+
|
| 60 |
+
```bash
|
| 61 |
+
# Build the image
|
| 62 |
+
docker build -t devops-incident-response .
|
| 63 |
+
|
| 64 |
+
# Run the container
|
| 65 |
+
docker run -p 7860:7860 devops-incident-response
|
| 66 |
+
```
|
| 67 |
+
|
| 68 |
+
## Environment Details
|
| 69 |
+
|
| 70 |
+
### The Simulated Infrastructure
|
| 71 |
+
|
| 72 |
+
The environment simulates a typical e-commerce microservices architecture:
|
| 73 |
+
|
| 74 |
+
```
|
| 75 |
+
┌─────────────────┐
|
| 76 |
+
│ API Gateway │
|
| 77 |
+
└────────┬────────┘
|
| 78 |
+
│
|
| 79 |
+
┌────────────────────┼────────────────────┐
|
| 80 |
+
│ │ │
|
| 81 |
+
┌─────┴─────┐ ┌──────┴──────┐ ┌─────┴─────┐
|
| 82 |
+
│ User │ │ Order │ │ Product │
|
| 83 |
+
│ Service │ │ Service │ │ Service │
|
| 84 |
+
└─────┬─────┘ └──────┬──────┘ └─────┬─────┘
|
| 85 |
+
│ │ │
|
| 86 |
+
│ ┌──────┴──────┐ │
|
| 87 |
+
│ │ Payment │ │
|
| 88 |
+
│ │ Service │ │
|
| 89 |
+
│ └─────────────┘ │
|
| 90 |
+
│ │
|
| 91 |
+
┌─────┴─────┐ ┌─────┴─────┐
|
| 92 |
+
│ Redis │ │Elasticsearch│
|
| 93 |
+
│ Cache │ └───────────┘
|
| 94 |
+
└───────────┘
|
| 95 |
+
│
|
| 96 |
+
┌─────┴─────┐ ┌─────────────┐
|
| 97 |
+
│ PostgreSQL│ │ Kafka │
|
| 98 |
+
│ DB │ │ │
|
| 99 |
+
└───────────┘ └─────────────┘
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
### Action Space
|
| 103 |
+
|
| 104 |
+
| Action | Description | Example |
|
| 105 |
+
|--------|-------------|---------|
|
| 106 |
+
| `query_service` | Get service status and info | `query_service:order-service` |
|
| 107 |
+
| `read_logs` | Read recent log entries | `read_logs:user-service` |
|
| 108 |
+
| `get_metrics` | Get CPU, memory, latency metrics | `get_metrics:postgres-db` |
|
| 109 |
+
| `get_alerts` | Get active monitoring alerts | `get_alerts` |
|
| 110 |
+
| `run_diagnostic` | Run diagnostic checks | `run_diagnostic:redis-cache` |
|
| 111 |
+
| `restart_service` | Restart a service | `restart_service:order-service` |
|
| 112 |
+
| `scale_service` | Scale service replicas | `scale_service:api-gateway:5` |
|
| 113 |
+
| `rollback_service` | Rollback to previous version | `rollback_service:payment-service` |
|
| 114 |
+
| `update_config` | Update configuration | `update_config:order-service:JAVA_OPTS:-Xmx1024m` |
|
| 115 |
+
| `resolve_incident` | Mark incident resolved | `resolve_incident` |
|
| 116 |
+
|
| 117 |
+
### Observation Space
|
| 118 |
+
|
| 119 |
+
Each observation includes:
|
| 120 |
+
|
| 121 |
+
- **Incident Context**: Title, severity, description, affected services, customer impact
|
| 122 |
+
- **Visible Data**: Services queried, logs read, metrics fetched, alerts active
|
| 123 |
+
- **Last Action Result**: Success/failure, error messages, returned data
|
| 124 |
+
- **Available Services**: List of all services in the infrastructure
|
| 125 |
+
|
| 126 |
+
### Reward Structure
|
| 127 |
+
|
| 128 |
+
Rewards are shaped to guide learning:
|
| 129 |
+
|
| 130 |
+
| Component | Value | Description |
|
| 131 |
+
|-----------|-------|-------------|
|
| 132 |
+
| Diagnostic actions | +0.02 | Investigating affected services |
|
| 133 |
+
| Correct remediation | +0.10 | Taking required fix actions |
|
| 134 |
+
| Successful resolution | +0.30 | Fully resolving the incident |
|
| 135 |
+
| Efficiency bonus | up to +0.10 | Resolving quickly |
|
| 136 |
+
| Unnecessary actions | -0.01 | Actions not needed |
|
| 137 |
+
| Time pressure | -0.01/step | Penalty after 80% of max steps |
|
| 138 |
+
|
| 139 |
+
## Tasks
|
| 140 |
+
|
| 141 |
+
### Task 1: Memory Crisis (Easy)
|
| 142 |
+
|
| 143 |
+
**Scenario**: The order-service has been OOM killed during a traffic spike.
|
| 144 |
+
|
| 145 |
+
**Root Cause**: Java heap size too small for traffic volume.
|
| 146 |
+
|
| 147 |
+
**Solution**: Increase JAVA_OPTS heap size and restart the service.
|
| 148 |
+
|
| 149 |
+
**Max Steps**: 15
|
| 150 |
+
|
| 151 |
+
### Task 2: Database Overload (Medium)
|
| 152 |
+
|
| 153 |
+
**Scenario**: Multiple services experiencing database connection timeouts with cascading failures.
|
| 154 |
+
|
| 155 |
+
**Root Cause**: PostgreSQL max connections too low, causing connection pool exhaustion across services.
|
| 156 |
+
|
| 157 |
+
**Solution**: Increase database connections and connection pool sizes for affected services.
|
| 158 |
+
|
| 159 |
+
**Max Steps**: 25
|
| 160 |
+
|
| 161 |
+
### Task 3: Perfect Storm (Hard)
|
| 162 |
+
|
| 163 |
+
**Scenario**: Multiple alerts firing across infrastructure with several services affected.
|
| 164 |
+
|
| 165 |
+
**Root Cause**: Multiple concurrent issues - Redis cluster network partition causing cache failures, leading to database overload, PLUS an unrelated memory leak in product-service.
|
| 166 |
+
|
| 167 |
+
**Solution**: Fix Redis cluster, restart services with memory leaks, scale as needed.
|
| 168 |
+
|
| 169 |
+
**Max Steps**: 40
|
| 170 |
+
|
| 171 |
+
## API Reference
|
| 172 |
+
|
| 173 |
+
### Endpoints
|
| 174 |
+
|
| 175 |
+
| Method | Endpoint | Description |
|
| 176 |
+
|--------|----------|-------------|
|
| 177 |
+
| POST | `/reset` | Reset environment, get initial observation |
|
| 178 |
+
| POST | `/step` | Take an action, get result |
|
| 179 |
+
| GET | `/state/{session_id}` | Get full environment state |
|
| 180 |
+
| POST | `/grade` | Grade completed episode |
|
| 181 |
+
| GET | `/tasks` | List available tasks |
|
| 182 |
+
| GET | `/health` | Health check |
|
| 183 |
+
|
| 184 |
+
### Example: Running an Episode
|
| 185 |
+
|
| 186 |
+
```python
|
| 187 |
+
import requests
|
| 188 |
+
|
| 189 |
+
BASE_URL = "http://localhost:7860"
|
| 190 |
+
|
| 191 |
+
# Reset environment
|
| 192 |
+
response = requests.post(f"{BASE_URL}/reset", json={"task_id": "task_easy_oom"})
|
| 193 |
+
session_id = response.json()["session_id"]
|
| 194 |
+
observation = response.json()["observation"]
|
| 195 |
+
|
| 196 |
+
# Take actions
|
| 197 |
+
while True:
|
| 198 |
+
action = {"session_id": session_id, "action_str": "get_alerts"}
|
| 199 |
+
response = requests.post(f"{BASE_URL}/step", json=action)
|
| 200 |
+
result = response.json()
|
| 201 |
+
|
| 202 |
+
if result["done"]:
|
| 203 |
+
break
|
| 204 |
+
|
| 205 |
+
# Grade the episode
|
| 206 |
+
response = requests.post(f"{BASE_URL}/grade", json={"session_id": session_id})
|
| 207 |
+
print(f"Score: {response.json()['score']}")
|
| 208 |
+
```
|
| 209 |
+
|
| 210 |
+
## Grading
|
| 211 |
+
|
| 212 |
+
Each task is graded on three components:
|
| 213 |
+
|
| 214 |
+
1. **Diagnosis Score** (30-40%): Did the agent investigate the affected services?
|
| 215 |
+
2. **Remediation Score** (45-60%): Did the agent take the correct fix actions?
|
| 216 |
+
3. **Efficiency Score** (10-15%): How quickly was the incident resolved?
|
| 217 |
+
|
| 218 |
+
Final scores range from 0.0 to 1.0.
|
| 219 |
+
|
| 220 |
+
## Baseline Scores
|
| 221 |
+
|
| 222 |
+
| Task | GPT-4o-mini | GPT-4o |
|
| 223 |
+
|------|-------------|--------|
|
| 224 |
+
| Easy (OOM) | ~0.65 | ~0.82 |
|
| 225 |
+
| Medium (Cascade) | ~0.45 | ~0.68 |
|
| 226 |
+
| Hard (Complex) | ~0.30 | ~0.52 |
|
| 227 |
+
|
| 228 |
+
## Development
|
| 229 |
+
|
| 230 |
+
### Project Structure
|
| 231 |
+
|
| 232 |
+
```
|
| 233 |
+
devops-incident-response/
|
| 234 |
+
├── app.py # FastAPI server
|
| 235 |
+
├── inference.py # Baseline inference script
|
| 236 |
+
├── openenv.yaml # OpenEnv configuration
|
| 237 |
+
├── Dockerfile # Container definition
|
| 238 |
+
├── requirements.txt # Python dependencies
|
| 239 |
+
├── README.md # This file
|
| 240 |
+
└── src/
|
| 241 |
+
├── __init__.py # Package exports
|
| 242 |
+
├── models.py # Pydantic models
|
| 243 |
+
├── environment.py # Main environment
|
| 244 |
+
├── simulator.py # Infrastructure simulator
|
| 245 |
+
├── graders.py # Task graders
|
| 246 |
+
└── tasks/
|
| 247 |
+
└── __init__.py # Task definitions
|
| 248 |
+
```
|
| 249 |
+
|
| 250 |
+
### Running Tests
|
| 251 |
+
|
| 252 |
+
```bash
|
| 253 |
+
pytest tests/ -v
|
| 254 |
+
```
|
| 255 |
+
|
| 256 |
+
### Validation
|
| 257 |
+
|
| 258 |
+
```bash
|
| 259 |
+
# Validate OpenEnv compliance
|
| 260 |
+
openenv validate .
|
| 261 |
+
```
|
| 262 |
+
|
| 263 |
+
## Configuration
|
| 264 |
+
|
| 265 |
+
### Environment Variables
|
| 266 |
+
|
| 267 |
+
| Variable | Description | Default |
|
| 268 |
+
|----------|-------------|---------|
|
| 269 |
+
| `API_BASE_URL` | LLM API endpoint | `https://api.openai.com/v1` |
|
| 270 |
+
| `MODEL_NAME` | Model to use for inference | `gpt-4o-mini` |
|
| 271 |
+
| `OPENAI_API_KEY` | API key for LLM | Required |
|
| 272 |
+
| `HF_TOKEN` | Alternative API key | - |
|
| 273 |
+
| `PORT` | Server port | `7860` |
|
| 274 |
+
|
| 275 |
+
## License
|
| 276 |
+
|
| 277 |
+
MIT License - see LICENSE file.
|
| 278 |
+
|
| 279 |
+
## Contributing
|
| 280 |
+
|
| 281 |
+
Contributions welcome! Please open an issue or PR.
|
| 282 |
+
|
| 283 |
+
## Acknowledgments
|
| 284 |
+
|
| 285 |
+
Built for the OpenEnv Hackathon. Special thanks to Hugging Face and Meta for organizing.
|
openenv-incident-response/app.py
ADDED
|
@@ -0,0 +1,344 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FastAPI Server for DevOps Incident Response Environment.
|
| 3 |
+
|
| 4 |
+
This server exposes the OpenEnv API endpoints for the environment,
|
| 5 |
+
allowing AI agents to interact with the incident response simulation
|
| 6 |
+
via HTTP requests.
|
| 7 |
+
|
| 8 |
+
Endpoints:
|
| 9 |
+
- POST /reset - Reset the environment
|
| 10 |
+
- POST /step - Take an action
|
| 11 |
+
- GET /state - Get current state
|
| 12 |
+
- GET /tasks - List available tasks
|
| 13 |
+
- POST /grade - Grade a completed episode
|
| 14 |
+
- GET /health - Health check
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
+
import uuid
|
| 21 |
+
from contextlib import asynccontextmanager
|
| 22 |
+
from typing import Any
|
| 23 |
+
|
| 24 |
+
from fastapi import FastAPI, HTTPException
|
| 25 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 26 |
+
from pydantic import BaseModel
|
| 27 |
+
|
| 28 |
+
from src import (
|
| 29 |
+
Action,
|
| 30 |
+
EnvironmentState,
|
| 31 |
+
GradeResult,
|
| 32 |
+
IncidentResponseEnv,
|
| 33 |
+
Observation,
|
| 34 |
+
StepResult,
|
| 35 |
+
grade_task,
|
| 36 |
+
list_tasks,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# ============================================================================
|
| 41 |
+
# Session Management
|
| 42 |
+
# ============================================================================
|
| 43 |
+
|
| 44 |
+
class SessionManager:
|
| 45 |
+
"""Manages environment sessions."""
|
| 46 |
+
|
| 47 |
+
def __init__(self):
|
| 48 |
+
self.sessions: dict[str, IncidentResponseEnv] = {}
|
| 49 |
+
self.max_sessions = 100
|
| 50 |
+
|
| 51 |
+
def create_session(self, task_id: str) -> str:
|
| 52 |
+
"""Create a new session."""
|
| 53 |
+
# Clean up if too many sessions
|
| 54 |
+
if len(self.sessions) >= self.max_sessions:
|
| 55 |
+
oldest = list(self.sessions.keys())[0]
|
| 56 |
+
del self.sessions[oldest]
|
| 57 |
+
|
| 58 |
+
session_id = str(uuid.uuid4())
|
| 59 |
+
self.sessions[session_id] = IncidentResponseEnv(task_id=task_id)
|
| 60 |
+
return session_id
|
| 61 |
+
|
| 62 |
+
def get_session(self, session_id: str) -> IncidentResponseEnv | None:
|
| 63 |
+
"""Get an existing session."""
|
| 64 |
+
return self.sessions.get(session_id)
|
| 65 |
+
|
| 66 |
+
def delete_session(self, session_id: str):
|
| 67 |
+
"""Delete a session."""
|
| 68 |
+
if session_id in self.sessions:
|
| 69 |
+
del self.sessions[session_id]
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
session_manager = SessionManager()
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# ============================================================================
|
| 76 |
+
# Request/Response Models
|
| 77 |
+
# ============================================================================
|
| 78 |
+
|
| 79 |
+
class ResetRequest(BaseModel):
|
| 80 |
+
"""Request to reset the environment."""
|
| 81 |
+
task_id: str = "task_easy_oom"
|
| 82 |
+
session_id: str | None = None
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class ResetResponse(BaseModel):
|
| 86 |
+
"""Response from reset."""
|
| 87 |
+
session_id: str
|
| 88 |
+
observation: Observation
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class StepRequest(BaseModel):
|
| 92 |
+
"""Request to take a step."""
|
| 93 |
+
session_id: str
|
| 94 |
+
action: Action | None = None
|
| 95 |
+
action_str: str | None = None
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class StepResponse(BaseModel):
|
| 99 |
+
"""Response from step."""
|
| 100 |
+
observation: Observation
|
| 101 |
+
reward: float
|
| 102 |
+
done: bool
|
| 103 |
+
info: dict[str, Any]
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
class StateRequest(BaseModel):
|
| 107 |
+
"""Request for state."""
|
| 108 |
+
session_id: str
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class StateResponse(BaseModel):
|
| 112 |
+
"""Response with full state."""
|
| 113 |
+
state: EnvironmentState
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class GradeRequest(BaseModel):
|
| 117 |
+
"""Request to grade an episode."""
|
| 118 |
+
session_id: str
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class GradeResponse(BaseModel):
|
| 122 |
+
"""Response with grade."""
|
| 123 |
+
score: float
|
| 124 |
+
diagnosis_score: float
|
| 125 |
+
remediation_score: float
|
| 126 |
+
efficiency_score: float
|
| 127 |
+
details: dict[str, Any]
|
| 128 |
+
feedback: str
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class TaskInfo(BaseModel):
|
| 132 |
+
"""Information about a task."""
|
| 133 |
+
id: str
|
| 134 |
+
name: str
|
| 135 |
+
difficulty: str
|
| 136 |
+
description: str
|
| 137 |
+
max_steps: int
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class TasksResponse(BaseModel):
|
| 141 |
+
"""Response with list of tasks."""
|
| 142 |
+
tasks: list[TaskInfo]
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class HealthResponse(BaseModel):
|
| 146 |
+
"""Health check response."""
|
| 147 |
+
status: str
|
| 148 |
+
version: str
|
| 149 |
+
sessions_active: int
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
# ============================================================================
|
| 153 |
+
# Application
|
| 154 |
+
# ============================================================================
|
| 155 |
+
|
| 156 |
+
@asynccontextmanager
|
| 157 |
+
async def lifespan(app: FastAPI):
|
| 158 |
+
"""Application lifespan handler."""
|
| 159 |
+
# Startup
|
| 160 |
+
print("DevOps Incident Response Environment starting...")
|
| 161 |
+
yield
|
| 162 |
+
# Shutdown
|
| 163 |
+
print("Shutting down...")
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
app = FastAPI(
|
| 167 |
+
title="DevOps Incident Response Environment",
|
| 168 |
+
description="An OpenEnv-compliant environment for training AI agents in production incident response",
|
| 169 |
+
version="1.0.0",
|
| 170 |
+
lifespan=lifespan,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
# CORS middleware for web clients
|
| 174 |
+
app.add_middleware(
|
| 175 |
+
CORSMiddleware,
|
| 176 |
+
allow_origins=["*"],
|
| 177 |
+
allow_credentials=True,
|
| 178 |
+
allow_methods=["*"],
|
| 179 |
+
allow_headers=["*"],
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
# ============================================================================
|
| 184 |
+
# Endpoints
|
| 185 |
+
# ============================================================================
|
| 186 |
+
|
| 187 |
+
@app.get("/", response_model=HealthResponse)
|
| 188 |
+
async def root():
|
| 189 |
+
"""Root endpoint - returns health status."""
|
| 190 |
+
return HealthResponse(
|
| 191 |
+
status="healthy",
|
| 192 |
+
version="1.0.0",
|
| 193 |
+
sessions_active=len(session_manager.sessions),
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
@app.get("/health", response_model=HealthResponse)
|
| 198 |
+
async def health():
|
| 199 |
+
"""Health check endpoint."""
|
| 200 |
+
return HealthResponse(
|
| 201 |
+
status="healthy",
|
| 202 |
+
version="1.0.0",
|
| 203 |
+
sessions_active=len(session_manager.sessions),
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
@app.get("/tasks", response_model=TasksResponse)
|
| 208 |
+
async def get_tasks():
|
| 209 |
+
"""List all available tasks."""
|
| 210 |
+
tasks = list_tasks()
|
| 211 |
+
return TasksResponse(
|
| 212 |
+
tasks=[TaskInfo(**t) for t in tasks]
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@app.post("/reset", response_model=ResetResponse)
|
| 217 |
+
async def reset(request: ResetRequest):
|
| 218 |
+
"""
|
| 219 |
+
Reset the environment to initial state.
|
| 220 |
+
|
| 221 |
+
Creates a new session or resets an existing one.
|
| 222 |
+
"""
|
| 223 |
+
try:
|
| 224 |
+
# Create or get session
|
| 225 |
+
if request.session_id and request.session_id in session_manager.sessions:
|
| 226 |
+
session_id = request.session_id
|
| 227 |
+
env = session_manager.sessions[session_id]
|
| 228 |
+
env.task_id = request.task_id
|
| 229 |
+
env.task = env.task # Reload task
|
| 230 |
+
else:
|
| 231 |
+
session_id = session_manager.create_session(request.task_id)
|
| 232 |
+
env = session_manager.get_session(session_id)
|
| 233 |
+
|
| 234 |
+
# Reset environment
|
| 235 |
+
observation = env.reset()
|
| 236 |
+
|
| 237 |
+
return ResetResponse(
|
| 238 |
+
session_id=session_id,
|
| 239 |
+
observation=observation,
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
except ValueError as e:
|
| 243 |
+
raise HTTPException(status_code=400, detail=str(e))
|
| 244 |
+
except Exception as e:
|
| 245 |
+
raise HTTPException(status_code=500, detail=f"Reset failed: {str(e)}")
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
@app.post("/step", response_model=StepResponse)
|
| 249 |
+
async def step(request: StepRequest):
|
| 250 |
+
"""
|
| 251 |
+
Take a step in the environment.
|
| 252 |
+
|
| 253 |
+
Executes the specified action and returns the result.
|
| 254 |
+
"""
|
| 255 |
+
env = session_manager.get_session(request.session_id)
|
| 256 |
+
if not env:
|
| 257 |
+
raise HTTPException(status_code=404, detail="Session not found")
|
| 258 |
+
|
| 259 |
+
try:
|
| 260 |
+
# Parse action
|
| 261 |
+
if request.action:
|
| 262 |
+
action = request.action
|
| 263 |
+
elif request.action_str:
|
| 264 |
+
action = Action(action_str=request.action_str)
|
| 265 |
+
else:
|
| 266 |
+
raise HTTPException(status_code=400, detail="No action provided")
|
| 267 |
+
|
| 268 |
+
# Execute step
|
| 269 |
+
result = env.step(action)
|
| 270 |
+
|
| 271 |
+
return StepResponse(
|
| 272 |
+
observation=result.observation,
|
| 273 |
+
reward=result.reward.value,
|
| 274 |
+
done=result.done,
|
| 275 |
+
info=result.info,
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
except Exception as e:
|
| 279 |
+
raise HTTPException(status_code=500, detail=f"Step failed: {str(e)}")
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
@app.get("/state/{session_id}", response_model=StateResponse)
|
| 283 |
+
async def get_state(session_id: str):
|
| 284 |
+
"""Get the full state of an environment session."""
|
| 285 |
+
env = session_manager.get_session(session_id)
|
| 286 |
+
if not env:
|
| 287 |
+
raise HTTPException(status_code=404, detail="Session not found")
|
| 288 |
+
|
| 289 |
+
try:
|
| 290 |
+
state = env.state()
|
| 291 |
+
return StateResponse(state=state)
|
| 292 |
+
except Exception as e:
|
| 293 |
+
raise HTTPException(status_code=500, detail=f"State retrieval failed: {str(e)}")
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
@app.post("/state", response_model=StateResponse)
|
| 297 |
+
async def post_state(request: StateRequest):
|
| 298 |
+
"""Get the full state of an environment session (POST version)."""
|
| 299 |
+
return await get_state(request.session_id)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
@app.post("/grade", response_model=GradeResponse)
|
| 303 |
+
async def grade(request: GradeRequest):
|
| 304 |
+
"""
|
| 305 |
+
Grade a completed episode.
|
| 306 |
+
|
| 307 |
+
Returns a score from 0.0 to 1.0 based on agent performance.
|
| 308 |
+
"""
|
| 309 |
+
env = session_manager.get_session(request.session_id)
|
| 310 |
+
if not env:
|
| 311 |
+
raise HTTPException(status_code=404, detail="Session not found")
|
| 312 |
+
|
| 313 |
+
try:
|
| 314 |
+
result = grade_task(env.task_id, env)
|
| 315 |
+
|
| 316 |
+
return GradeResponse(
|
| 317 |
+
score=result.score,
|
| 318 |
+
diagnosis_score=result.diagnosis_score,
|
| 319 |
+
remediation_score=result.remediation_score,
|
| 320 |
+
efficiency_score=result.efficiency_score,
|
| 321 |
+
details=result.details,
|
| 322 |
+
feedback=result.feedback,
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
except Exception as e:
|
| 326 |
+
raise HTTPException(status_code=500, detail=f"Grading failed: {str(e)}")
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
@app.delete("/session/{session_id}")
|
| 330 |
+
async def delete_session(session_id: str):
|
| 331 |
+
"""Delete a session."""
|
| 332 |
+
session_manager.delete_session(session_id)
|
| 333 |
+
return {"status": "deleted", "session_id": session_id}
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
# ============================================================================
|
| 337 |
+
# Main
|
| 338 |
+
# ============================================================================
|
| 339 |
+
|
| 340 |
+
if __name__ == "__main__":
|
| 341 |
+
import uvicorn
|
| 342 |
+
|
| 343 |
+
port = int(os.environ.get("PORT", 7860))
|
| 344 |
+
uvicorn.run(app, host="0.0.0.0", port=port)
|
openenv-incident-response/inference.py
ADDED
|
@@ -0,0 +1,408 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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ident Response Environment.
|
| 4 |
+
|
| 5 |
+
This script runs an AI agent against all tasks in the environment
|
| 6 |
+
and reports performance scores. It uses the OpenAI API client
|
| 7 |
+
as specified in the hackathon requirements.
|
| 8 |
+
|
| 9 |
+
Environment Variables:
|
| 10 |
+
API_BASE_URL: The API endpoint for the LLM
|
| 11 |
+
MODEL_NAME: The model identifier to use
|
| 12 |
+
HF_TOKEN: Hugging Face / API key (used as OPENAI_API_KEY)
|
| 13 |
+
OPENAI_API_KEY: Alternative API key variable
|
| 14 |
+
|
| 15 |
+
Usage:
|
| 16 |
+
python inference.py
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
import re
|
| 24 |
+
import sys
|
| 25 |
+
import time
|
| 26 |
+
from typing import Any
|
| 27 |
+
|
| 28 |
+
from openai import OpenAI
|
| 29 |
+
|
| 30 |
+
# Add src to path
|
| 31 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 32 |
+
|
| 33 |
+
from src import (
|
| 34 |
+
Action,
|
| 35 |
+
ActionType,
|
| 36 |
+
IncidentResponseEnv,
|
| 37 |
+
grade_task,
|
| 38 |
+
list_tasks,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# ============================================================================
|
| 43 |
+
# Configuration
|
| 44 |
+
# ============================================================================
|
| 45 |
+
|
| 46 |
+
API_BASE_URL = os.environ.get("API_BASE_URL", "https://api.openai.com/v1")
|
| 47 |
+
MODEL_NAME = os.environ.get("MODEL_NAME", "gpt-4o-mini")
|
| 48 |
+
API_KEY = os.environ.get("HF_TOKEN") or os.environ.get("OPENAI_API_KEY", "")
|
| 49 |
+
|
| 50 |
+
MAX_TOKENS = 1024
|
| 51 |
+
TEMPERATURE = 0.3
|
| 52 |
+
MAX_RETRIES = 3
|
| 53 |
+
RETRY_DELAY = 2.0
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# ============================================================================
|
| 57 |
+
# System Prompt
|
| 58 |
+
# ============================================================================
|
| 59 |
+
|
| 60 |
+
SYSTEM_PROMPT = """You are an expert Site Reliability Engineer (SRE) responding to a production incident.
|
| 61 |
+
|
| 62 |
+
Your job is to diagnose the root cause of the incident and take appropriate remediation actions.
|
| 63 |
+
|
| 64 |
+
## Available Actions
|
| 65 |
+
|
| 66 |
+
You can take the following actions (use the exact format shown):
|
| 67 |
+
|
| 68 |
+
1. **Query Service Status**: `query_service:<service_name>`
|
| 69 |
+
- Get current status, replicas, version, and dependencies
|
| 70 |
+
|
| 71 |
+
2. **Read Logs**: `read_logs:<service_name>`
|
| 72 |
+
- Get recent log entries from the service
|
| 73 |
+
|
| 74 |
+
3. **Get Metrics**: `get_metrics:<service_name>`
|
| 75 |
+
- Get CPU, memory, latency, and error rate metrics
|
| 76 |
+
|
| 77 |
+
4. **Get Alerts**: `get_alerts`
|
| 78 |
+
- Get all active monitoring alerts
|
| 79 |
+
|
| 80 |
+
5. **Run Diagnostics**: `run_diagnostic:<service_name>`
|
| 81 |
+
- Run diagnostic checks on a service
|
| 82 |
+
|
| 83 |
+
6. **Restart Service**: `restart_service:<service_name>`
|
| 84 |
+
- Restart a service (may fix some issues)
|
| 85 |
+
|
| 86 |
+
7. **Scale Service**: `scale_service:<service_name>:<replicas>`
|
| 87 |
+
- Scale a service to specified replica count
|
| 88 |
+
|
| 89 |
+
8. **Rollback Service**: `rollback_service:<service_name>`
|
| 90 |
+
- Rollback to the previous deployment
|
| 91 |
+
|
| 92 |
+
9. **Update Config**: `update_config:<service_name>:<key>:<value>`
|
| 93 |
+
- Update a configuration value (requires restart)
|
| 94 |
+
|
| 95 |
+
10. **Resolve Incident**: `resolve_incident`
|
| 96 |
+
- Mark the incident as resolved (only when fully fixed)
|
| 97 |
+
|
| 98 |
+
## Response Format
|
| 99 |
+
|
| 100 |
+
Respond with your reasoning followed by your action in this format:
|
| 101 |
+
|
| 102 |
+
```
|
| 103 |
+
THOUGHT: [Your analysis of the current situation]
|
| 104 |
+
ACTION: [action_string]
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
Example:
|
| 108 |
+
```
|
| 109 |
+
THOUGHT: The order-service is showing OOM errors in the logs. The current heap size is too small. I need to increase the Java heap size.
|
| 110 |
+
ACTION: update_config:order-service:JAVA_OPTS:-Xmx1024m -Xms512m
|
| 111 |
+
```
|
| 112 |
+
|
| 113 |
+
## Guidelines
|
| 114 |
+
|
| 115 |
+
1. Start by gathering information - check alerts, query affected services, read logs
|
| 116 |
+
2. Look for patterns in errors and metrics
|
| 117 |
+
3. Identify the root cause before attempting fixes
|
| 118 |
+
4. Configuration changes require a service restart to take effect
|
| 119 |
+
5. Work methodically through the affected services
|
| 120 |
+
6. Only call resolve_incident when you've verified the fix worked
|
| 121 |
+
|
| 122 |
+
Remember: You're dealing with a production system. Be careful and methodical."""
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# ============================================================================
|
| 126 |
+
# Action Parser
|
| 127 |
+
# ============================================================================
|
| 128 |
+
|
| 129 |
+
def parse_model_response(response: str) -> str:
|
| 130 |
+
"""Extract action from model response."""
|
| 131 |
+
# Look for ACTION: pattern
|
| 132 |
+
action_match = re.search(r"ACTION:\s*(.+?)(?:\n|$)", response, re.IGNORECASE)
|
| 133 |
+
if action_match:
|
| 134 |
+
action = action_match.group(1).strip()
|
| 135 |
+
# Clean up any backticks or quotes
|
| 136 |
+
action = action.strip("`'\"")
|
| 137 |
+
return action
|
| 138 |
+
|
| 139 |
+
# Look for action-like patterns
|
| 140 |
+
action_patterns = [
|
| 141 |
+
r"(query_service:\S+)",
|
| 142 |
+
r"(read_logs:\S+)",
|
| 143 |
+
r"(get_metrics:\S+)",
|
| 144 |
+
r"(get_alerts)",
|
| 145 |
+
r"(restart_service:\S+)",
|
| 146 |
+
r"(scale_service:\S+:\d+)",
|
| 147 |
+
r"(rollback_service:\S+)",
|
| 148 |
+
r"(update_config:\S+:\S+:\S+)",
|
| 149 |
+
r"(run_diagnostic:\S+)",
|
| 150 |
+
r"(resolve_incident)",
|
| 151 |
+
]
|
| 152 |
+
|
| 153 |
+
for pattern in action_patterns:
|
| 154 |
+
match = re.search(pattern, response, re.IGNORECASE)
|
| 155 |
+
if match:
|
| 156 |
+
return match.group(1)
|
| 157 |
+
|
| 158 |
+
# Default fallback
|
| 159 |
+
return "get_alerts"
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
# ============================================================================
|
| 163 |
+
# Agent
|
| 164 |
+
# ============================================================================
|
| 165 |
+
|
| 166 |
+
class IncidentResponseAgent:
|
| 167 |
+
"""AI agent for incident response using OpenAI API."""
|
| 168 |
+
|
| 169 |
+
def __init__(self, client: OpenAI, model: str = MODEL_NAME):
|
| 170 |
+
self.client = client
|
| 171 |
+
self.model = model
|
| 172 |
+
self.conversation_history: list[dict[str, Any]] = []
|
| 173 |
+
|
| 174 |
+
def reset(self):
|
| 175 |
+
"""Reset conversation history."""
|
| 176 |
+
self.conversation_history = []
|
| 177 |
+
|
| 178 |
+
def get_action(self, observation_str: str) -> str:
|
| 179 |
+
"""Get an action from the model based on current observation."""
|
| 180 |
+
# Add observation to history
|
| 181 |
+
self.conversation_history.append({
|
| 182 |
+
"role": "user",
|
| 183 |
+
"content": observation_str,
|
| 184 |
+
})
|
| 185 |
+
|
| 186 |
+
# Prepare messages
|
| 187 |
+
messages = [
|
| 188 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 189 |
+
*self.conversation_history,
|
| 190 |
+
]
|
| 191 |
+
|
| 192 |
+
# Call the model
|
| 193 |
+
for attempt in range(MAX_RETRIES):
|
| 194 |
+
try:
|
| 195 |
+
completion = self.client.chat.completions.create(
|
| 196 |
+
model=self.model,
|
| 197 |
+
messages=messages,
|
| 198 |
+
temperature=TEMPERATURE,
|
| 199 |
+
max_tokens=MAX_TOKENS,
|
| 200 |
+
)
|
| 201 |
+
response = completion.choices[0].message.content or ""
|
| 202 |
+
|
| 203 |
+
# Add response to history
|
| 204 |
+
self.conversation_history.append({
|
| 205 |
+
"role": "assistant",
|
| 206 |
+
"content": response,
|
| 207 |
+
})
|
| 208 |
+
|
| 209 |
+
# Parse action
|
| 210 |
+
action = parse_model_response(response)
|
| 211 |
+
return action
|
| 212 |
+
|
| 213 |
+
except Exception as e:
|
| 214 |
+
print(f" API call failed (attempt {attempt + 1}): {e}")
|
| 215 |
+
if attempt < MAX_RETRIES - 1:
|
| 216 |
+
time.sleep(RETRY_DELAY)
|
| 217 |
+
|
| 218 |
+
# Fallback
|
| 219 |
+
return "get_alerts"
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
# ============================================================================
|
| 223 |
+
# Observation Formatter
|
| 224 |
+
# ============================================================================
|
| 225 |
+
|
| 226 |
+
def format_observation(obs) -> str:
|
| 227 |
+
"""Format observation as readable text for the model."""
|
| 228 |
+
lines = []
|
| 229 |
+
|
| 230 |
+
# Incident info
|
| 231 |
+
lines.append("=" * 60)
|
| 232 |
+
lines.append(f"INCIDENT: {obs.incident.title}")
|
| 233 |
+
lines.append(f"Severity: {obs.incident.severity}")
|
| 234 |
+
lines.append(f"Description: {obs.incident.description}")
|
| 235 |
+
lines.append(f"Affected Services: {', '.join(obs.incident.affected_services)}")
|
| 236 |
+
lines.append(f"Customer Impact: {obs.incident.customer_impact}")
|
| 237 |
+
lines.append("=" * 60)
|
| 238 |
+
|
| 239 |
+
# Step info
|
| 240 |
+
lines.append(f"\nStep: {obs.step}")
|
| 241 |
+
|
| 242 |
+
# Available services
|
| 243 |
+
lines.append(f"\nAvailable services: {', '.join(obs.available_services)}")
|
| 244 |
+
|
| 245 |
+
# Last action result
|
| 246 |
+
if obs.last_action:
|
| 247 |
+
lines.append(f"\nLast action: {obs.last_action}")
|
| 248 |
+
if obs.last_action_success:
|
| 249 |
+
lines.append("Result: SUCCESS")
|
| 250 |
+
else:
|
| 251 |
+
lines.append(f"Result: FAILED - {obs.last_action_error}")
|
| 252 |
+
|
| 253 |
+
if obs.last_action_result:
|
| 254 |
+
result_str = json.dumps(obs.last_action_result, indent=2, default=str)
|
| 255 |
+
lines.append(f"Data:\n{result_str}")
|
| 256 |
+
|
| 257 |
+
# Active alerts
|
| 258 |
+
if obs.visible_alerts:
|
| 259 |
+
lines.append("\n--- ACTIVE ALERTS ---")
|
| 260 |
+
for alert in obs.visible_alerts:
|
| 261 |
+
lines.append(f"[{alert.severity}] {alert.title}")
|
| 262 |
+
lines.append(f" Service: {alert.service}")
|
| 263 |
+
lines.append(f" {alert.description}")
|
| 264 |
+
|
| 265 |
+
# Hint (for easy tasks)
|
| 266 |
+
if obs.hint:
|
| 267 |
+
lines.append(f"\nHINT: {obs.hint}")
|
| 268 |
+
|
| 269 |
+
return "\n".join(lines)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
# ============================================================================
|
| 273 |
+
# Run Episode
|
| 274 |
+
# ============================================================================
|
| 275 |
+
|
| 276 |
+
def run_episode(env: IncidentResponseEnv, agent: IncidentResponseAgent) -> dict[str, Any]:
|
| 277 |
+
"""Run a single episode and return results."""
|
| 278 |
+
observation = env.reset()
|
| 279 |
+
agent.reset()
|
| 280 |
+
|
| 281 |
+
total_reward = 0.0
|
| 282 |
+
steps = 0
|
| 283 |
+
actions_taken = []
|
| 284 |
+
|
| 285 |
+
print(f"\n{'='*60}")
|
| 286 |
+
print(f"Starting episode: {env.task.name}")
|
| 287 |
+
print(f"Difficulty: {env.task.difficulty}")
|
| 288 |
+
print(f"Max steps: {env.task.max_steps}")
|
| 289 |
+
print(f"{'='*60}\n")
|
| 290 |
+
|
| 291 |
+
while not env.done and steps < env.task.max_steps:
|
| 292 |
+
# Format observation for model
|
| 293 |
+
obs_str = format_observation(observation)
|
| 294 |
+
|
| 295 |
+
# Get action from agent
|
| 296 |
+
action_str = agent.get_action(obs_str)
|
| 297 |
+
print(f"Step {steps + 1}: {action_str}")
|
| 298 |
+
|
| 299 |
+
# Execute action
|
| 300 |
+
action = Action(action_str=action_str)
|
| 301 |
+
result = env.step(action)
|
| 302 |
+
|
| 303 |
+
observation = result.observation
|
| 304 |
+
total_reward += result.reward.value
|
| 305 |
+
steps += 1
|
| 306 |
+
actions_taken.append(action_str)
|
| 307 |
+
|
| 308 |
+
# Print progress
|
| 309 |
+
if result.done:
|
| 310 |
+
print(f" -> Episode done. Total reward: {total_reward:.4f}")
|
| 311 |
+
break
|
| 312 |
+
|
| 313 |
+
# Grade the episode
|
| 314 |
+
grade = grade_task(env.task_id, env)
|
| 315 |
+
|
| 316 |
+
return {
|
| 317 |
+
"task_id": env.task_id,
|
| 318 |
+
"task_name": env.task.name,
|
| 319 |
+
"difficulty": env.task.difficulty,
|
| 320 |
+
"steps": steps,
|
| 321 |
+
"total_reward": total_reward,
|
| 322 |
+
"score": grade.score,
|
| 323 |
+
"diagnosis_score": grade.diagnosis_score,
|
| 324 |
+
"remediation_score": grade.remediation_score,
|
| 325 |
+
"efficiency_score": grade.efficiency_score,
|
| 326 |
+
"feedback": grade.feedback,
|
| 327 |
+
"resolved": env.state().resolved,
|
| 328 |
+
"actions": actions_taken,
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
# ============================================================================
|
| 333 |
+
# Main
|
| 334 |
+
# ============================================================================
|
| 335 |
+
|
| 336 |
+
def main():
|
| 337 |
+
"""Run inference on all tasks."""
|
| 338 |
+
print("DevOps Incident Response Environment - Baseline Inference")
|
| 339 |
+
print("=" * 60)
|
| 340 |
+
|
| 341 |
+
# Check API key
|
| 342 |
+
if not API_KEY:
|
| 343 |
+
print("ERROR: No API key found. Set OPENAI_API_KEY or HF_TOKEN environment variable.")
|
| 344 |
+
sys.exit(1)
|
| 345 |
+
|
| 346 |
+
# Initialize client
|
| 347 |
+
print(f"API Base: {API_BASE_URL}")
|
| 348 |
+
print(f"Model: {MODEL_NAME}")
|
| 349 |
+
|
| 350 |
+
client = OpenAI(
|
| 351 |
+
api_key=API_KEY,
|
| 352 |
+
base_url=API_BASE_URL,
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
# Create agent
|
| 356 |
+
agent = IncidentResponseAgent(client, MODEL_NAME)
|
| 357 |
+
|
| 358 |
+
# Get all tasks
|
| 359 |
+
tasks = list_tasks()
|
| 360 |
+
print(f"\nFound {len(tasks)} tasks:")
|
| 361 |
+
for task in tasks:
|
| 362 |
+
print(f" - {task['id']}: {task['name']} ({task['difficulty']})")
|
| 363 |
+
|
| 364 |
+
# Run each task
|
| 365 |
+
results = []
|
| 366 |
+
for task in tasks:
|
| 367 |
+
task_id = task["id"]
|
| 368 |
+
env = IncidentResponseEnv(task_id=task_id)
|
| 369 |
+
|
| 370 |
+
result = run_episode(env, agent)
|
| 371 |
+
results.append(result)
|
| 372 |
+
|
| 373 |
+
print(f"\n--- {task_id} Results ---")
|
| 374 |
+
print(f"Score: {result['score']:.4f}")
|
| 375 |
+
print(f"Resolved: {result['resolved']}")
|
| 376 |
+
print(f"Feedback: {result['feedback']}")
|
| 377 |
+
|
| 378 |
+
# Summary
|
| 379 |
+
print("\n" + "=" * 60)
|
| 380 |
+
print("FINAL RESULTS")
|
| 381 |
+
print("=" * 60)
|
| 382 |
+
|
| 383 |
+
total_score = sum(r["score"] for r in results)
|
| 384 |
+
avg_score = total_score / len(results) if results else 0.0
|
| 385 |
+
|
| 386 |
+
for result in results:
|
| 387 |
+
status = "RESOLVED" if result["resolved"] else "UNRESOLVED"
|
| 388 |
+
print(f"{result['task_id']}: {result['score']:.4f} [{status}]")
|
| 389 |
+
|
| 390 |
+
print(f"\nAverage Score: {avg_score:.4f}")
|
| 391 |
+
print(f"Total Score: {total_score:.4f}")
|
| 392 |
+
|
| 393 |
+
# Save results
|
| 394 |
+
output_file = "inference_results.json"
|
| 395 |
+
with open(output_file, "w") as f:
|
| 396 |
+
json.dump({
|
| 397 |
+
"model": MODEL_NAME,
|
| 398 |
+
"results": results,
|
| 399 |
+
"average_score": avg_score,
|
| 400 |
+
"total_score": total_score,
|
| 401 |
+
}, f, indent=2)
|
| 402 |
+
print(f"\nResults saved to {output_file}")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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# OpenEnv Configuration for DevOps Incident Response Environment
|
| 2 |
+
# This file defines the environment metadata and task configurations
|
| 3 |
+
|
| 4 |
+
name: devops-incident-response
|
| 5 |
+
version: "1.0.0"
|
| 6 |
+
description: |
|
| 7 |
+
An AI training environment for production incident response in microservices architectures.
|
| 8 |
+
Agents must diagnose and resolve realistic production incidents by analyzing logs, metrics,
|
| 9 |
+
and alerts, then taking appropriate remediation actions.
|
| 10 |
+
|
| 11 |
+
author: OpenEnv Hackathon Team
|
| 12 |
+
license: MIT
|
| 13 |
+
repository: https://huggingface.co/spaces/openenv/devops-incident-response
|
| 14 |
+
|
| 15 |
+
# Environment type
|
| 16 |
+
type: step-based
|
| 17 |
+
episode_type: finite
|
| 18 |
+
|
| 19 |
+
# API endpoints
|
| 20 |
+
api:
|
| 21 |
+
version: "1.0"
|
| 22 |
+
endpoints:
|
| 23 |
+
reset: /reset
|
| 24 |
+
step: /step
|
| 25 |
+
state: /state
|
| 26 |
+
grade: /grade
|
| 27 |
+
health: /health
|
| 28 |
+
tasks: /tasks
|
| 29 |
+
|
| 30 |
+
# Model definitions
|
| 31 |
+
models:
|
| 32 |
+
observation:
|
| 33 |
+
type: object
|
| 34 |
+
description: "Current state of the incident and infrastructure"
|
| 35 |
+
schema: src.models.Observation
|
| 36 |
+
|
| 37 |
+
action:
|
| 38 |
+
type: object
|
| 39 |
+
description: "An action the agent can take"
|
| 40 |
+
schema: src.models.Action
|
| 41 |
+
|
| 42 |
+
reward:
|
| 43 |
+
type: object
|
| 44 |
+
description: "Reward signal with breakdown"
|
| 45 |
+
schema: src.models.Reward
|
| 46 |
+
|
| 47 |
+
# Action space
|
| 48 |
+
action_space:
|
| 49 |
+
type: discrete
|
| 50 |
+
actions:
|
| 51 |
+
- name: query_service
|
| 52 |
+
description: "Get status and info for a service"
|
| 53 |
+
parameters:
|
| 54 |
+
- name: service
|
| 55 |
+
type: string
|
| 56 |
+
required: true
|
| 57 |
+
|
| 58 |
+
- name: read_logs
|
| 59 |
+
description: "Read recent logs from a service"
|
| 60 |
+
parameters:
|
| 61 |
+
- name: service
|
| 62 |
+
type: string
|
| 63 |
+
required: true
|
| 64 |
+
- name: log_lines
|
| 65 |
+
type: integer
|
| 66 |
+
default: 20
|
| 67 |
+
|
| 68 |
+
- name: get_metrics
|
| 69 |
+
description: "Get current metrics for a service"
|
| 70 |
+
parameters:
|
| 71 |
+
- name: service
|
| 72 |
+
type: string
|
| 73 |
+
required: true
|
| 74 |
+
|
| 75 |
+
- name: get_alerts
|
| 76 |
+
description: "Get active monitoring alerts"
|
| 77 |
+
parameters: []
|
| 78 |
+
|
| 79 |
+
- name: restart_service
|
| 80 |
+
description: "Restart a service"
|
| 81 |
+
parameters:
|
| 82 |
+
- name: service
|
| 83 |
+
type: string
|
| 84 |
+
required: true
|
| 85 |
+
|
| 86 |
+
- name: scale_service
|
| 87 |
+
description: "Scale a service to specified replicas"
|
| 88 |
+
parameters:
|
| 89 |
+
- name: service
|
| 90 |
+
type: string
|
| 91 |
+
required: true
|
| 92 |
+
- name: scale_replicas
|
| 93 |
+
type: integer
|
| 94 |
+
required: true
|
| 95 |
+
|
| 96 |
+
- name: rollback_service
|
| 97 |
+
description: "Rollback a service to previous version"
|
| 98 |
+
parameters:
|
| 99 |
+
- name: service
|
| 100 |
+
type: string
|
| 101 |
+
required: true
|
| 102 |
+
|
| 103 |
+
- name: update_config
|
| 104 |
+
description: "Update a service configuration"
|
| 105 |
+
parameters:
|
| 106 |
+
- name: service
|
| 107 |
+
type: string
|
| 108 |
+
required: true
|
| 109 |
+
- name: config_key
|
| 110 |
+
type: string
|
| 111 |
+
required: true
|
| 112 |
+
- name: config_value
|
| 113 |
+
type: any
|
| 114 |
+
required: true
|
| 115 |
+
|
| 116 |
+
- name: run_diagnostic
|
| 117 |
+
description: "Run diagnostic checks on a service"
|
| 118 |
+
parameters:
|
| 119 |
+
- name: service
|
| 120 |
+
type: string
|
| 121 |
+
required: true
|
| 122 |
+
|
| 123 |
+
- name: resolve_incident
|
| 124 |
+
description: "Mark the incident as resolved"
|
| 125 |
+
parameters: []
|
| 126 |
+
|
| 127 |
+
# Observation space
|
| 128 |
+
observation_space:
|
| 129 |
+
type: object
|
| 130 |
+
properties:
|
| 131 |
+
incident:
|
| 132 |
+
type: object
|
| 133 |
+
description: "Current incident information"
|
| 134 |
+
step:
|
| 135 |
+
type: integer
|
| 136 |
+
description: "Current step number"
|
| 137 |
+
visible_services:
|
| 138 |
+
type: object
|
| 139 |
+
description: "Information about queried services"
|
| 140 |
+
visible_logs:
|
| 141 |
+
type: array
|
| 142 |
+
description: "Log entries from queried services"
|
| 143 |
+
visible_metrics:
|
| 144 |
+
type: object
|
| 145 |
+
description: "Metrics from queried services"
|
| 146 |
+
visible_alerts:
|
| 147 |
+
type: array
|
| 148 |
+
description: "Active monitoring alerts"
|
| 149 |
+
last_action:
|
| 150 |
+
type: string
|
| 151 |
+
description: "The last action taken"
|
| 152 |
+
last_action_result:
|
| 153 |
+
type: object
|
| 154 |
+
description: "Result of the last action"
|
| 155 |
+
available_services:
|
| 156 |
+
type: array
|
| 157 |
+
description: "List of all services in the infrastructure"
|
| 158 |
+
|
| 159 |
+
# Task definitions
|
| 160 |
+
tasks:
|
| 161 |
+
- id: task_easy_oom
|
| 162 |
+
name: "Memory Crisis: OOM Kill Resolution"
|
| 163 |
+
difficulty: easy
|
| 164 |
+
description: |
|
| 165 |
+
The order-service has been OOM killed during a traffic spike.
|
| 166 |
+
Identify the root cause and restore service health.
|
| 167 |
+
max_steps: 15
|
| 168 |
+
time_limit_seconds: 300
|
| 169 |
+
grader:
|
| 170 |
+
type: programmatic
|
| 171 |
+
module: src.graders
|
| 172 |
+
function: grade_task
|
| 173 |
+
metrics:
|
| 174 |
+
diagnosis_weight: 0.3
|
| 175 |
+
remediation_weight: 0.6
|
| 176 |
+
efficiency_weight: 0.1
|
| 177 |
+
|
| 178 |
+
- id: task_medium_cascade
|
| 179 |
+
name: "Database Overload: Cascading Connection Failure"
|
| 180 |
+
difficulty: medium
|
| 181 |
+
description: |
|
| 182 |
+
Multiple services are experiencing database connection timeouts.
|
| 183 |
+
Identify the root cause and fix all affected services.
|
| 184 |
+
max_steps: 25
|
| 185 |
+
time_limit_seconds: 600
|
| 186 |
+
grader:
|
| 187 |
+
type: programmatic
|
| 188 |
+
module: src.graders
|
| 189 |
+
function: grade_task
|
| 190 |
+
metrics:
|
| 191 |
+
diagnosis_weight: 0.35
|
| 192 |
+
remediation_weight: 0.55
|
| 193 |
+
efficiency_weight: 0.1
|
| 194 |
+
|
| 195 |
+
- id: task_hard_complex
|
| 196 |
+
name: "Perfect Storm: Multi-Factor Cascading Incident"
|
| 197 |
+
difficulty: hard
|
| 198 |
+
description: |
|
| 199 |
+
Multiple alerts firing with several services affected.
|
| 200 |
+
This incident has multiple root causes that must all be addressed.
|
| 201 |
+
max_steps: 40
|
| 202 |
+
time_limit_seconds: 900
|
| 203 |
+
grader:
|
| 204 |
+
type: programmatic
|
| 205 |
+
module: src.graders
|
| 206 |
+
function: grade_task
|
| 207 |
+
metrics:
|
| 208 |
+
diagnosis_weight: 0.4
|
| 209 |
+
remediation_weight: 0.45
|
| 210 |
+
efficiency_weight: 0.15
|
| 211 |
+
|
| 212 |
+
# Reward configuration
|
| 213 |
+
reward:
|
| 214 |
+
type: shaped
|
| 215 |
+
range: [-1.0, 1.0]
|
| 216 |
+
shaping:
|
| 217 |
+
diagnostic_actions: 0.02
|
| 218 |
+
correct_remediation: 0.1
|
| 219 |
+
successful_resolution: 0.3
|
| 220 |
+
efficiency_bonus: 0.1
|
| 221 |
+
penalties:
|
| 222 |
+
unnecessary_actions: -0.01
|
| 223 |
+
harmful_actions: -0.05
|
| 224 |
+
time_pressure: -0.01
|
| 225 |
+
|
| 226 |
+
# Termination conditions
|
| 227 |
+
termination:
|
| 228 |
+
conditions:
|
| 229 |
+
- type: max_steps
|
| 230 |
+
description: "Episode ends when max steps reached"
|
| 231 |
+
- type: successful_resolution
|
| 232 |
+
description: "Episode ends when incident is resolved"
|
| 233 |
+
|
| 234 |
+
# Tags for discoverability
|
| 235 |
+
tags:
|
| 236 |
+
- devops
|
| 237 |
+
- incident-response
|
| 238 |
+
- sre
|
| 239 |
+
- microservices
|
| 240 |
+
- production
|
| 241 |
+
- real-world
|
| 242 |
+
- openenv
|
| 243 |
+
|
| 244 |
+
# Hardware requirements
|
| 245 |
+
requirements:
|
| 246 |
+
vcpu: 2
|
| 247 |
+
memory_gb: 8
|
| 248 |
+
runtime_minutes: 20
|
| 249 |
+
|
| 250 |
+
# Validation
|
| 251 |
+
validation:
|
| 252 |
+
schema_version: "1.0"
|
| 253 |
+
validate_endpoints: true
|
| 254 |
+
validate_graders: true
|
| 255 |
+
validate_tasks: true
|
openenv-incident-response/requirements.txt
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# DevOps Incident Response Environment Dependencies
|
| 2 |
+
|
| 3 |
+
# Core
|
| 4 |
+
pydantic>=2.0.0
|
| 5 |
+
fastapi>=0.100.0
|
| 6 |
+
uvicorn[standard]>=0.22.0
|
| 7 |
+
|
| 8 |
+
# API client for inference
|
| 9 |
+
openai>=1.0.0
|
| 10 |
+
|
| 11 |
+
# Utils
|
| 12 |
+
python-dotenv>=1.0.0
|
| 13 |
+
pyyaml>=6.0.0
|
| 14 |
+
|
| 15 |
+
# Testing
|
| 16 |
+
pytest>=7.0.0
|
| 17 |
+
httpx>=0.24.0
|
openenv-incident-response/src/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
DevOps Incident Response Environment for OpenEnv.
|
| 3 |
+
|
| 4 |
+
A reinforcement learning environment for training AI agents
|
| 5 |
+
to handle production incident response in microservices architectures.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from .environment import IncidentResponseEnv
|
| 9 |
+
from .graders import GradeResult, TaskGrader, grade_all_tasks, grade_task
|
| 10 |
+
from .models import (
|
| 11 |
+
Action,
|
| 12 |
+
ActionType,
|
| 13 |
+
Alert,
|
| 14 |
+
AlertSeverity,
|
| 15 |
+
DiagnosticResult,
|
| 16 |
+
EnvironmentState,
|
| 17 |
+
IncidentInfo,
|
| 18 |
+
LogEntry,
|
| 19 |
+
LogLevel,
|
| 20 |
+
MetricData,
|
| 21 |
+
Observation,
|
| 22 |
+
Reward,
|
| 23 |
+
ServiceInfo,
|
| 24 |
+
ServiceStatus,
|
| 25 |
+
StepResult,
|
| 26 |
+
TaskDefinition,
|
| 27 |
+
)
|
| 28 |
+
from .simulator import InfrastructureSimulator, ServiceSimulator
|
| 29 |
+
from .tasks import TASKS, get_task, list_tasks
|
| 30 |
+
|
| 31 |
+
__version__ = "1.0.0"
|
| 32 |
+
__all__ = [
|
| 33 |
+
# Main environment
|
| 34 |
+
"IncidentResponseEnv",
|
| 35 |
+
# Models
|
| 36 |
+
"Action",
|
| 37 |
+
"ActionType",
|
| 38 |
+
"Alert",
|
| 39 |
+
"AlertSeverity",
|
| 40 |
+
"DiagnosticResult",
|
| 41 |
+
"EnvironmentState",
|
| 42 |
+
"IncidentInfo",
|
| 43 |
+
"LogEntry",
|
| 44 |
+
"LogLevel",
|
| 45 |
+
"MetricData",
|
| 46 |
+
"Observation",
|
| 47 |
+
"Reward",
|
| 48 |
+
"ServiceInfo",
|
| 49 |
+
"ServiceStatus",
|
| 50 |
+
"StepResult",
|
| 51 |
+
"TaskDefinition",
|
| 52 |
+
# Simulator
|
| 53 |
+
"InfrastructureSimulator",
|
| 54 |
+
"ServiceSimulator",
|
| 55 |
+
# Graders
|
| 56 |
+
"GradeResult",
|
| 57 |
+
"TaskGrader",
|
| 58 |
+
"grade_task",
|
| 59 |
+
"grade_all_tasks",
|
| 60 |
+
# Tasks
|
| 61 |
+
"TASKS",
|
| 62 |
+
"get_task",
|
| 63 |
+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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
DevOps Incident Response Environment - Main Environment Implementation.
|
| 3 |
+
|
| 4 |
+
This module implements the OpenEnv specification for an AI agent
|
| 5 |
+
to learn incident response in a simulated microservices infrastructure.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import re
|
| 12 |
+
from datetime import datetime
|
| 13 |
+
from typing import Any, Optional
|
| 14 |
+
|
| 15 |
+
from .models import (
|
| 16 |
+
Action,
|
| 17 |
+
ActionType,
|
| 18 |
+
AlertSeverity,
|
| 19 |
+
EnvironmentState,
|
| 20 |
+
IncidentInfo,
|
| 21 |
+
LogLevel,
|
| 22 |
+
Observation,
|
| 23 |
+
Reward,
|
| 24 |
+
ServiceStatus,
|
| 25 |
+
StepResult,
|
| 26 |
+
TaskDefinition,
|
| 27 |
+
)
|
| 28 |
+
from .simulator import (
|
| 29 |
+
InfrastructureSimulator,
|
| 30 |
+
create_bad_deploy_scenario,
|
| 31 |
+
create_cascading_failure_scenario,
|
| 32 |
+
create_complex_incident_scenario,
|
| 33 |
+
create_memory_leak_scenario,
|
| 34 |
+
create_oom_scenario,
|
| 35 |
+
)
|
| 36 |
+
from .tasks import get_task
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class IncidentResponseEnv:
|
| 40 |
+
"""
|
| 41 |
+
An OpenEnv-compliant environment for training AI agents
|
| 42 |
+
in DevOps incident response.
|
| 43 |
+
|
| 44 |
+
The agent must diagnose and resolve production incidents in a
|
| 45 |
+
simulated microservices infrastructure by:
|
| 46 |
+
- Querying service status, logs, and metrics
|
| 47 |
+
- Identifying root causes
|
| 48 |
+
- Executing remediation actions
|
| 49 |
+
- Validating resolution
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def __init__(self, task_id: str = "task_easy_oom"):
|
| 53 |
+
"""
|
| 54 |
+
Initialize the environment.
|
| 55 |
+
|
| 56 |
+
Args:
|
| 57 |
+
task_id: The task/scenario to run
|
| 58 |
+
"""
|
| 59 |
+
self.task_id = task_id
|
| 60 |
+
self.task: TaskDefinition = get_task(task_id)
|
| 61 |
+
self.infra = InfrastructureSimulator()
|
| 62 |
+
|
| 63 |
+
# Episode state
|
| 64 |
+
self.current_step = 0
|
| 65 |
+
self.done = False
|
| 66 |
+
self.total_reward = 0.0
|
| 67 |
+
|
| 68 |
+
# Tracking for grading
|
| 69 |
+
self.actions_taken: list[str] = []
|
| 70 |
+
self.services_queried: set[str] = set()
|
| 71 |
+
self.correct_diagnosis = False
|
| 72 |
+
self.remediation_progress: dict[str, bool] = {}
|
| 73 |
+
|
| 74 |
+
# Scenario-specific ground truth
|
| 75 |
+
self.scenario_data: dict[str, Any] = {}
|
| 76 |
+
|
| 77 |
+
# Observation state
|
| 78 |
+
self._observation: Optional[Observation] = None
|
| 79 |
+
|
| 80 |
+
def reset(self) -> Observation:
|
| 81 |
+
"""
|
| 82 |
+
Reset the environment to initial state.
|
| 83 |
+
|
| 84 |
+
Returns:
|
| 85 |
+
Initial observation
|
| 86 |
+
"""
|
| 87 |
+
self.current_step = 0
|
| 88 |
+
self.done = False
|
| 89 |
+
self.total_reward = 0.0
|
| 90 |
+
self.actions_taken = []
|
| 91 |
+
self.services_queried = set()
|
| 92 |
+
self.correct_diagnosis = False
|
| 93 |
+
self.remediation_progress = {}
|
| 94 |
+
|
| 95 |
+
# Reset infrastructure
|
| 96 |
+
self.infra = InfrastructureSimulator()
|
| 97 |
+
|
| 98 |
+
# Set up scenario based on task
|
| 99 |
+
if self.task_id == "task_easy_oom":
|
| 100 |
+
self.scenario_data = create_oom_scenario(self.infra)
|
| 101 |
+
elif self.task_id == "task_medium_cascade":
|
| 102 |
+
self.scenario_data = create_cascading_failure_scenario(self.infra)
|
| 103 |
+
elif self.task_id == "task_hard_complex":
|
| 104 |
+
self.scenario_data = create_complex_incident_scenario(self.infra)
|
| 105 |
+
else:
|
| 106 |
+
# Default fallback
|
| 107 |
+
self.scenario_data = create_oom_scenario(self.infra)
|
| 108 |
+
|
| 109 |
+
# Initialize remediation tracking
|
| 110 |
+
for action in self.scenario_data.get("required_remediation", []):
|
| 111 |
+
self.remediation_progress[action] = False
|
| 112 |
+
|
| 113 |
+
# Create initial observation
|
| 114 |
+
self._observation = self._create_observation()
|
| 115 |
+
return self._observation
|
| 116 |
+
|
| 117 |
+
def step(self, action: Action) -> StepResult:
|
| 118 |
+
"""
|
| 119 |
+
Execute an action in the environment.
|
| 120 |
+
|
| 121 |
+
Args:
|
| 122 |
+
action: The action to execute
|
| 123 |
+
|
| 124 |
+
Returns:
|
| 125 |
+
StepResult with observation, reward, done, info
|
| 126 |
+
"""
|
| 127 |
+
if self.done:
|
| 128 |
+
return StepResult(
|
| 129 |
+
observation=self._observation,
|
| 130 |
+
reward=Reward(value=0.0, reason="Episode already done"),
|
| 131 |
+
done=True,
|
| 132 |
+
info={"message": "Episode has ended. Call reset() to start a new episode."},
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
self.current_step += 1
|
| 136 |
+
|
| 137 |
+
# Parse action if provided as string
|
| 138 |
+
if action.action_str and not action.action_type:
|
| 139 |
+
action = self._parse_action_string(action.action_str)
|
| 140 |
+
|
| 141 |
+
# Execute the action
|
| 142 |
+
result = self._execute_action(action)
|
| 143 |
+
|
| 144 |
+
# Calculate reward
|
| 145 |
+
reward = self._calculate_reward(action, result)
|
| 146 |
+
self.total_reward += reward.value
|
| 147 |
+
|
| 148 |
+
# Check termination
|
| 149 |
+
if self.current_step >= self.task.max_steps:
|
| 150 |
+
self.done = True
|
| 151 |
+
reward.reason += " Max steps reached."
|
| 152 |
+
|
| 153 |
+
if self._check_resolution():
|
| 154 |
+
self.done = True
|
| 155 |
+
reward.value += 0.3 # Bonus for successful resolution
|
| 156 |
+
reward.reason += " Incident resolved successfully!"
|
| 157 |
+
|
| 158 |
+
# Update observation
|
| 159 |
+
self._observation = self._create_observation(
|
| 160 |
+
last_action=self._action_to_string(action),
|
| 161 |
+
last_action_success=result.get("success", True),
|
| 162 |
+
last_action_error=result.get("error"),
|
| 163 |
+
last_action_result=result.get("data"),
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
# Record action
|
| 167 |
+
self.actions_taken.append(self._action_to_string(action))
|
| 168 |
+
|
| 169 |
+
return StepResult(
|
| 170 |
+
observation=self._observation,
|
| 171 |
+
reward=reward,
|
| 172 |
+
done=self.done,
|
| 173 |
+
info={
|
| 174 |
+
"step": self.current_step,
|
| 175 |
+
"total_reward": self.total_reward,
|
| 176 |
+
"remediation_progress": self.remediation_progress,
|
| 177 |
+
},
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
def state(self) -> EnvironmentState:
|
| 181 |
+
"""
|
| 182 |
+
Get the full environment state for checkpointing.
|
| 183 |
+
|
| 184 |
+
Returns:
|
| 185 |
+
Complete serializable state
|
| 186 |
+
"""
|
| 187 |
+
return EnvironmentState(
|
| 188 |
+
task_id=self.task_id,
|
| 189 |
+
task_difficulty=self.task.difficulty,
|
| 190 |
+
episode_step=self.current_step,
|
| 191 |
+
max_steps=self.task.max_steps,
|
| 192 |
+
done=self.done,
|
| 193 |
+
observation=self._observation or self._create_observation(),
|
| 194 |
+
total_reward=self.total_reward,
|
| 195 |
+
root_cause=self.scenario_data.get("root_cause", ""),
|
| 196 |
+
required_actions=self.scenario_data.get("required_remediation", []),
|
| 197 |
+
services_state=self.infra.get_state(),
|
| 198 |
+
resolved=self._check_resolution(),
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
def close(self):
|
| 202 |
+
"""Clean up resources."""
|
| 203 |
+
pass # No cleanup needed for this simulation
|
| 204 |
+
|
| 205 |
+
def _create_observation(
|
| 206 |
+
self,
|
| 207 |
+
last_action: str | None = None,
|
| 208 |
+
last_action_success: bool = True,
|
| 209 |
+
last_action_error: str | None = None,
|
| 210 |
+
last_action_result: dict | None = None,
|
| 211 |
+
) -> Observation:
|
| 212 |
+
"""Create an observation from current state."""
|
| 213 |
+
# Get current alerts
|
| 214 |
+
alerts = self.infra.get_alerts()
|
| 215 |
+
|
| 216 |
+
# Determine hint based on difficulty
|
| 217 |
+
hint = None
|
| 218 |
+
if self.task.difficulty == "easy" and self.current_step == 0:
|
| 219 |
+
hint = "Start by checking the alerts and querying the affected service's logs and metrics."
|
| 220 |
+
|
| 221 |
+
return Observation(
|
| 222 |
+
incident=IncidentInfo(
|
| 223 |
+
id=f"INC-{self.task_id.upper()[:8]}",
|
| 224 |
+
title=self.task.incident_title,
|
| 225 |
+
severity=self.task.incident_severity,
|
| 226 |
+
started_at=datetime.now(),
|
| 227 |
+
description=self.task.incident_description,
|
| 228 |
+
affected_services=self.task.affected_services,
|
| 229 |
+
customer_impact=self.task.customer_impact,
|
| 230 |
+
),
|
| 231 |
+
step=self.current_step,
|
| 232 |
+
last_action=last_action,
|
| 233 |
+
last_action_success=last_action_success,
|
| 234 |
+
last_action_error=last_action_error,
|
| 235 |
+
last_action_result=last_action_result,
|
| 236 |
+
visible_alerts=alerts,
|
| 237 |
+
action_history=self.actions_taken.copy(),
|
| 238 |
+
available_services=self.infra.get_service_names(),
|
| 239 |
+
hint=hint,
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
def _parse_action_string(self, action_str: str) -> Action:
|
| 243 |
+
"""Parse a natural language or formatted action string."""
|
| 244 |
+
action_str = action_str.strip().lower()
|
| 245 |
+
|
| 246 |
+
# Parse structured format: action_type:service:param
|
| 247 |
+
if ":" in action_str:
|
| 248 |
+
parts = action_str.split(":")
|
| 249 |
+
action_type = parts[0]
|
| 250 |
+
service = parts[1] if len(parts) > 1 else None
|
| 251 |
+
param = parts[2] if len(parts) > 2 else None
|
| 252 |
+
extra = parts[3] if len(parts) > 3 else None
|
| 253 |
+
|
| 254 |
+
type_map = {
|
| 255 |
+
"query_service": ActionType.QUERY_SERVICE,
|
| 256 |
+
"query": ActionType.QUERY_SERVICE,
|
| 257 |
+
"read_logs": ActionType.READ_LOGS,
|
| 258 |
+
"logs": ActionType.READ_LOGS,
|
| 259 |
+
"get_metrics": ActionType.GET_METRICS,
|
| 260 |
+
"metrics": ActionType.GET_METRICS,
|
| 261 |
+
"get_alerts": ActionType.GET_ALERTS,
|
| 262 |
+
"alerts": ActionType.GET_ALERTS,
|
| 263 |
+
"restart_service": ActionType.RESTART_SERVICE,
|
| 264 |
+
"restart": ActionType.RESTART_SERVICE,
|
| 265 |
+
"scale_service": ActionType.SCALE_SERVICE,
|
| 266 |
+
"scale": ActionType.SCALE_SERVICE,
|
| 267 |
+
"rollback_service": ActionType.ROLLBACK_SERVICE,
|
| 268 |
+
"rollback": ActionType.ROLLBACK_SERVICE,
|
| 269 |
+
"update_config": ActionType.UPDATE_CONFIG,
|
| 270 |
+
"config": ActionType.UPDATE_CONFIG,
|
| 271 |
+
"run_diagnostic": ActionType.RUN_DIAGNOSTIC,
|
| 272 |
+
"diagnostic": ActionType.RUN_DIAGNOSTIC,
|
| 273 |
+
"diagnostics": ActionType.RUN_DIAGNOSTIC,
|
| 274 |
+
"resolve_incident": ActionType.RESOLVE_INCIDENT,
|
| 275 |
+
"resolve": ActionType.RESOLVE_INCIDENT,
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
if action_type in type_map:
|
| 279 |
+
action = Action(action_type=type_map[action_type], service=service)
|
| 280 |
+
|
| 281 |
+
if action_type in ["scale", "scale_service"] and param:
|
| 282 |
+
try:
|
| 283 |
+
action.scale_replicas = int(param)
|
| 284 |
+
except ValueError:
|
| 285 |
+
pass
|
| 286 |
+
|
| 287 |
+
if action_type in ["config", "update_config"] and param:
|
| 288 |
+
action.config_key = param
|
| 289 |
+
action.config_value = extra
|
| 290 |
+
|
| 291 |
+
return action
|
| 292 |
+
|
| 293 |
+
# Parse natural language
|
| 294 |
+
if "restart" in action_str:
|
| 295 |
+
service = self._extract_service_name(action_str)
|
| 296 |
+
return Action(action_type=ActionType.RESTART_SERVICE, service=service)
|
| 297 |
+
|
| 298 |
+
if "rollback" in action_str:
|
| 299 |
+
service = self._extract_service_name(action_str)
|
| 300 |
+
return Action(action_type=ActionType.ROLLBACK_SERVICE, service=service)
|
| 301 |
+
|
| 302 |
+
if "scale" in action_str:
|
| 303 |
+
service = self._extract_service_name(action_str)
|
| 304 |
+
replicas = self._extract_number(action_str) or 3
|
| 305 |
+
return Action(action_type=ActionType.SCALE_SERVICE, service=service, scale_replicas=replicas)
|
| 306 |
+
|
| 307 |
+
if "log" in action_str:
|
| 308 |
+
service = self._extract_service_name(action_str)
|
| 309 |
+
return Action(action_type=ActionType.READ_LOGS, service=service)
|
| 310 |
+
|
| 311 |
+
if "metric" in action_str:
|
| 312 |
+
service = self._extract_service_name(action_str)
|
| 313 |
+
return Action(action_type=ActionType.GET_METRICS, service=service)
|
| 314 |
+
|
| 315 |
+
if "alert" in action_str:
|
| 316 |
+
return Action(action_type=ActionType.GET_ALERTS)
|
| 317 |
+
|
| 318 |
+
if "diagnostic" in action_str:
|
| 319 |
+
service = self._extract_service_name(action_str)
|
| 320 |
+
return Action(action_type=ActionType.RUN_DIAGNOSTIC, service=service)
|
| 321 |
+
|
| 322 |
+
if "query" in action_str or "status" in action_str or "check" in action_str:
|
| 323 |
+
service = self._extract_service_name(action_str)
|
| 324 |
+
return Action(action_type=ActionType.QUERY_SERVICE, service=service)
|
| 325 |
+
|
| 326 |
+
if "config" in action_str:
|
| 327 |
+
service = self._extract_service_name(action_str)
|
| 328 |
+
return Action(action_type=ActionType.UPDATE_CONFIG, service=service)
|
| 329 |
+
|
| 330 |
+
# Default to query if service mentioned
|
| 331 |
+
service = self._extract_service_name(action_str)
|
| 332 |
+
if service:
|
| 333 |
+
return Action(action_type=ActionType.QUERY_SERVICE, service=service)
|
| 334 |
+
|
| 335 |
+
# Fallback
|
| 336 |
+
return Action(action_type=ActionType.GET_ALERTS)
|
| 337 |
+
|
| 338 |
+
def _extract_service_name(self, text: str) -> str | None:
|
| 339 |
+
"""Extract service name from text."""
|
| 340 |
+
services = self.infra.get_service_names()
|
| 341 |
+
text_lower = text.lower()
|
| 342 |
+
|
| 343 |
+
for service in services:
|
| 344 |
+
if service.lower() in text_lower:
|
| 345 |
+
return service
|
| 346 |
+
|
| 347 |
+
# Handle variations
|
| 348 |
+
simple_name = service.replace("-", "").replace("_", "")
|
| 349 |
+
if simple_name in text_lower.replace("-", "").replace("_", ""):
|
| 350 |
+
return service
|
| 351 |
+
|
| 352 |
+
return None
|
| 353 |
+
|
| 354 |
+
def _extract_number(self, text: str) -> int | None:
|
| 355 |
+
"""Extract a number from text."""
|
| 356 |
+
match = re.search(r"\d+", text)
|
| 357 |
+
return int(match.group()) if match else None
|
| 358 |
+
|
| 359 |
+
def _execute_action(self, action: Action) -> dict[str, Any]:
|
| 360 |
+
"""Execute an action and return the result."""
|
| 361 |
+
action_type = action.action_type
|
| 362 |
+
service_name = action.service
|
| 363 |
+
|
| 364 |
+
try:
|
| 365 |
+
if action_type == ActionType.QUERY_SERVICE:
|
| 366 |
+
if not service_name or service_name not in self.infra.services:
|
| 367 |
+
return {"success": False, "error": f"Unknown service: {service_name}"}
|
| 368 |
+
|
| 369 |
+
service = self.infra.services[service_name]
|
| 370 |
+
self.services_queried.add(service_name)
|
| 371 |
+
info = service.get_info()
|
| 372 |
+
self._observation.visible_services[service_name] = info
|
| 373 |
+
return {"success": True, "data": info.model_dump()}
|
| 374 |
+
|
| 375 |
+
elif action_type == ActionType.READ_LOGS:
|
| 376 |
+
if not service_name or service_name not in self.infra.services:
|
| 377 |
+
return {"success": False, "error": f"Unknown service: {service_name}"}
|
| 378 |
+
|
| 379 |
+
service = self.infra.services[service_name]
|
| 380 |
+
self.services_queried.add(service_name)
|
| 381 |
+
logs = service.get_logs(action.log_lines, action.log_level_filter)
|
| 382 |
+
self._observation.visible_logs.extend(logs)
|
| 383 |
+
return {"success": True, "data": [log.model_dump() for log in logs]}
|
| 384 |
+
|
| 385 |
+
elif action_type == ActionType.GET_METRICS:
|
| 386 |
+
if not service_name or service_name not in self.infra.services:
|
| 387 |
+
return {"success": False, "error": f"Unknown service: {service_name}"}
|
| 388 |
+
|
| 389 |
+
service = self.infra.services[service_name]
|
| 390 |
+
self.services_queried.add(service_name)
|
| 391 |
+
metrics = service.get_metrics()
|
| 392 |
+
self._observation.visible_metrics[service_name] = metrics
|
| 393 |
+
return {"success": True, "data": metrics.model_dump()}
|
| 394 |
+
|
| 395 |
+
elif action_type == ActionType.GET_ALERTS:
|
| 396 |
+
alerts = self.infra.get_alerts(service_name)
|
| 397 |
+
return {"success": True, "data": [a.model_dump() for a in alerts]}
|
| 398 |
+
|
| 399 |
+
elif action_type == ActionType.RESTART_SERVICE:
|
| 400 |
+
if not service_name or service_name not in self.infra.services:
|
| 401 |
+
return {"success": False, "error": f"Unknown service: {service_name}"}
|
| 402 |
+
|
| 403 |
+
service = self.infra.services[service_name]
|
| 404 |
+
success = service.restart()
|
| 405 |
+
|
| 406 |
+
# Track remediation
|
| 407 |
+
self._track_remediation(f"restart_service:{service_name}")
|
| 408 |
+
|
| 409 |
+
return {
|
| 410 |
+
"success": success,
|
| 411 |
+
"data": {"message": f"Service {service_name} restart {'successful' if success else 'failed'}"},
|
| 412 |
+
"error": None if success else "Service failed to restart",
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
elif action_type == ActionType.SCALE_SERVICE:
|
| 416 |
+
if not service_name or service_name not in self.infra.services:
|
| 417 |
+
return {"success": False, "error": f"Unknown service: {service_name}"}
|
| 418 |
+
|
| 419 |
+
service = self.infra.services[service_name]
|
| 420 |
+
success = service.scale(action.scale_replicas)
|
| 421 |
+
|
| 422 |
+
# Track remediation
|
| 423 |
+
self._track_remediation(f"scale_service:{service_name}")
|
| 424 |
+
|
| 425 |
+
return {
|
| 426 |
+
"success": success,
|
| 427 |
+
"data": {"message": f"Scaled {service_name} to {action.scale_replicas} replicas"},
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
elif action_type == ActionType.ROLLBACK_SERVICE:
|
| 431 |
+
if not service_name or service_name not in self.infra.services:
|
| 432 |
+
return {"success": False, "error": f"Unknown service: {service_name}"}
|
| 433 |
+
|
| 434 |
+
service = self.infra.services[service_name]
|
| 435 |
+
success = service.rollback()
|
| 436 |
+
|
| 437 |
+
# Track remediation
|
| 438 |
+
self._track_remediation(f"rollback_service:{service_name}")
|
| 439 |
+
|
| 440 |
+
return {
|
| 441 |
+
"success": success,
|
| 442 |
+
"data": {"message": f"Rollback of {service_name} {'successful' if success else 'failed'}"},
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
elif action_type == ActionType.UPDATE_CONFIG:
|
| 446 |
+
if not service_name or service_name not in self.infra.services:
|
| 447 |
+
return {"success": False, "error": f"Unknown service: {service_name}"}
|
| 448 |
+
|
| 449 |
+
if not action.config_key:
|
| 450 |
+
return {"success": False, "error": "No config key provided"}
|
| 451 |
+
|
| 452 |
+
service = self.infra.services[service_name]
|
| 453 |
+
success = service.update_config(action.config_key, action.config_value)
|
| 454 |
+
|
| 455 |
+
# Track remediation with key
|
| 456 |
+
self._track_remediation(f"update_config:{service_name}:{action.config_key}")
|
| 457 |
+
|
| 458 |
+
return {
|
| 459 |
+
"success": success,
|
| 460 |
+
"data": {"message": f"Config {action.config_key} updated on {service_name}"},
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
elif action_type == ActionType.RUN_DIAGNOSTIC:
|
| 464 |
+
if not service_name or service_name not in self.infra.services:
|
| 465 |
+
return {"success": False, "error": f"Unknown service: {service_name}"}
|
| 466 |
+
|
| 467 |
+
service = self.infra.services[service_name]
|
| 468 |
+
self.services_queried.add(service_name)
|
| 469 |
+
result = service.run_diagnostic()
|
| 470 |
+
self._observation.visible_diagnostics[service_name] = result
|
| 471 |
+
return {"success": True, "data": result.model_dump()}
|
| 472 |
+
|
| 473 |
+
elif action_type == ActionType.RESOLVE_INCIDENT:
|
| 474 |
+
# Check if actually resolved
|
| 475 |
+
if self._check_resolution():
|
| 476 |
+
return {"success": True, "data": {"message": "Incident resolved successfully"}}
|
| 477 |
+
else:
|
| 478 |
+
return {
|
| 479 |
+
"success": False,
|
| 480 |
+
"error": "Incident not yet resolved. Some services still unhealthy.",
|
| 481 |
+
"data": {"unhealthy_services": self._get_unhealthy_services()},
|
| 482 |
+
}
|
| 483 |
+
|
| 484 |
+
else:
|
| 485 |
+
return {"success": False, "error": f"Unknown action type: {action_type}"}
|
| 486 |
+
|
| 487 |
+
except Exception as e:
|
| 488 |
+
return {"success": False, "error": str(e)}
|
| 489 |
+
|
| 490 |
+
def _track_remediation(self, action: str):
|
| 491 |
+
"""Track remediation action for partial credit."""
|
| 492 |
+
# Check against required actions
|
| 493 |
+
for required in self.remediation_progress:
|
| 494 |
+
# Flexible matching
|
| 495 |
+
if action.startswith(required.split(":")[0]):
|
| 496 |
+
if required.split(":")[1] in action:
|
| 497 |
+
self.remediation_progress[required] = True
|
| 498 |
+
break
|
| 499 |
+
|
| 500 |
+
def _calculate_reward(self, action: Action, result: dict[str, Any]) -> Reward:
|
| 501 |
+
"""Calculate reward for an action."""
|
| 502 |
+
reward_value = 0.0
|
| 503 |
+
diagnosis_progress = 0.0
|
| 504 |
+
remediation_progress = 0.0
|
| 505 |
+
efficiency_bonus = 0.0
|
| 506 |
+
unnecessary_penalty = 0.0
|
| 507 |
+
harmful_penalty = 0.0
|
| 508 |
+
time_penalty = 0.0
|
| 509 |
+
reason = ""
|
| 510 |
+
|
| 511 |
+
action_type = action.action_type
|
| 512 |
+
success = result.get("success", False)
|
| 513 |
+
|
| 514 |
+
# Diagnostic actions (querying info)
|
| 515 |
+
if action_type in [
|
| 516 |
+
ActionType.QUERY_SERVICE,
|
| 517 |
+
ActionType.READ_LOGS,
|
| 518 |
+
ActionType.GET_METRICS,
|
| 519 |
+
ActionType.GET_ALERTS,
|
| 520 |
+
ActionType.RUN_DIAGNOSTIC,
|
| 521 |
+
]:
|
| 522 |
+
if success:
|
| 523 |
+
# Reward for investigating affected services
|
| 524 |
+
if action.service in self.scenario_data.get("affected_services", []):
|
| 525 |
+
reward_value += 0.02
|
| 526 |
+
diagnosis_progress += 0.1
|
| 527 |
+
reason = f"Investigated affected service: {action.service}"
|
| 528 |
+
else:
|
| 529 |
+
# Small reward for any investigation
|
| 530 |
+
reward_value += 0.005
|
| 531 |
+
diagnosis_progress += 0.02
|
| 532 |
+
reason = f"Investigated service: {action.service}"
|
| 533 |
+
|
| 534 |
+
# Bonus for comprehensive investigation
|
| 535 |
+
affected = set(self.scenario_data.get("affected_services", []))
|
| 536 |
+
if affected and affected.issubset(self.services_queried):
|
| 537 |
+
diagnosis_progress += 0.2
|
| 538 |
+
reward_value += 0.05
|
| 539 |
+
reason += " All affected services investigated."
|
| 540 |
+
|
| 541 |
+
# Remediation actions
|
| 542 |
+
elif action_type in [
|
| 543 |
+
ActionType.RESTART_SERVICE,
|
| 544 |
+
ActionType.SCALE_SERVICE,
|
| 545 |
+
ActionType.ROLLBACK_SERVICE,
|
| 546 |
+
ActionType.UPDATE_CONFIG,
|
| 547 |
+
]:
|
| 548 |
+
if success:
|
| 549 |
+
# Check if this is a required remediation
|
| 550 |
+
action_str = self._action_to_string(action)
|
| 551 |
+
is_required = any(
|
| 552 |
+
action_str.startswith(req.split(":")[0]) and req.split(":")[1] in action_str
|
| 553 |
+
for req in self.scenario_data.get("required_remediation", [])
|
| 554 |
+
)
|
| 555 |
+
|
| 556 |
+
if is_required:
|
| 557 |
+
reward_value += 0.1
|
| 558 |
+
remediation_progress += 0.25
|
| 559 |
+
reason = f"Correct remediation action: {action_str}"
|
| 560 |
+
else:
|
| 561 |
+
# Small penalty for unnecessary actions
|
| 562 |
+
reward_value -= 0.01
|
| 563 |
+
unnecessary_penalty = 0.01
|
| 564 |
+
reason = f"Unnecessary action: {action_str}"
|
| 565 |
+
else:
|
| 566 |
+
reward_value -= 0.02
|
| 567 |
+
reason = f"Action failed: {result.get('error', 'unknown error')}"
|
| 568 |
+
|
| 569 |
+
# Time penalty (encourage efficiency)
|
| 570 |
+
if self.current_step > self.task.max_steps * 0.8:
|
| 571 |
+
time_penalty = 0.01 * (self.current_step - self.task.max_steps * 0.8)
|
| 572 |
+
reward_value -= time_penalty
|
| 573 |
+
reason += f" Time pressure penalty: {time_penalty:.3f}"
|
| 574 |
+
|
| 575 |
+
# Efficiency bonus for quick resolution
|
| 576 |
+
if self._check_resolution():
|
| 577 |
+
efficiency_factor = 1.0 - (self.current_step / self.task.max_steps)
|
| 578 |
+
efficiency_bonus = efficiency_factor * 0.1
|
| 579 |
+
reward_value += efficiency_bonus
|
| 580 |
+
reason += f" Efficiency bonus: {efficiency_bonus:.3f}"
|
| 581 |
+
|
| 582 |
+
return Reward(
|
| 583 |
+
value=round(reward_value, 4),
|
| 584 |
+
diagnosis_progress=diagnosis_progress,
|
| 585 |
+
remediation_progress=remediation_progress,
|
| 586 |
+
efficiency_bonus=efficiency_bonus,
|
| 587 |
+
unnecessary_action_penalty=unnecessary_penalty,
|
| 588 |
+
harmful_action_penalty=harmful_penalty,
|
| 589 |
+
time_penalty=time_penalty,
|
| 590 |
+
reason=reason,
|
| 591 |
+
)
|
| 592 |
+
|
| 593 |
+
def _check_resolution(self) -> bool:
|
| 594 |
+
"""Check if the incident is resolved."""
|
| 595 |
+
# All affected services must be healthy
|
| 596 |
+
affected = self.scenario_data.get("affected_services", [])
|
| 597 |
+
for service_name in affected:
|
| 598 |
+
if service_name in self.infra.services:
|
| 599 |
+
service = self.infra.services[service_name]
|
| 600 |
+
if service.get_status() not in [ServiceStatus.HEALTHY, ServiceStatus.DEGRADED]:
|
| 601 |
+
return False
|
| 602 |
+
|
| 603 |
+
return True
|
| 604 |
+
|
| 605 |
+
def _get_unhealthy_services(self) -> list[str]:
|
| 606 |
+
"""Get list of unhealthy services."""
|
| 607 |
+
unhealthy = []
|
| 608 |
+
for name, service in self.infra.services.items():
|
| 609 |
+
if service.get_status() not in [ServiceStatus.HEALTHY]:
|
| 610 |
+
unhealthy.append(name)
|
| 611 |
+
return unhealthy
|
| 612 |
+
|
| 613 |
+
def _action_to_string(self, action: Action) -> str:
|
| 614 |
+
"""Convert action to string representation."""
|
| 615 |
+
parts = [action.action_type.value]
|
| 616 |
+
if action.service:
|
| 617 |
+
parts.append(action.service)
|
| 618 |
+
if action.config_key:
|
| 619 |
+
parts.append(action.config_key)
|
| 620 |
+
if action.config_value:
|
| 621 |
+
parts.append(str(action.config_value))
|
| 622 |
+
if action.scale_replicas and action.action_type == ActionType.SCALE_SERVICE:
|
| 623 |
+
parts.append(str(action.scale_replicas))
|
| 624 |
+
return ":".join(parts)
|
openenv-incident-response/src/graders.py
ADDED
|
@@ -0,0 +1,293 @@
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Task Graders for the DevOps Incident Response Environment.
|
| 3 |
+
|
| 4 |
+
Each grader evaluates agent performance on a specific task,
|
| 5 |
+
producing a score from 0.0 to 1.0 based on:
|
| 6 |
+
- Diagnosis accuracy (did the agent identify the root cause?)
|
| 7 |
+
- Remediation completeness (did the agent fix the issue?)
|
| 8 |
+
- Efficiency (how quickly was the issue resolved?)
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
from dataclasses import dataclass
|
| 14 |
+
from typing import Any
|
| 15 |
+
|
| 16 |
+
from .environment import IncidentResponseEnv
|
| 17 |
+
from .models import EnvironmentState, ServiceStatus
|
| 18 |
+
from .tasks import TASKS, TaskDefinition
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass
|
| 22 |
+
class GradeResult:
|
| 23 |
+
"""Result of grading an episode."""
|
| 24 |
+
|
| 25 |
+
score: float # 0.0 to 1.0
|
| 26 |
+
diagnosis_score: float
|
| 27 |
+
remediation_score: float
|
| 28 |
+
efficiency_score: float
|
| 29 |
+
details: dict[str, Any]
|
| 30 |
+
feedback: str
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class TaskGrader:
|
| 34 |
+
"""
|
| 35 |
+
Grades agent performance on incident response tasks.
|
| 36 |
+
|
| 37 |
+
Scoring is deterministic and based on:
|
| 38 |
+
1. Whether the agent investigated affected services
|
| 39 |
+
2. Whether the agent took correct remediation actions
|
| 40 |
+
3. Whether the incident was resolved
|
| 41 |
+
4. How efficiently the agent resolved the incident
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
def __init__(self, task: TaskDefinition):
|
| 45 |
+
self.task = task
|
| 46 |
+
|
| 47 |
+
def grade(self, env: IncidentResponseEnv) -> GradeResult:
|
| 48 |
+
"""
|
| 49 |
+
Grade the agent's performance on a completed episode.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
env: The environment after the episode
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
GradeResult with score and breakdown
|
| 56 |
+
"""
|
| 57 |
+
state = env.state()
|
| 58 |
+
|
| 59 |
+
# Calculate component scores
|
| 60 |
+
diagnosis_score = self._score_diagnosis(env, state)
|
| 61 |
+
remediation_score = self._score_remediation(env, state)
|
| 62 |
+
efficiency_score = self._score_efficiency(env, state)
|
| 63 |
+
|
| 64 |
+
# Weighted combination
|
| 65 |
+
final_score = (
|
| 66 |
+
diagnosis_score * self.task.diagnosis_weight
|
| 67 |
+
+ remediation_score * self.task.remediation_weight
|
| 68 |
+
+ efficiency_score * self.task.efficiency_weight
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
# Clamp to [0.0, 1.0]
|
| 72 |
+
final_score = max(0.0, min(1.0, final_score))
|
| 73 |
+
|
| 74 |
+
# Generate feedback
|
| 75 |
+
feedback = self._generate_feedback(
|
| 76 |
+
diagnosis_score, remediation_score, efficiency_score, state
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
return GradeResult(
|
| 80 |
+
score=round(final_score, 4),
|
| 81 |
+
diagnosis_score=round(diagnosis_score, 4),
|
| 82 |
+
remediation_score=round(remediation_score, 4),
|
| 83 |
+
efficiency_score=round(efficiency_score, 4),
|
| 84 |
+
details={
|
| 85 |
+
"services_queried": list(env.services_queried),
|
| 86 |
+
"affected_services": env.scenario_data.get("affected_services", []),
|
| 87 |
+
"actions_taken": env.actions_taken,
|
| 88 |
+
"required_remediation": env.scenario_data.get("required_remediation", []),
|
| 89 |
+
"remediation_progress": env.remediation_progress,
|
| 90 |
+
"resolved": state.resolved,
|
| 91 |
+
"steps_used": state.episode_step,
|
| 92 |
+
"max_steps": state.max_steps,
|
| 93 |
+
},
|
| 94 |
+
feedback=feedback,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
def _score_diagnosis(self, env: IncidentResponseEnv, state: EnvironmentState) -> float:
|
| 98 |
+
"""
|
| 99 |
+
Score the agent's diagnostic investigation.
|
| 100 |
+
|
| 101 |
+
Full credit for investigating all affected services.
|
| 102 |
+
Partial credit proportional to coverage.
|
| 103 |
+
"""
|
| 104 |
+
affected = set(env.scenario_data.get("affected_services", []))
|
| 105 |
+
queried = env.services_queried
|
| 106 |
+
|
| 107 |
+
if not affected:
|
| 108 |
+
return 1.0 # No affected services = automatic pass
|
| 109 |
+
|
| 110 |
+
# Calculate coverage
|
| 111 |
+
covered = affected.intersection(queried)
|
| 112 |
+
coverage = len(covered) / len(affected)
|
| 113 |
+
|
| 114 |
+
# Bonus for using diagnostic tools
|
| 115 |
+
diagnostic_bonus = 0.0
|
| 116 |
+
diagnostic_count = sum(
|
| 117 |
+
1 for a in env.actions_taken
|
| 118 |
+
if "diagnostic" in a.lower() or "logs" in a.lower() or "metrics" in a.lower()
|
| 119 |
+
)
|
| 120 |
+
if diagnostic_count > 0:
|
| 121 |
+
diagnostic_bonus = min(0.1, diagnostic_count * 0.02)
|
| 122 |
+
|
| 123 |
+
return min(1.0, coverage + diagnostic_bonus)
|
| 124 |
+
|
| 125 |
+
def _score_remediation(self, env: IncidentResponseEnv, state: EnvironmentState) -> float:
|
| 126 |
+
"""
|
| 127 |
+
Score the agent's remediation actions.
|
| 128 |
+
|
| 129 |
+
Full credit for completing all required remediation actions.
|
| 130 |
+
Partial credit for partial completion.
|
| 131 |
+
Major bonus for actually resolving the incident.
|
| 132 |
+
"""
|
| 133 |
+
required = env.scenario_data.get("required_remediation", [])
|
| 134 |
+
progress = env.remediation_progress
|
| 135 |
+
|
| 136 |
+
if not required:
|
| 137 |
+
return 1.0 if state.resolved else 0.5
|
| 138 |
+
|
| 139 |
+
# Count completed remediation actions
|
| 140 |
+
completed = sum(1 for r in progress.values() if r)
|
| 141 |
+
completion_rate = completed / len(required)
|
| 142 |
+
|
| 143 |
+
# Resolution bonus - this is the main goal
|
| 144 |
+
resolution_bonus = 0.4 if state.resolved else 0.0
|
| 145 |
+
|
| 146 |
+
# Penalty for unnecessary actions
|
| 147 |
+
unnecessary_actions = len(env.actions_taken) - len(
|
| 148 |
+
[a for a in env.actions_taken if any(req.split(":")[0] in a for req in required)]
|
| 149 |
+
)
|
| 150 |
+
unnecessary_penalty = min(0.2, unnecessary_actions * 0.02)
|
| 151 |
+
|
| 152 |
+
score = completion_rate * 0.6 + resolution_bonus - unnecessary_penalty
|
| 153 |
+
return max(0.0, min(1.0, score))
|
| 154 |
+
|
| 155 |
+
def _score_efficiency(self, env: IncidentResponseEnv, state: EnvironmentState) -> float:
|
| 156 |
+
"""
|
| 157 |
+
Score the agent's efficiency.
|
| 158 |
+
|
| 159 |
+
Based on how quickly the incident was resolved relative to max steps.
|
| 160 |
+
"""
|
| 161 |
+
steps_used = state.episode_step
|
| 162 |
+
max_steps = state.max_steps
|
| 163 |
+
|
| 164 |
+
if not state.resolved:
|
| 165 |
+
# No efficiency bonus if not resolved
|
| 166 |
+
return 0.0
|
| 167 |
+
|
| 168 |
+
# Linear scaling: fewer steps = higher score
|
| 169 |
+
# Perfect efficiency at 30% of max steps
|
| 170 |
+
# Zero efficiency at max steps
|
| 171 |
+
optimal = max_steps * 0.3
|
| 172 |
+
if steps_used <= optimal:
|
| 173 |
+
return 1.0
|
| 174 |
+
elif steps_used >= max_steps:
|
| 175 |
+
return 0.0
|
| 176 |
+
else:
|
| 177 |
+
return 1.0 - (steps_used - optimal) / (max_steps - optimal)
|
| 178 |
+
|
| 179 |
+
def _generate_feedback(
|
| 180 |
+
self,
|
| 181 |
+
diagnosis_score: float,
|
| 182 |
+
remediation_score: float,
|
| 183 |
+
efficiency_score: float,
|
| 184 |
+
state: EnvironmentState,
|
| 185 |
+
) -> str:
|
| 186 |
+
"""Generate human-readable feedback."""
|
| 187 |
+
feedback_parts = []
|
| 188 |
+
|
| 189 |
+
# Diagnosis feedback
|
| 190 |
+
if diagnosis_score >= 0.8:
|
| 191 |
+
feedback_parts.append("Excellent investigation - all affected services were analyzed.")
|
| 192 |
+
elif diagnosis_score >= 0.5:
|
| 193 |
+
feedback_parts.append("Partial investigation - consider checking all affected services.")
|
| 194 |
+
else:
|
| 195 |
+
feedback_parts.append("Limited investigation - more diagnostic work needed.")
|
| 196 |
+
|
| 197 |
+
# Remediation feedback
|
| 198 |
+
if remediation_score >= 0.8:
|
| 199 |
+
feedback_parts.append("Strong remediation - correct actions taken.")
|
| 200 |
+
elif remediation_score >= 0.5:
|
| 201 |
+
feedback_parts.append("Partial remediation - some required fixes were missed.")
|
| 202 |
+
else:
|
| 203 |
+
feedback_parts.append("Incomplete remediation - review the required actions.")
|
| 204 |
+
|
| 205 |
+
# Efficiency feedback
|
| 206 |
+
if state.resolved:
|
| 207 |
+
if efficiency_score >= 0.8:
|
| 208 |
+
feedback_parts.append("Very efficient resolution!")
|
| 209 |
+
elif efficiency_score >= 0.5:
|
| 210 |
+
feedback_parts.append("Resolved in reasonable time.")
|
| 211 |
+
else:
|
| 212 |
+
feedback_parts.append("Resolved but could be faster.")
|
| 213 |
+
else:
|
| 214 |
+
feedback_parts.append("Incident was not fully resolved.")
|
| 215 |
+
|
| 216 |
+
return " ".join(feedback_parts)
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def grade_task(task_id: str, env: IncidentResponseEnv) -> GradeResult:
|
| 220 |
+
"""
|
| 221 |
+
Grade a specific task.
|
| 222 |
+
|
| 223 |
+
Args:
|
| 224 |
+
task_id: The task identifier
|
| 225 |
+
env: The environment after the episode
|
| 226 |
+
|
| 227 |
+
Returns:
|
| 228 |
+
GradeResult with score and details
|
| 229 |
+
"""
|
| 230 |
+
task = TASKS.get(task_id)
|
| 231 |
+
if not task:
|
| 232 |
+
raise ValueError(f"Unknown task: {task_id}")
|
| 233 |
+
|
| 234 |
+
grader = TaskGrader(task)
|
| 235 |
+
return grader.grade(env)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def grade_all_tasks(results: dict[str, IncidentResponseEnv]) -> dict[str, GradeResult]:
|
| 239 |
+
"""
|
| 240 |
+
Grade all tasks from a set of completed environments.
|
| 241 |
+
|
| 242 |
+
Args:
|
| 243 |
+
results: Dictionary mapping task_id to completed environment
|
| 244 |
+
|
| 245 |
+
Returns:
|
| 246 |
+
Dictionary mapping task_id to GradeResult
|
| 247 |
+
"""
|
| 248 |
+
grades = {}
|
| 249 |
+
for task_id, env in results.items():
|
| 250 |
+
if task_id in TASKS:
|
| 251 |
+
grades[task_id] = grade_task(task_id, env)
|
| 252 |
+
return grades
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
# ============================================================================
|
| 256 |
+
# Validation Helpers
|
| 257 |
+
# ============================================================================
|
| 258 |
+
|
| 259 |
+
def validate_grader(task_id: str) -> bool:
|
| 260 |
+
"""
|
| 261 |
+
Validate that a grader produces scores in the correct range.
|
| 262 |
+
|
| 263 |
+
This is used by the OpenEnv validator.
|
| 264 |
+
"""
|
| 265 |
+
task = TASKS.get(task_id)
|
| 266 |
+
if not task:
|
| 267 |
+
return False
|
| 268 |
+
|
| 269 |
+
grader = TaskGrader(task)
|
| 270 |
+
|
| 271 |
+
# Test with a fresh environment
|
| 272 |
+
env = IncidentResponseEnv(task_id=task_id)
|
| 273 |
+
env.reset()
|
| 274 |
+
|
| 275 |
+
# Grade with no actions (should be low but valid)
|
| 276 |
+
result = grader.grade(env)
|
| 277 |
+
|
| 278 |
+
# Validate score range
|
| 279 |
+
if not (0.0 <= result.score <= 1.0):
|
| 280 |
+
return False
|
| 281 |
+
if not (0.0 <= result.diagnosis_score <= 1.0):
|
| 282 |
+
return False
|
| 283 |
+
if not (0.0 <= result.remediation_score <= 1.0):
|
| 284 |
+
return False
|
| 285 |
+
if not (0.0 <= result.efficiency_score <= 1.0):
|
| 286 |
+
return False
|
| 287 |
+
|
| 288 |
+
return True
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def validate_all_graders() -> dict[str, bool]:
|
| 292 |
+
"""Validate all task graders."""
|
| 293 |
+
return {task_id: validate_grader(task_id) for task_id in TASKS}
|
openenv-incident-response/src/models.py
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pydantic models for the DevOps Incident Response Environment.
|
| 3 |
+
|
| 4 |
+
This module defines typed models for observations, actions, and rewards
|
| 5 |
+
following the OpenEnv specification.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from enum import Enum
|
| 12 |
+
from typing import Any, Optional
|
| 13 |
+
|
| 14 |
+
from pydantic import BaseModel, Field
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# ============================================================================
|
| 18 |
+
# Enums
|
| 19 |
+
# ============================================================================
|
| 20 |
+
|
| 21 |
+
class ServiceStatus(str, Enum):
|
| 22 |
+
"""Status of a microservice."""
|
| 23 |
+
HEALTHY = "healthy"
|
| 24 |
+
DEGRADED = "degraded"
|
| 25 |
+
UNHEALTHY = "unhealthy"
|
| 26 |
+
DOWN = "down"
|
| 27 |
+
UNKNOWN = "unknown"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class AlertSeverity(str, Enum):
|
| 31 |
+
"""Severity levels for alerts."""
|
| 32 |
+
CRITICAL = "critical"
|
| 33 |
+
WARNING = "warning"
|
| 34 |
+
INFO = "info"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class LogLevel(str, Enum):
|
| 38 |
+
"""Log levels."""
|
| 39 |
+
ERROR = "ERROR"
|
| 40 |
+
WARN = "WARN"
|
| 41 |
+
INFO = "INFO"
|
| 42 |
+
DEBUG = "DEBUG"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class ActionType(str, Enum):
|
| 46 |
+
"""Types of actions the agent can take."""
|
| 47 |
+
QUERY_SERVICE = "query_service"
|
| 48 |
+
READ_LOGS = "read_logs"
|
| 49 |
+
GET_METRICS = "get_metrics"
|
| 50 |
+
GET_ALERTS = "get_alerts"
|
| 51 |
+
RESTART_SERVICE = "restart_service"
|
| 52 |
+
SCALE_SERVICE = "scale_service"
|
| 53 |
+
ROLLBACK_SERVICE = "rollback_service"
|
| 54 |
+
UPDATE_CONFIG = "update_config"
|
| 55 |
+
RUN_DIAGNOSTIC = "run_diagnostic"
|
| 56 |
+
RESOLVE_INCIDENT = "resolve_incident"
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# ============================================================================
|
| 60 |
+
# Sub-models for Observations
|
| 61 |
+
# ============================================================================
|
| 62 |
+
|
| 63 |
+
class LogEntry(BaseModel):
|
| 64 |
+
"""A single log entry from a service."""
|
| 65 |
+
timestamp: datetime
|
| 66 |
+
level: LogLevel
|
| 67 |
+
service: str
|
| 68 |
+
message: str
|
| 69 |
+
trace_id: Optional[str] = None
|
| 70 |
+
metadata: dict[str, Any] = Field(default_factory=dict)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class MetricData(BaseModel):
|
| 74 |
+
"""Metrics for a service."""
|
| 75 |
+
service: str
|
| 76 |
+
timestamp: datetime
|
| 77 |
+
cpu_percent: float = Field(ge=0, le=100)
|
| 78 |
+
memory_percent: float = Field(ge=0, le=100)
|
| 79 |
+
memory_mb: float = Field(ge=0)
|
| 80 |
+
memory_limit_mb: float = Field(ge=0)
|
| 81 |
+
request_rate: float = Field(ge=0, description="Requests per second")
|
| 82 |
+
error_rate: float = Field(ge=0, le=100, description="Percentage of requests erroring")
|
| 83 |
+
latency_p50_ms: float = Field(ge=0)
|
| 84 |
+
latency_p99_ms: float = Field(ge=0)
|
| 85 |
+
active_connections: int = Field(ge=0)
|
| 86 |
+
healthy_replicas: int = Field(ge=0)
|
| 87 |
+
total_replicas: int = Field(ge=0)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class Alert(BaseModel):
|
| 91 |
+
"""An alert from the monitoring system."""
|
| 92 |
+
id: str
|
| 93 |
+
timestamp: datetime
|
| 94 |
+
severity: AlertSeverity
|
| 95 |
+
service: str
|
| 96 |
+
title: str
|
| 97 |
+
description: str
|
| 98 |
+
firing: bool = True
|
| 99 |
+
labels: dict[str, str] = Field(default_factory=dict)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class ServiceInfo(BaseModel):
|
| 103 |
+
"""Information about a service."""
|
| 104 |
+
name: str
|
| 105 |
+
status: ServiceStatus
|
| 106 |
+
version: str
|
| 107 |
+
replicas: int
|
| 108 |
+
healthy_replicas: int
|
| 109 |
+
last_deploy: datetime
|
| 110 |
+
dependencies: list[str] = Field(default_factory=list)
|
| 111 |
+
config: dict[str, Any] = Field(default_factory=dict)
|
| 112 |
+
endpoints: list[str] = Field(default_factory=list)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class DiagnosticResult(BaseModel):
|
| 116 |
+
"""Result of running diagnostics on a service."""
|
| 117 |
+
service: str
|
| 118 |
+
timestamp: datetime
|
| 119 |
+
checks: dict[str, bool]
|
| 120 |
+
details: dict[str, str]
|
| 121 |
+
recommendations: list[str] = Field(default_factory=list)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class IncidentInfo(BaseModel):
|
| 125 |
+
"""Information about the current incident."""
|
| 126 |
+
id: str
|
| 127 |
+
title: str
|
| 128 |
+
severity: AlertSeverity
|
| 129 |
+
started_at: datetime
|
| 130 |
+
description: str
|
| 131 |
+
affected_services: list[str]
|
| 132 |
+
customer_impact: str
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# ============================================================================
|
| 136 |
+
# Main Observation Model
|
| 137 |
+
# ============================================================================
|
| 138 |
+
|
| 139 |
+
class Observation(BaseModel):
|
| 140 |
+
"""
|
| 141 |
+
The observation returned by the environment after each step.
|
| 142 |
+
|
| 143 |
+
Contains all information the agent can observe about the current
|
| 144 |
+
state of the incident and infrastructure.
|
| 145 |
+
"""
|
| 146 |
+
# Incident context
|
| 147 |
+
incident: IncidentInfo
|
| 148 |
+
|
| 149 |
+
# Current step number
|
| 150 |
+
step: int = 0
|
| 151 |
+
|
| 152 |
+
# Results from the last action
|
| 153 |
+
last_action: Optional[str] = None
|
| 154 |
+
last_action_success: bool = True
|
| 155 |
+
last_action_error: Optional[str] = None
|
| 156 |
+
last_action_result: Optional[dict[str, Any]] = None
|
| 157 |
+
|
| 158 |
+
# Currently visible data (populated by query actions)
|
| 159 |
+
visible_services: dict[str, ServiceInfo] = Field(default_factory=dict)
|
| 160 |
+
visible_logs: list[LogEntry] = Field(default_factory=list)
|
| 161 |
+
visible_metrics: dict[str, MetricData] = Field(default_factory=dict)
|
| 162 |
+
visible_alerts: list[Alert] = Field(default_factory=list)
|
| 163 |
+
visible_diagnostics: dict[str, DiagnosticResult] = Field(default_factory=dict)
|
| 164 |
+
|
| 165 |
+
# Action history
|
| 166 |
+
action_history: list[str] = Field(default_factory=list)
|
| 167 |
+
|
| 168 |
+
# Available services in the system
|
| 169 |
+
available_services: list[str] = Field(default_factory=list)
|
| 170 |
+
|
| 171 |
+
# Hint for the agent (optional, used in easier tasks)
|
| 172 |
+
hint: Optional[str] = None
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# ============================================================================
|
| 176 |
+
# Action Model
|
| 177 |
+
# ============================================================================
|
| 178 |
+
|
| 179 |
+
class Action(BaseModel):
|
| 180 |
+
"""
|
| 181 |
+
An action the agent can take in the environment.
|
| 182 |
+
|
| 183 |
+
The agent must specify an action type and relevant parameters.
|
| 184 |
+
"""
|
| 185 |
+
action_type: ActionType
|
| 186 |
+
|
| 187 |
+
# Target service for service-specific actions
|
| 188 |
+
service: Optional[str] = None
|
| 189 |
+
|
| 190 |
+
# Parameters for specific actions
|
| 191 |
+
log_lines: int = Field(default=20, ge=1, le=100, description="Number of log lines to fetch")
|
| 192 |
+
log_level_filter: Optional[LogLevel] = None
|
| 193 |
+
|
| 194 |
+
scale_replicas: int = Field(default=1, ge=0, le=10, description="Target replica count")
|
| 195 |
+
|
| 196 |
+
config_key: Optional[str] = None
|
| 197 |
+
config_value: Optional[Any] = None
|
| 198 |
+
|
| 199 |
+
# For resolve_incident action
|
| 200 |
+
root_cause: Optional[str] = None
|
| 201 |
+
resolution_summary: Optional[str] = None
|
| 202 |
+
|
| 203 |
+
# Raw action string (for compatibility)
|
| 204 |
+
action_str: Optional[str] = None
|
| 205 |
+
|
| 206 |
+
class Config:
|
| 207 |
+
use_enum_values = True
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
# ============================================================================
|
| 211 |
+
# Reward Model
|
| 212 |
+
# ============================================================================
|
| 213 |
+
|
| 214 |
+
class Reward(BaseModel):
|
| 215 |
+
"""
|
| 216 |
+
Reward signal from the environment.
|
| 217 |
+
|
| 218 |
+
Provides both a scalar reward and detailed breakdown for interpretability.
|
| 219 |
+
"""
|
| 220 |
+
# Main reward value (0.0 to 1.0 for final, can be negative during episode)
|
| 221 |
+
value: float
|
| 222 |
+
|
| 223 |
+
# Detailed breakdown
|
| 224 |
+
diagnosis_progress: float = Field(default=0.0, description="Progress toward identifying root cause")
|
| 225 |
+
remediation_progress: float = Field(default=0.0, description="Progress toward fixing the issue")
|
| 226 |
+
efficiency_bonus: float = Field(default=0.0, description="Bonus for efficient resolution")
|
| 227 |
+
|
| 228 |
+
# Penalties
|
| 229 |
+
unnecessary_action_penalty: float = Field(default=0.0, description="Penalty for redundant actions")
|
| 230 |
+
harmful_action_penalty: float = Field(default=0.0, description="Penalty for making things worse")
|
| 231 |
+
time_penalty: float = Field(default=0.0, description="Penalty for taking too long")
|
| 232 |
+
|
| 233 |
+
# Explanation
|
| 234 |
+
reason: str = ""
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
# ============================================================================
|
| 238 |
+
# State Model (for state() endpoint)
|
| 239 |
+
# ============================================================================
|
| 240 |
+
|
| 241 |
+
class EnvironmentState(BaseModel):
|
| 242 |
+
"""
|
| 243 |
+
Full environment state for serialization.
|
| 244 |
+
|
| 245 |
+
Used by the state() endpoint for checkpointing/debugging.
|
| 246 |
+
"""
|
| 247 |
+
# Task information
|
| 248 |
+
task_id: str
|
| 249 |
+
task_difficulty: str
|
| 250 |
+
|
| 251 |
+
# Episode state
|
| 252 |
+
episode_step: int
|
| 253 |
+
max_steps: int
|
| 254 |
+
done: bool
|
| 255 |
+
|
| 256 |
+
# Current observation
|
| 257 |
+
observation: Observation
|
| 258 |
+
|
| 259 |
+
# Cumulative reward
|
| 260 |
+
total_reward: float
|
| 261 |
+
|
| 262 |
+
# Ground truth (for grading)
|
| 263 |
+
root_cause: str
|
| 264 |
+
required_actions: list[str]
|
| 265 |
+
|
| 266 |
+
# Internal simulator state
|
| 267 |
+
services_state: dict[str, dict[str, Any]]
|
| 268 |
+
resolved: bool
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
# ============================================================================
|
| 272 |
+
# Step Result Model
|
| 273 |
+
# ============================================================================
|
| 274 |
+
|
| 275 |
+
class StepResult(BaseModel):
|
| 276 |
+
"""Result of calling step() on the environment."""
|
| 277 |
+
observation: Observation
|
| 278 |
+
reward: Reward
|
| 279 |
+
done: bool
|
| 280 |
+
info: dict[str, Any] = Field(default_factory=dict)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
# ============================================================================
|
| 284 |
+
# Task Definition Model
|
| 285 |
+
# ============================================================================
|
| 286 |
+
|
| 287 |
+
class TaskDefinition(BaseModel):
|
| 288 |
+
"""Definition of a task/scenario."""
|
| 289 |
+
id: str
|
| 290 |
+
name: str
|
| 291 |
+
difficulty: str # "easy", "medium", "hard"
|
| 292 |
+
description: str
|
| 293 |
+
max_steps: int
|
| 294 |
+
time_limit_seconds: int
|
| 295 |
+
|
| 296 |
+
# Scenario configuration
|
| 297 |
+
incident_title: str
|
| 298 |
+
incident_description: str
|
| 299 |
+
incident_severity: AlertSeverity
|
| 300 |
+
affected_services: list[str]
|
| 301 |
+
customer_impact: str
|
| 302 |
+
|
| 303 |
+
# Ground truth
|
| 304 |
+
root_cause: str
|
| 305 |
+
required_remediation: list[str]
|
| 306 |
+
|
| 307 |
+
# Scoring weights
|
| 308 |
+
diagnosis_weight: float = 0.4
|
| 309 |
+
remediation_weight: float = 0.5
|
| 310 |
+
efficiency_weight: float = 0.1
|
openenv-incident-response/src/simulator.py
ADDED
|
@@ -0,0 +1,801 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Infrastructure Simulator for the DevOps Incident Response Environment.
|
| 3 |
+
|
| 4 |
+
This module simulates a microservices architecture with realistic:
|
| 5 |
+
- Service health states and dependencies
|
| 6 |
+
- Log generation with error patterns
|
| 7 |
+
- Metrics (CPU, memory, latency, error rates)
|
| 8 |
+
- Alerts from monitoring systems
|
| 9 |
+
- Service behaviors and failure modes
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import copy
|
| 15 |
+
import random
|
| 16 |
+
import uuid
|
| 17 |
+
from datetime import datetime, timedelta
|
| 18 |
+
from typing import Any, Optional
|
| 19 |
+
|
| 20 |
+
from .models import (
|
| 21 |
+
Alert,
|
| 22 |
+
AlertSeverity,
|
| 23 |
+
DiagnosticResult,
|
| 24 |
+
LogEntry,
|
| 25 |
+
LogLevel,
|
| 26 |
+
MetricData,
|
| 27 |
+
ServiceInfo,
|
| 28 |
+
ServiceStatus,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class ServiceSimulator:
|
| 33 |
+
"""Simulates a single microservice."""
|
| 34 |
+
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
name: str,
|
| 38 |
+
version: str = "1.0.0",
|
| 39 |
+
replicas: int = 3,
|
| 40 |
+
dependencies: list[str] | None = None,
|
| 41 |
+
config: dict[str, Any] | None = None,
|
| 42 |
+
):
|
| 43 |
+
self.name = name
|
| 44 |
+
self.version = version
|
| 45 |
+
self.replicas = replicas
|
| 46 |
+
self.healthy_replicas = replicas
|
| 47 |
+
self.dependencies = dependencies or []
|
| 48 |
+
self.config = config or {}
|
| 49 |
+
self.endpoints = [f"/{name}/health", f"/{name}/api/v1"]
|
| 50 |
+
self.last_deploy = datetime.now() - timedelta(days=random.randint(1, 30))
|
| 51 |
+
|
| 52 |
+
# Internal state
|
| 53 |
+
self._status = ServiceStatus.HEALTHY
|
| 54 |
+
self._cpu_base = random.uniform(10, 30)
|
| 55 |
+
self._memory_base = random.uniform(20, 40)
|
| 56 |
+
self._memory_limit = 512.0
|
| 57 |
+
self._latency_base = random.uniform(10, 50)
|
| 58 |
+
self._error_rate = 0.0
|
| 59 |
+
self._request_rate = random.uniform(100, 500)
|
| 60 |
+
|
| 61 |
+
# Failure injection
|
| 62 |
+
self._failure_mode: Optional[str] = None
|
| 63 |
+
self._failure_params: dict[str, Any] = {}
|
| 64 |
+
|
| 65 |
+
# Log buffer
|
| 66 |
+
self._logs: list[LogEntry] = []
|
| 67 |
+
self._log_id = 0
|
| 68 |
+
|
| 69 |
+
def inject_failure(self, mode: str, params: dict[str, Any] | None = None):
|
| 70 |
+
"""Inject a failure mode into the service."""
|
| 71 |
+
self._failure_mode = mode
|
| 72 |
+
self._failure_params = params or {}
|
| 73 |
+
self._apply_failure_effects()
|
| 74 |
+
|
| 75 |
+
def clear_failure(self):
|
| 76 |
+
"""Clear any injected failures."""
|
| 77 |
+
self._failure_mode = None
|
| 78 |
+
self._failure_params = {}
|
| 79 |
+
self._status = ServiceStatus.HEALTHY
|
| 80 |
+
self.healthy_replicas = self.replicas
|
| 81 |
+
self._error_rate = 0.0
|
| 82 |
+
|
| 83 |
+
def _apply_failure_effects(self):
|
| 84 |
+
"""Apply effects based on the current failure mode."""
|
| 85 |
+
mode = self._failure_mode
|
| 86 |
+
params = self._failure_params
|
| 87 |
+
|
| 88 |
+
if mode == "oom":
|
| 89 |
+
# Out of memory - service crashes and restarts
|
| 90 |
+
self._status = ServiceStatus.UNHEALTHY
|
| 91 |
+
self.healthy_replicas = 0
|
| 92 |
+
self._memory_base = 95.0
|
| 93 |
+
self._add_log(LogLevel.ERROR, "OutOfMemoryError: Java heap space")
|
| 94 |
+
self._add_log(LogLevel.ERROR, "Container killed due to OOM (exit code 137)")
|
| 95 |
+
self._add_log(LogLevel.WARN, "Service restarting...")
|
| 96 |
+
self._error_rate = 100.0
|
| 97 |
+
|
| 98 |
+
elif mode == "memory_leak":
|
| 99 |
+
# Memory leak - gradual memory increase
|
| 100 |
+
self._memory_base = params.get("memory_percent", 85.0)
|
| 101 |
+
self._status = ServiceStatus.DEGRADED
|
| 102 |
+
self.healthy_replicas = max(1, self.replicas - 1)
|
| 103 |
+
self._add_log(LogLevel.WARN, f"High memory usage detected: {self._memory_base:.1f}%")
|
| 104 |
+
self._add_log(LogLevel.WARN, "GC overhead limit exceeded")
|
| 105 |
+
self._error_rate = 15.0
|
| 106 |
+
|
| 107 |
+
elif mode == "cpu_spike":
|
| 108 |
+
# CPU spike - high CPU usage
|
| 109 |
+
self._cpu_base = params.get("cpu_percent", 95.0)
|
| 110 |
+
self._status = ServiceStatus.DEGRADED
|
| 111 |
+
self._latency_base = 500.0
|
| 112 |
+
self._add_log(LogLevel.WARN, f"High CPU usage: {self._cpu_base:.1f}%")
|
| 113 |
+
self._add_log(LogLevel.WARN, "Request processing delayed due to CPU contention")
|
| 114 |
+
self._error_rate = 5.0
|
| 115 |
+
|
| 116 |
+
elif mode == "dependency_timeout":
|
| 117 |
+
# Dependency is timing out
|
| 118 |
+
dep = params.get("dependency", "unknown")
|
| 119 |
+
self._status = ServiceStatus.DEGRADED
|
| 120 |
+
self._latency_base = 5000.0 # 5 second timeout
|
| 121 |
+
self._error_rate = 50.0
|
| 122 |
+
self._add_log(LogLevel.ERROR, f"Connection timeout to {dep}: Read timed out after 5000ms")
|
| 123 |
+
self._add_log(LogLevel.ERROR, f"CircuitBreaker for {dep} is OPEN")
|
| 124 |
+
self._add_log(LogLevel.WARN, "Fallback activated for degraded dependency")
|
| 125 |
+
|
| 126 |
+
elif mode == "database_connection_pool":
|
| 127 |
+
# Database connection pool exhausted
|
| 128 |
+
self._status = ServiceStatus.DEGRADED
|
| 129 |
+
self._error_rate = 60.0
|
| 130 |
+
self._add_log(LogLevel.ERROR, "HikariPool-1 - Connection is not available, request timed out after 30000ms")
|
| 131 |
+
self._add_log(LogLevel.ERROR, "Unable to acquire JDBC Connection")
|
| 132 |
+
self._add_log(LogLevel.WARN, f"Active connections: {params.get('active', 50)}/{params.get('max', 50)}")
|
| 133 |
+
|
| 134 |
+
elif mode == "bad_deploy":
|
| 135 |
+
# Bad deployment - service is crashing on startup
|
| 136 |
+
self._status = ServiceStatus.UNHEALTHY
|
| 137 |
+
self.healthy_replicas = 0
|
| 138 |
+
self._error_rate = 100.0
|
| 139 |
+
self._add_log(LogLevel.ERROR, "Application failed to start")
|
| 140 |
+
self._add_log(LogLevel.ERROR, f"NullPointerException at {self.name}.Application.main(Application.java:42)")
|
| 141 |
+
self._add_log(LogLevel.ERROR, "CrashLoopBackOff: restarting failed container")
|
| 142 |
+
|
| 143 |
+
elif mode == "config_error":
|
| 144 |
+
# Configuration error
|
| 145 |
+
key = params.get("config_key", "UNKNOWN_CONFIG")
|
| 146 |
+
self._status = ServiceStatus.UNHEALTHY
|
| 147 |
+
self.healthy_replicas = 0
|
| 148 |
+
self._error_rate = 100.0
|
| 149 |
+
self._add_log(LogLevel.ERROR, f"Failed to parse configuration: {key}")
|
| 150 |
+
self._add_log(LogLevel.ERROR, "IllegalArgumentException: Invalid configuration value")
|
| 151 |
+
|
| 152 |
+
elif mode == "network_partition":
|
| 153 |
+
# Network partition - some replicas can't communicate
|
| 154 |
+
self._status = ServiceStatus.DEGRADED
|
| 155 |
+
self.healthy_replicas = 1
|
| 156 |
+
self._error_rate = 30.0
|
| 157 |
+
self._add_log(LogLevel.ERROR, "Failed to connect to peer nodes")
|
| 158 |
+
self._add_log(LogLevel.WARN, "Cluster quorum lost, running in degraded mode")
|
| 159 |
+
|
| 160 |
+
elif mode == "disk_full":
|
| 161 |
+
# Disk full
|
| 162 |
+
self._status = ServiceStatus.UNHEALTHY
|
| 163 |
+
self._error_rate = 80.0
|
| 164 |
+
self._add_log(LogLevel.ERROR, "No space left on device")
|
| 165 |
+
self._add_log(LogLevel.ERROR, "Failed to write to /data/logs/application.log")
|
| 166 |
+
|
| 167 |
+
elif mode == "cascading":
|
| 168 |
+
# Cascading failure from dependency
|
| 169 |
+
self._status = ServiceStatus.UNHEALTHY
|
| 170 |
+
self.healthy_replicas = 0
|
| 171 |
+
self._error_rate = 100.0
|
| 172 |
+
self._add_log(LogLevel.ERROR, "Upstream service unavailable")
|
| 173 |
+
self._add_log(LogLevel.ERROR, "Circuit breaker tripped for all dependencies")
|
| 174 |
+
|
| 175 |
+
def _add_log(self, level: LogLevel, message: str, trace_id: str | None = None):
|
| 176 |
+
"""Add a log entry."""
|
| 177 |
+
self._log_id += 1
|
| 178 |
+
self._logs.append(
|
| 179 |
+
LogEntry(
|
| 180 |
+
timestamp=datetime.now(),
|
| 181 |
+
level=level,
|
| 182 |
+
service=self.name,
|
| 183 |
+
message=message,
|
| 184 |
+
trace_id=trace_id or f"trace-{uuid.uuid4().hex[:8]}",
|
| 185 |
+
)
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
def get_status(self) -> ServiceStatus:
|
| 189 |
+
"""Get current service status."""
|
| 190 |
+
return self._status
|
| 191 |
+
|
| 192 |
+
def get_info(self) -> ServiceInfo:
|
| 193 |
+
"""Get service information."""
|
| 194 |
+
return ServiceInfo(
|
| 195 |
+
name=self.name,
|
| 196 |
+
status=self._status,
|
| 197 |
+
version=self.version,
|
| 198 |
+
replicas=self.replicas,
|
| 199 |
+
healthy_replicas=self.healthy_replicas,
|
| 200 |
+
last_deploy=self.last_deploy,
|
| 201 |
+
dependencies=self.dependencies,
|
| 202 |
+
config=self.config,
|
| 203 |
+
endpoints=self.endpoints,
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
def get_metrics(self) -> MetricData:
|
| 207 |
+
"""Get current metrics."""
|
| 208 |
+
# Add some noise to metrics
|
| 209 |
+
cpu = min(100, max(0, self._cpu_base + random.uniform(-5, 5)))
|
| 210 |
+
memory = min(100, max(0, self._memory_base + random.uniform(-2, 2)))
|
| 211 |
+
latency = max(1, self._latency_base + random.uniform(-10, 10))
|
| 212 |
+
|
| 213 |
+
return MetricData(
|
| 214 |
+
service=self.name,
|
| 215 |
+
timestamp=datetime.now(),
|
| 216 |
+
cpu_percent=cpu,
|
| 217 |
+
memory_percent=memory,
|
| 218 |
+
memory_mb=(memory / 100) * self._memory_limit,
|
| 219 |
+
memory_limit_mb=self._memory_limit,
|
| 220 |
+
request_rate=self._request_rate + random.uniform(-20, 20),
|
| 221 |
+
error_rate=self._error_rate,
|
| 222 |
+
latency_p50_ms=latency,
|
| 223 |
+
latency_p99_ms=latency * 3,
|
| 224 |
+
active_connections=random.randint(10, 100),
|
| 225 |
+
healthy_replicas=self.healthy_replicas,
|
| 226 |
+
total_replicas=self.replicas,
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
def get_logs(self, count: int = 20, level_filter: LogLevel | None = None) -> list[LogEntry]:
|
| 230 |
+
"""Get recent logs."""
|
| 231 |
+
logs = self._logs
|
| 232 |
+
if level_filter:
|
| 233 |
+
logs = [log for log in logs if log.level == level_filter]
|
| 234 |
+
return logs[-count:]
|
| 235 |
+
|
| 236 |
+
def restart(self) -> bool:
|
| 237 |
+
"""Restart the service."""
|
| 238 |
+
self._add_log(LogLevel.INFO, "Service restart initiated")
|
| 239 |
+
|
| 240 |
+
# Restart clears some failures
|
| 241 |
+
if self._failure_mode in ["oom", "bad_deploy"]:
|
| 242 |
+
# These persist through restart
|
| 243 |
+
self._add_log(LogLevel.ERROR, "Service failed to start after restart")
|
| 244 |
+
return False
|
| 245 |
+
|
| 246 |
+
if self._failure_mode == "memory_leak":
|
| 247 |
+
# Restart temporarily fixes memory leak
|
| 248 |
+
self._memory_base = random.uniform(20, 40)
|
| 249 |
+
self._status = ServiceStatus.HEALTHY
|
| 250 |
+
self.healthy_replicas = self.replicas
|
| 251 |
+
self._error_rate = 0.0
|
| 252 |
+
self._add_log(LogLevel.INFO, "Service restarted successfully")
|
| 253 |
+
return True
|
| 254 |
+
|
| 255 |
+
if self._failure_mode is None:
|
| 256 |
+
self._add_log(LogLevel.INFO, "Service restarted successfully")
|
| 257 |
+
return True
|
| 258 |
+
|
| 259 |
+
return False
|
| 260 |
+
|
| 261 |
+
def scale(self, replicas: int) -> bool:
|
| 262 |
+
"""Scale the service."""
|
| 263 |
+
if replicas < 0 or replicas > 10:
|
| 264 |
+
self._add_log(LogLevel.ERROR, f"Invalid replica count: {replicas}")
|
| 265 |
+
return False
|
| 266 |
+
|
| 267 |
+
old_replicas = self.replicas
|
| 268 |
+
self.replicas = replicas
|
| 269 |
+
self._add_log(LogLevel.INFO, f"Scaling from {old_replicas} to {replicas} replicas")
|
| 270 |
+
|
| 271 |
+
# If failure mode affects replicas, recalculate healthy ones
|
| 272 |
+
if self._failure_mode:
|
| 273 |
+
self.healthy_replicas = min(replicas, self.healthy_replicas)
|
| 274 |
+
else:
|
| 275 |
+
self.healthy_replicas = replicas
|
| 276 |
+
|
| 277 |
+
return True
|
| 278 |
+
|
| 279 |
+
def rollback(self, target_version: str = "previous") -> bool:
|
| 280 |
+
"""Rollback the service."""
|
| 281 |
+
self._add_log(LogLevel.INFO, f"Rolling back to {target_version}")
|
| 282 |
+
|
| 283 |
+
if self._failure_mode == "bad_deploy":
|
| 284 |
+
# Rollback fixes bad deploy
|
| 285 |
+
self.clear_failure()
|
| 286 |
+
self.version = "0.9.0" # Previous version
|
| 287 |
+
self._add_log(LogLevel.INFO, "Rollback successful, service is healthy")
|
| 288 |
+
return True
|
| 289 |
+
|
| 290 |
+
self._add_log(LogLevel.INFO, "Rollback completed")
|
| 291 |
+
return True
|
| 292 |
+
|
| 293 |
+
def update_config(self, key: str, value: Any) -> bool:
|
| 294 |
+
"""Update service configuration."""
|
| 295 |
+
self._add_log(LogLevel.INFO, f"Updating config: {key}={value}")
|
| 296 |
+
self.config[key] = value
|
| 297 |
+
|
| 298 |
+
if self._failure_mode == "config_error":
|
| 299 |
+
if key == self._failure_params.get("config_key"):
|
| 300 |
+
# Correct config fix doesn't auto-resolve; needs restart
|
| 301 |
+
self._add_log(LogLevel.INFO, "Configuration updated. Restart required.")
|
| 302 |
+
return True
|
| 303 |
+
|
| 304 |
+
if self._failure_mode == "oom" and key == "JAVA_OPTS" and "-Xmx" in str(value):
|
| 305 |
+
# Fixing memory limit
|
| 306 |
+
self._add_log(LogLevel.INFO, "Memory configuration updated. Restart required.")
|
| 307 |
+
self._failure_params["memory_fixed"] = True
|
| 308 |
+
return True
|
| 309 |
+
|
| 310 |
+
if self._failure_mode == "database_connection_pool" and key == "MAX_POOL_SIZE":
|
| 311 |
+
# Increasing connection pool
|
| 312 |
+
self._add_log(LogLevel.INFO, "Connection pool size updated. Restart required.")
|
| 313 |
+
return True
|
| 314 |
+
|
| 315 |
+
return True
|
| 316 |
+
|
| 317 |
+
def run_diagnostic(self) -> DiagnosticResult:
|
| 318 |
+
"""Run diagnostics on the service."""
|
| 319 |
+
checks = {
|
| 320 |
+
"health_endpoint": self._status != ServiceStatus.DOWN,
|
| 321 |
+
"memory_ok": self._memory_base < 90,
|
| 322 |
+
"cpu_ok": self._cpu_base < 90,
|
| 323 |
+
"dependencies_ok": self._failure_mode != "dependency_timeout",
|
| 324 |
+
"disk_ok": self._failure_mode != "disk_full",
|
| 325 |
+
"config_ok": self._failure_mode != "config_error",
|
| 326 |
+
}
|
| 327 |
+
|
| 328 |
+
details = {}
|
| 329 |
+
recommendations = []
|
| 330 |
+
|
| 331 |
+
if not checks["memory_ok"]:
|
| 332 |
+
details["memory"] = f"High memory usage: {self._memory_base:.1f}%"
|
| 333 |
+
recommendations.append("Consider increasing memory limit or fixing memory leak")
|
| 334 |
+
|
| 335 |
+
if not checks["cpu_ok"]:
|
| 336 |
+
details["cpu"] = f"High CPU usage: {self._cpu_base:.1f}%"
|
| 337 |
+
recommendations.append("Check for CPU-intensive operations or scale horizontally")
|
| 338 |
+
|
| 339 |
+
if not checks["dependencies_ok"]:
|
| 340 |
+
dep = self._failure_params.get("dependency", "unknown")
|
| 341 |
+
details["dependencies"] = f"Dependency {dep} is unhealthy"
|
| 342 |
+
recommendations.append(f"Check status of {dep} service")
|
| 343 |
+
|
| 344 |
+
if not checks["disk_ok"]:
|
| 345 |
+
details["disk"] = "Disk space critically low"
|
| 346 |
+
recommendations.append("Clear old logs or increase disk size")
|
| 347 |
+
|
| 348 |
+
if not checks["config_ok"]:
|
| 349 |
+
key = self._failure_params.get("config_key", "unknown")
|
| 350 |
+
details["config"] = f"Invalid configuration: {key}"
|
| 351 |
+
recommendations.append(f"Fix configuration value for {key}")
|
| 352 |
+
|
| 353 |
+
if self._failure_mode == "oom":
|
| 354 |
+
details["memory"] = "OutOfMemoryError detected in logs"
|
| 355 |
+
recommendations.append("Increase heap size via JAVA_OPTS or fix memory leak")
|
| 356 |
+
|
| 357 |
+
if self._failure_mode == "bad_deploy":
|
| 358 |
+
details["deployment"] = "Application failing to start"
|
| 359 |
+
recommendations.append("Consider rolling back to previous version")
|
| 360 |
+
|
| 361 |
+
return DiagnosticResult(
|
| 362 |
+
service=self.name,
|
| 363 |
+
timestamp=datetime.now(),
|
| 364 |
+
checks=checks,
|
| 365 |
+
details=details,
|
| 366 |
+
recommendations=recommendations,
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
def get_state(self) -> dict[str, Any]:
|
| 370 |
+
"""Get serializable state."""
|
| 371 |
+
return {
|
| 372 |
+
"name": self.name,
|
| 373 |
+
"version": self.version,
|
| 374 |
+
"replicas": self.replicas,
|
| 375 |
+
"healthy_replicas": self.healthy_replicas,
|
| 376 |
+
"status": self._status.value,
|
| 377 |
+
"failure_mode": self._failure_mode,
|
| 378 |
+
"failure_params": self._failure_params,
|
| 379 |
+
"cpu_base": self._cpu_base,
|
| 380 |
+
"memory_base": self._memory_base,
|
| 381 |
+
"error_rate": self._error_rate,
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
def load_state(self, state: dict[str, Any]):
|
| 385 |
+
"""Load state from dict."""
|
| 386 |
+
self.version = state["version"]
|
| 387 |
+
self.replicas = state["replicas"]
|
| 388 |
+
self.healthy_replicas = state["healthy_replicas"]
|
| 389 |
+
self._status = ServiceStatus(state["status"])
|
| 390 |
+
self._failure_mode = state.get("failure_mode")
|
| 391 |
+
self._failure_params = state.get("failure_params", {})
|
| 392 |
+
self._cpu_base = state.get("cpu_base", 20.0)
|
| 393 |
+
self._memory_base = state.get("memory_base", 30.0)
|
| 394 |
+
self._error_rate = state.get("error_rate", 0.0)
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
class InfrastructureSimulator:
|
| 398 |
+
"""
|
| 399 |
+
Simulates a complete microservices infrastructure.
|
| 400 |
+
|
| 401 |
+
Manages multiple services with dependencies, generates realistic
|
| 402 |
+
telemetry data, and handles failure scenarios.
|
| 403 |
+
"""
|
| 404 |
+
|
| 405 |
+
def __init__(self):
|
| 406 |
+
self.services: dict[str, ServiceSimulator] = {}
|
| 407 |
+
self.alerts: list[Alert] = []
|
| 408 |
+
self._alert_id = 0
|
| 409 |
+
self._global_time = datetime.now()
|
| 410 |
+
|
| 411 |
+
def add_service(
|
| 412 |
+
self,
|
| 413 |
+
name: str,
|
| 414 |
+
version: str = "1.0.0",
|
| 415 |
+
replicas: int = 3,
|
| 416 |
+
dependencies: list[str] | None = None,
|
| 417 |
+
config: dict[str, Any] | None = None,
|
| 418 |
+
) -> ServiceSimulator:
|
| 419 |
+
"""Add a service to the infrastructure."""
|
| 420 |
+
service = ServiceSimulator(name, version, replicas, dependencies, config)
|
| 421 |
+
self.services[name] = service
|
| 422 |
+
return service
|
| 423 |
+
|
| 424 |
+
def create_standard_infrastructure(self):
|
| 425 |
+
"""Create a standard microservices setup."""
|
| 426 |
+
# API Gateway
|
| 427 |
+
self.add_service(
|
| 428 |
+
"api-gateway",
|
| 429 |
+
version="2.1.0",
|
| 430 |
+
replicas=3,
|
| 431 |
+
dependencies=["user-service", "order-service", "product-service"],
|
| 432 |
+
config={"RATE_LIMIT": 1000, "TIMEOUT_MS": 5000},
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
# User Service
|
| 436 |
+
self.add_service(
|
| 437 |
+
"user-service",
|
| 438 |
+
version="1.5.2",
|
| 439 |
+
replicas=3,
|
| 440 |
+
dependencies=["postgres-db", "redis-cache"],
|
| 441 |
+
config={"MAX_POOL_SIZE": 50, "CACHE_TTL": 300},
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
# Order Service
|
| 445 |
+
self.add_service(
|
| 446 |
+
"order-service",
|
| 447 |
+
version="3.0.1",
|
| 448 |
+
replicas=4,
|
| 449 |
+
dependencies=["postgres-db", "user-service", "payment-service", "kafka"],
|
| 450 |
+
config={"JAVA_OPTS": "-Xmx512m -Xms256m", "MAX_POOL_SIZE": 50},
|
| 451 |
+
)
|
| 452 |
+
|
| 453 |
+
# Product Service
|
| 454 |
+
self.add_service(
|
| 455 |
+
"product-service",
|
| 456 |
+
version="1.2.0",
|
| 457 |
+
replicas=2,
|
| 458 |
+
dependencies=["postgres-db", "elasticsearch"],
|
| 459 |
+
config={"CACHE_ENABLED": True},
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
# Payment Service
|
| 463 |
+
self.add_service(
|
| 464 |
+
"payment-service",
|
| 465 |
+
version="2.0.0",
|
| 466 |
+
replicas=3,
|
| 467 |
+
dependencies=["payment-gateway-external"],
|
| 468 |
+
config={"RETRY_COUNT": 3, "TIMEOUT_MS": 30000},
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
# Database
|
| 472 |
+
self.add_service(
|
| 473 |
+
"postgres-db",
|
| 474 |
+
version="14.2",
|
| 475 |
+
replicas=1,
|
| 476 |
+
config={"MAX_CONNECTIONS": 200, "SHARED_BUFFERS": "256MB"},
|
| 477 |
+
)
|
| 478 |
+
|
| 479 |
+
# Cache
|
| 480 |
+
self.add_service(
|
| 481 |
+
"redis-cache",
|
| 482 |
+
version="6.2",
|
| 483 |
+
replicas=3,
|
| 484 |
+
config={"MAXMEMORY": "512mb", "EVICTION_POLICY": "allkeys-lru"},
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
# Message Queue
|
| 488 |
+
self.add_service(
|
| 489 |
+
"kafka",
|
| 490 |
+
version="3.0",
|
| 491 |
+
replicas=3,
|
| 492 |
+
config={"REPLICATION_FACTOR": 3, "NUM_PARTITIONS": 10},
|
| 493 |
+
)
|
| 494 |
+
|
| 495 |
+
# Search
|
| 496 |
+
self.add_service(
|
| 497 |
+
"elasticsearch",
|
| 498 |
+
version="8.0",
|
| 499 |
+
replicas=3,
|
| 500 |
+
config={"HEAP_SIZE": "1g"},
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
def inject_failure(self, service_name: str, mode: str, params: dict[str, Any] | None = None):
|
| 504 |
+
"""Inject a failure into a service."""
|
| 505 |
+
if service_name not in self.services:
|
| 506 |
+
raise ValueError(f"Service {service_name} not found")
|
| 507 |
+
|
| 508 |
+
service = self.services[service_name]
|
| 509 |
+
service.inject_failure(mode, params)
|
| 510 |
+
|
| 511 |
+
# Generate appropriate alerts
|
| 512 |
+
self._generate_alerts_for_failure(service_name, mode, params)
|
| 513 |
+
|
| 514 |
+
def _generate_alerts_for_failure(self, service_name: str, mode: str, params: dict[str, Any] | None = None):
|
| 515 |
+
"""Generate alerts based on failure mode."""
|
| 516 |
+
params = params or {}
|
| 517 |
+
|
| 518 |
+
if mode == "oom":
|
| 519 |
+
self._add_alert(
|
| 520 |
+
AlertSeverity.CRITICAL,
|
| 521 |
+
service_name,
|
| 522 |
+
f"{service_name} OOMKilled",
|
| 523 |
+
f"Container {service_name} was killed due to out of memory. Exit code 137.",
|
| 524 |
+
)
|
| 525 |
+
|
| 526 |
+
elif mode == "memory_leak":
|
| 527 |
+
self._add_alert(
|
| 528 |
+
AlertSeverity.WARNING,
|
| 529 |
+
service_name,
|
| 530 |
+
f"{service_name} High Memory Usage",
|
| 531 |
+
f"Memory usage is at {params.get('memory_percent', 85)}% of limit.",
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
elif mode == "cpu_spike":
|
| 535 |
+
self._add_alert(
|
| 536 |
+
AlertSeverity.WARNING,
|
| 537 |
+
service_name,
|
| 538 |
+
f"{service_name} High CPU",
|
| 539 |
+
f"CPU usage is at {params.get('cpu_percent', 95)}%.",
|
| 540 |
+
)
|
| 541 |
+
|
| 542 |
+
elif mode == "dependency_timeout":
|
| 543 |
+
dep = params.get("dependency", "unknown")
|
| 544 |
+
self._add_alert(
|
| 545 |
+
AlertSeverity.CRITICAL,
|
| 546 |
+
service_name,
|
| 547 |
+
f"{service_name} Dependency Timeout",
|
| 548 |
+
f"Service {service_name} cannot reach {dep}. Connections timing out.",
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
elif mode == "database_connection_pool":
|
| 552 |
+
self._add_alert(
|
| 553 |
+
AlertSeverity.CRITICAL,
|
| 554 |
+
service_name,
|
| 555 |
+
f"{service_name} Connection Pool Exhausted",
|
| 556 |
+
f"Database connection pool is exhausted. Active: {params.get('active', 50)}/{params.get('max', 50)}",
|
| 557 |
+
)
|
| 558 |
+
|
| 559 |
+
elif mode == "bad_deploy":
|
| 560 |
+
self._add_alert(
|
| 561 |
+
AlertSeverity.CRITICAL,
|
| 562 |
+
service_name,
|
| 563 |
+
f"{service_name} CrashLoopBackOff",
|
| 564 |
+
f"Pod {service_name} is in CrashLoopBackOff. Application failing to start.",
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
elif mode == "cascading":
|
| 568 |
+
self._add_alert(
|
| 569 |
+
AlertSeverity.CRITICAL,
|
| 570 |
+
service_name,
|
| 571 |
+
f"{service_name} Service Down",
|
| 572 |
+
f"Service {service_name} is completely unavailable due to cascading failure.",
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
def _add_alert(self, severity: AlertSeverity, service: str, title: str, description: str):
|
| 576 |
+
"""Add a new alert."""
|
| 577 |
+
self._alert_id += 1
|
| 578 |
+
self.alerts.append(
|
| 579 |
+
Alert(
|
| 580 |
+
id=f"alert-{self._alert_id}",
|
| 581 |
+
timestamp=datetime.now(),
|
| 582 |
+
severity=severity,
|
| 583 |
+
service=service,
|
| 584 |
+
title=title,
|
| 585 |
+
description=description,
|
| 586 |
+
firing=True,
|
| 587 |
+
labels={"env": "production", "team": "platform"},
|
| 588 |
+
)
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
def get_alerts(self, service_name: str | None = None) -> list[Alert]:
|
| 592 |
+
"""Get active alerts, optionally filtered by service."""
|
| 593 |
+
alerts = [a for a in self.alerts if a.firing]
|
| 594 |
+
if service_name:
|
| 595 |
+
alerts = [a for a in alerts if a.service == service_name]
|
| 596 |
+
return alerts
|
| 597 |
+
|
| 598 |
+
def resolve_alert(self, alert_id: str):
|
| 599 |
+
"""Mark an alert as resolved."""
|
| 600 |
+
for alert in self.alerts:
|
| 601 |
+
if alert.id == alert_id:
|
| 602 |
+
alert.firing = False
|
| 603 |
+
|
| 604 |
+
def get_service_names(self) -> list[str]:
|
| 605 |
+
"""Get list of all service names."""
|
| 606 |
+
return list(self.services.keys())
|
| 607 |
+
|
| 608 |
+
def get_state(self) -> dict[str, dict[str, Any]]:
|
| 609 |
+
"""Get full state for serialization."""
|
| 610 |
+
return {name: svc.get_state() for name, svc in self.services.items()}
|
| 611 |
+
|
| 612 |
+
def load_state(self, state: dict[str, dict[str, Any]]):
|
| 613 |
+
"""Load state from dict."""
|
| 614 |
+
for name, svc_state in state.items():
|
| 615 |
+
if name in self.services:
|
| 616 |
+
self.services[name].load_state(svc_state)
|
| 617 |
+
|
| 618 |
+
def reset(self):
|
| 619 |
+
"""Reset all services to healthy state."""
|
| 620 |
+
for service in self.services.values():
|
| 621 |
+
service.clear_failure()
|
| 622 |
+
service._logs.clear()
|
| 623 |
+
self.alerts.clear()
|
| 624 |
+
self._alert_id = 0
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
# ============================================================================
|
| 628 |
+
# Scenario Presets
|
| 629 |
+
# ============================================================================
|
| 630 |
+
|
| 631 |
+
def create_oom_scenario(infra: InfrastructureSimulator) -> dict[str, Any]:
|
| 632 |
+
"""
|
| 633 |
+
Scenario: Order service running out of memory during peak traffic.
|
| 634 |
+
|
| 635 |
+
Root cause: Heap size too small for traffic volume.
|
| 636 |
+
Solution: Increase JAVA_OPTS heap size and restart.
|
| 637 |
+
"""
|
| 638 |
+
infra.create_standard_infrastructure()
|
| 639 |
+
infra.inject_failure("order-service", "oom")
|
| 640 |
+
|
| 641 |
+
return {
|
| 642 |
+
"root_cause": "order-service OOM due to insufficient heap size",
|
| 643 |
+
"required_remediation": [
|
| 644 |
+
"update_config:order-service:JAVA_OPTS:-Xmx1024m -Xms512m",
|
| 645 |
+
"restart_service:order-service",
|
| 646 |
+
],
|
| 647 |
+
"affected_services": ["order-service", "api-gateway"],
|
| 648 |
+
}
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
def create_cascading_failure_scenario(infra: InfrastructureSimulator) -> dict[str, Any]:
|
| 652 |
+
"""
|
| 653 |
+
Scenario: Database connection pool exhausted, causing cascading failures.
|
| 654 |
+
|
| 655 |
+
Root cause: postgres-db max connections too low for current load.
|
| 656 |
+
Solution: Increase database connections and connection pool sizes.
|
| 657 |
+
"""
|
| 658 |
+
infra.create_standard_infrastructure()
|
| 659 |
+
|
| 660 |
+
# Database is overloaded
|
| 661 |
+
infra.inject_failure("postgres-db", "cpu_spike", {"cpu_percent": 98})
|
| 662 |
+
|
| 663 |
+
# Services can't get connections
|
| 664 |
+
infra.inject_failure("user-service", "database_connection_pool", {"active": 50, "max": 50})
|
| 665 |
+
infra.inject_failure("order-service", "database_connection_pool", {"active": 50, "max": 50})
|
| 666 |
+
|
| 667 |
+
# API gateway sees failures
|
| 668 |
+
infra.services["api-gateway"]._status = ServiceStatus.DEGRADED
|
| 669 |
+
infra.services["api-gateway"]._error_rate = 40.0
|
| 670 |
+
|
| 671 |
+
infra._add_alert(
|
| 672 |
+
AlertSeverity.CRITICAL,
|
| 673 |
+
"api-gateway",
|
| 674 |
+
"High Error Rate",
|
| 675 |
+
"API Gateway error rate at 40%. Multiple downstream services affected.",
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
return {
|
| 679 |
+
"root_cause": "postgres-db overloaded, connection pools exhausted across services",
|
| 680 |
+
"required_remediation": [
|
| 681 |
+
"update_config:postgres-db:MAX_CONNECTIONS:500",
|
| 682 |
+
"restart_service:postgres-db",
|
| 683 |
+
"update_config:user-service:MAX_POOL_SIZE:100",
|
| 684 |
+
"restart_service:user-service",
|
| 685 |
+
"update_config:order-service:MAX_POOL_SIZE:100",
|
| 686 |
+
"restart_service:order-service",
|
| 687 |
+
],
|
| 688 |
+
"affected_services": ["postgres-db", "user-service", "order-service", "api-gateway"],
|
| 689 |
+
}
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
def create_bad_deploy_scenario(infra: InfrastructureSimulator) -> dict[str, Any]:
|
| 693 |
+
"""
|
| 694 |
+
Scenario: Bad deployment of payment service causing checkout failures.
|
| 695 |
+
|
| 696 |
+
Root cause: New version has a bug causing startup crash.
|
| 697 |
+
Solution: Rollback to previous version.
|
| 698 |
+
"""
|
| 699 |
+
infra.create_standard_infrastructure()
|
| 700 |
+
|
| 701 |
+
# Payment service has bad deploy
|
| 702 |
+
infra.services["payment-service"].version = "2.1.0" # New bad version
|
| 703 |
+
infra.inject_failure("payment-service", "bad_deploy")
|
| 704 |
+
|
| 705 |
+
# Order service affected (can't process payments)
|
| 706 |
+
infra.inject_failure("order-service", "dependency_timeout", {"dependency": "payment-service"})
|
| 707 |
+
|
| 708 |
+
return {
|
| 709 |
+
"root_cause": "payment-service v2.1.0 deployment has startup bug",
|
| 710 |
+
"required_remediation": [
|
| 711 |
+
"rollback_service:payment-service",
|
| 712 |
+
],
|
| 713 |
+
"affected_services": ["payment-service", "order-service"],
|
| 714 |
+
}
|
| 715 |
+
|
| 716 |
+
|
| 717 |
+
def create_memory_leak_scenario(infra: InfrastructureSimulator) -> dict[str, Any]:
|
| 718 |
+
"""
|
| 719 |
+
Scenario: Slow memory leak in user-service causing gradual degradation.
|
| 720 |
+
|
| 721 |
+
Root cause: Memory leak in user session handling.
|
| 722 |
+
Solution: Restart service (temporary) and scale up to handle load.
|
| 723 |
+
"""
|
| 724 |
+
infra.create_standard_infrastructure()
|
| 725 |
+
infra.inject_failure("user-service", "memory_leak", {"memory_percent": 88})
|
| 726 |
+
|
| 727 |
+
return {
|
| 728 |
+
"root_cause": "user-service memory leak in session handling",
|
| 729 |
+
"required_remediation": [
|
| 730 |
+
"restart_service:user-service",
|
| 731 |
+
"scale_service:user-service:5",
|
| 732 |
+
],
|
| 733 |
+
"affected_services": ["user-service", "api-gateway"],
|
| 734 |
+
}
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
def create_complex_incident_scenario(infra: InfrastructureSimulator) -> dict[str, Any]:
|
| 738 |
+
"""
|
| 739 |
+
Scenario: Complex multi-factor incident with multiple root causes.
|
| 740 |
+
|
| 741 |
+
This is the hard scenario combining multiple issues:
|
| 742 |
+
1. Redis cache is down (network issue)
|
| 743 |
+
2. This causes user-service to hit DB directly
|
| 744 |
+
3. DB gets overloaded
|
| 745 |
+
4. Order service starts timing out
|
| 746 |
+
5. Plus there's a memory leak in product-service (unrelated)
|
| 747 |
+
|
| 748 |
+
Solution requires identifying and fixing multiple issues.
|
| 749 |
+
"""
|
| 750 |
+
infra.create_standard_infrastructure()
|
| 751 |
+
|
| 752 |
+
# Redis is down
|
| 753 |
+
infra.inject_failure("redis-cache", "network_partition")
|
| 754 |
+
infra._add_alert(
|
| 755 |
+
AlertSeverity.CRITICAL,
|
| 756 |
+
"redis-cache",
|
| 757 |
+
"Redis Cluster Unavailable",
|
| 758 |
+
"Redis cluster has lost quorum. Cache reads failing.",
|
| 759 |
+
)
|
| 760 |
+
|
| 761 |
+
# User service hitting DB hard without cache
|
| 762 |
+
infra.inject_failure("user-service", "dependency_timeout", {"dependency": "redis-cache"})
|
| 763 |
+
infra.services["user-service"]._latency_base = 200.0
|
| 764 |
+
infra.services["user-service"]._error_rate = 10.0
|
| 765 |
+
|
| 766 |
+
# DB is overloaded from cache misses
|
| 767 |
+
infra.inject_failure("postgres-db", "cpu_spike", {"cpu_percent": 92})
|
| 768 |
+
|
| 769 |
+
# Order service slow due to user-service issues
|
| 770 |
+
infra.services["order-service"]._status = ServiceStatus.DEGRADED
|
| 771 |
+
infra.services["order-service"]._latency_base = 3000.0
|
| 772 |
+
infra.services["order-service"]._error_rate = 25.0
|
| 773 |
+
infra._add_alert(
|
| 774 |
+
AlertSeverity.WARNING,
|
| 775 |
+
"order-service",
|
| 776 |
+
"High Latency",
|
| 777 |
+
"Order service P99 latency exceeds 3s threshold.",
|
| 778 |
+
)
|
| 779 |
+
|
| 780 |
+
# Unrelated: product-service has memory leak
|
| 781 |
+
infra.inject_failure("product-service", "memory_leak", {"memory_percent": 82})
|
| 782 |
+
|
| 783 |
+
# API gateway showing errors
|
| 784 |
+
infra.services["api-gateway"]._status = ServiceStatus.DEGRADED
|
| 785 |
+
infra.services["api-gateway"]._error_rate = 30.0
|
| 786 |
+
infra._add_alert(
|
| 787 |
+
AlertSeverity.CRITICAL,
|
| 788 |
+
"api-gateway",
|
| 789 |
+
"Elevated Error Rate",
|
| 790 |
+
"Multiple backend services degraded. Error rate: 30%",
|
| 791 |
+
)
|
| 792 |
+
|
| 793 |
+
return {
|
| 794 |
+
"root_cause": "redis-cache network partition causing cascading DB overload, plus unrelated product-service memory leak",
|
| 795 |
+
"required_remediation": [
|
| 796 |
+
"restart_service:redis-cache",
|
| 797 |
+
"restart_service:product-service",
|
| 798 |
+
"scale_service:product-service:4",
|
| 799 |
+
],
|
| 800 |
+
"affected_services": ["redis-cache", "user-service", "postgres-db", "order-service", "product-service", "api-gateway"],
|
| 801 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Task definitions for the DevOps Incident Response Environment.
|
| 3 |
+
|
| 4 |
+
Each task represents a realistic incident scenario with defined:
|
| 5 |
+
- Difficulty level
|
| 6 |
+
- Initial state
|
| 7 |
+
- Success criteria
|
| 8 |
+
- Grading rubric
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
from typing import Any
|
| 14 |
+
|
| 15 |
+
from ..models import AlertSeverity, TaskDefinition
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# ============================================================================
|
| 19 |
+
# Task 1: Easy - OOM Incident
|
| 20 |
+
# ============================================================================
|
| 21 |
+
|
| 22 |
+
TASK_EASY = TaskDefinition(
|
| 23 |
+
id="task_easy_oom",
|
| 24 |
+
name="Memory Crisis: OOM Kill Resolution",
|
| 25 |
+
difficulty="easy",
|
| 26 |
+
description="""
|
| 27 |
+
The order-service has been OOM killed during a traffic spike.
|
| 28 |
+
Customers are unable to place orders, causing revenue loss.
|
| 29 |
+
|
| 30 |
+
Your objective:
|
| 31 |
+
1. Identify the root cause of the OOM
|
| 32 |
+
2. Fix the configuration to prevent recurrence
|
| 33 |
+
3. Restore service health
|
| 34 |
+
|
| 35 |
+
Hints:
|
| 36 |
+
- Check the order-service logs and metrics
|
| 37 |
+
- Look at the JAVA_OPTS configuration
|
| 38 |
+
- Services need configuration changes AND restarts to take effect
|
| 39 |
+
""".strip(),
|
| 40 |
+
max_steps=15,
|
| 41 |
+
time_limit_seconds=300,
|
| 42 |
+
incident_title="CRITICAL: Order Service Down - Customers Cannot Checkout",
|
| 43 |
+
incident_description="The order-service has been repeatedly OOM killed. All checkout operations are failing. Revenue impact estimated at $50k/hour.",
|
| 44 |
+
incident_severity=AlertSeverity.CRITICAL,
|
| 45 |
+
affected_services=["order-service", "api-gateway"],
|
| 46 |
+
customer_impact="100% of checkout operations failing. Estimated revenue loss: $50k/hour",
|
| 47 |
+
root_cause="order-service OOM due to insufficient heap size",
|
| 48 |
+
required_remediation=["update_config:order-service:JAVA_OPTS", "restart_service:order-service"],
|
| 49 |
+
diagnosis_weight=0.3,
|
| 50 |
+
remediation_weight=0.6,
|
| 51 |
+
efficiency_weight=0.1,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# ============================================================================
|
| 56 |
+
# Task 2: Medium - Cascading Database Failure
|
| 57 |
+
# ============================================================================
|
| 58 |
+
|
| 59 |
+
TASK_MEDIUM = TaskDefinition(
|
| 60 |
+
id="task_medium_cascade",
|
| 61 |
+
name="Database Overload: Cascading Connection Failure",
|
| 62 |
+
difficulty="medium",
|
| 63 |
+
description="""
|
| 64 |
+
Multiple services are experiencing database connection timeouts.
|
| 65 |
+
The API gateway is showing elevated error rates.
|
| 66 |
+
|
| 67 |
+
Your objective:
|
| 68 |
+
1. Identify the root cause of the cascading failures
|
| 69 |
+
2. Determine why the database is overloaded
|
| 70 |
+
3. Fix connection pool configurations
|
| 71 |
+
4. Restore all affected services to healthy state
|
| 72 |
+
|
| 73 |
+
This incident has multiple affected services - you need to fix them
|
| 74 |
+
in the right order for the system to recover.
|
| 75 |
+
""".strip(),
|
| 76 |
+
max_steps=25,
|
| 77 |
+
time_limit_seconds=600,
|
| 78 |
+
incident_title="CRITICAL: Multiple Services Failing - Database Connection Issues",
|
| 79 |
+
incident_description="Alert storm: user-service, order-service, and api-gateway all reporting errors. Database appears overloaded. Customer complaints about slow responses and failures.",
|
| 80 |
+
incident_severity=AlertSeverity.CRITICAL,
|
| 81 |
+
affected_services=["postgres-db", "user-service", "order-service", "api-gateway"],
|
| 82 |
+
customer_impact="60% of requests failing or timing out. Customer complaints escalating.",
|
| 83 |
+
root_cause="postgres-db overloaded, connection pools exhausted across services",
|
| 84 |
+
required_remediation=[
|
| 85 |
+
"update_config:postgres-db:MAX_CONNECTIONS",
|
| 86 |
+
"restart_service:postgres-db",
|
| 87 |
+
"update_config:user-service:MAX_POOL_SIZE",
|
| 88 |
+
"restart_service:user-service",
|
| 89 |
+
"update_config:order-service:MAX_POOL_SIZE",
|
| 90 |
+
"restart_service:order-service",
|
| 91 |
+
],
|
| 92 |
+
diagnosis_weight=0.35,
|
| 93 |
+
remediation_weight=0.55,
|
| 94 |
+
efficiency_weight=0.1,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# ============================================================================
|
| 99 |
+
# Task 3: Hard - Complex Multi-Factor Incident
|
| 100 |
+
# ============================================================================
|
| 101 |
+
|
| 102 |
+
TASK_HARD = TaskDefinition(
|
| 103 |
+
id="task_hard_complex",
|
| 104 |
+
name="Perfect Storm: Multi-Factor Cascading Incident",
|
| 105 |
+
difficulty="hard",
|
| 106 |
+
description="""
|
| 107 |
+
Multiple alerts firing. The system appears to be in a degraded state
|
| 108 |
+
with several services affected. Initial investigation suggests
|
| 109 |
+
this might not be a single root cause situation.
|
| 110 |
+
|
| 111 |
+
Your objective:
|
| 112 |
+
1. Triage the alerts and identify ALL contributing factors
|
| 113 |
+
2. Determine which issues are related vs coincidental
|
| 114 |
+
3. Prioritize and fix issues in the optimal order
|
| 115 |
+
4. Restore full system health
|
| 116 |
+
|
| 117 |
+
Warning: This incident has multiple root causes. A simple restart
|
| 118 |
+
won't fix everything. You need to understand the full picture.
|
| 119 |
+
""".strip(),
|
| 120 |
+
max_steps=40,
|
| 121 |
+
time_limit_seconds=900,
|
| 122 |
+
incident_title="CRITICAL: System-Wide Degradation - Multiple Root Causes Suspected",
|
| 123 |
+
incident_description="Alert storm across infrastructure. Redis cluster issues, database slow, API gateway errors at 30%, multiple services degraded. Incident commander has been paged.",
|
| 124 |
+
incident_severity=AlertSeverity.CRITICAL,
|
| 125 |
+
affected_services=["redis-cache", "user-service", "postgres-db", "order-service", "product-service", "api-gateway"],
|
| 126 |
+
customer_impact="30% of requests failing. Search degraded. Checkout slow. Customer satisfaction scores dropping.",
|
| 127 |
+
root_cause="redis-cache network partition causing cascading DB overload, plus unrelated product-service memory leak",
|
| 128 |
+
required_remediation=[
|
| 129 |
+
"restart_service:redis-cache",
|
| 130 |
+
"restart_service:product-service",
|
| 131 |
+
"scale_service:product-service",
|
| 132 |
+
],
|
| 133 |
+
diagnosis_weight=0.4,
|
| 134 |
+
remediation_weight=0.45,
|
| 135 |
+
efficiency_weight=0.15,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
# ============================================================================
|
| 140 |
+
# Task Registry
|
| 141 |
+
# ============================================================================
|
| 142 |
+
|
| 143 |
+
TASKS: dict[str, TaskDefinition] = {
|
| 144 |
+
"task_easy_oom": TASK_EASY,
|
| 145 |
+
"task_medium_cascade": TASK_MEDIUM,
|
| 146 |
+
"task_hard_complex": TASK_HARD,
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def get_task(task_id: str) -> TaskDefinition:
|
| 151 |
+
"""Get a task definition by ID."""
|
| 152 |
+
if task_id not in TASKS:
|
| 153 |
+
raise ValueError(f"Unknown task: {task_id}. Available: {list(TASKS.keys())}")
|
| 154 |
+
return TASKS[task_id]
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def list_tasks() -> list[dict[str, Any]]:
|
| 158 |
+
"""List all available tasks."""
|
| 159 |
+
return [
|
| 160 |
+
{
|
| 161 |
+
"id": task.id,
|
| 162 |
+
"name": task.name,
|
| 163 |
+
"difficulty": task.difficulty,
|
| 164 |
+
"description": task.description[:200] + "...",
|
| 165 |
+
"max_steps": task.max_steps,
|
| 166 |
+
}
|
| 167 |
+
for task in TASKS.values()
|
| 168 |
+
]
|