KartikAneja5/sre-incident-response
GitHub: KartikAneja5/sre-incident-response
这是一个模拟真实生产环境故障模式的 SRE 智能体评估环境,用于测试和训练 LLM 在警报分类、根因诊断及故障修复全流程中的自动化运维能力。
Stars: 0 | Forks: 0
title: SRE 故障响应
emoji: 🚨
colorFrom: red
colorTo: yellow
sdk: docker
app_port: 7860
pinned: false
license: mit
tags:
- openenv
- sre
- incident-response
- devops
- real-world
- rl
- agent-evaluation
- llm-evaluation
# 🚨 SRE 故障响应
### OpenEnv 环境 — Meta × Hugging Face Hackathon 2026






**一个让智能体扮演值班 SRE 工程师的 AI 智能体环境。**
分类警报 → 诊断根本原因 → 按正确顺序应用修复 → 编写事后分析
[🌐 Live Space](https://huggingface.co/spaces/kartikaneja5/sre-incident-response) · [📖 API Docs](https://kartikaneja5-sre-incident-response.hf.space/docs) · [📊 Metrics](https://kartikaneja5-sre-incident-response.hf.space/metrics) · [⭐ GitHub](https://github.com/KartikAneja5/sre-incident-response)
## 🎯 为什么存在这个环境
每个 SRE 工程师都经历过这种噩梦:凌晨 3 点,五个警报同时触发,在公司的收入受损之前,你只有几分钟的时间找出哪一个是根本原因。你在极端的压力下,在脑海中关联着十几个服务的日志、指标和警报。
**这个环境正是模拟了这种场景。**
不同于玩具问题或合成基准,该环境中的每个场景都基于 Google、Meta、Netflix 和 Stripe 的工程师每周在生产环境中遇到的真实故障模式。级联故障链、误导性的虚假警报、修复顺序约束——这一切都是真实的。
## 🏗️ 架构
```
┌──────────────────────────────────────────────────────────────────┐
│ AI Agent (LLM / RL Policy) │
│ │
│ Input: logs + metrics + active_alerts + task_goal + hint │
│ Output: {"action_type": "diagnose", "value": "..."} │
└─────────────────────────┬────────────────────────────────────────┘
│ OpenEnv API
┌───────────────▼───────────────────┐
│ FastAPI Environment Server │
│ (port 7860, Docker) │
│ │
│ POST /reset → ObservationModel │
│ POST /step → StepResultModel │
│ GET /state → StateModel │
│ GET /tasks → List[TaskInfo] │
│ GET /health → HealthModel │
│ GET /metrics→ MetricsModel │
└───────────────┬───────────────────┘
│
┌───────────────▼───────────────────┐
│ Session-Isolated Episodes │
│ (OrderedDict, max 50 sessions) │
│ │
│ ┌──────────┐ ┌──────────┐ ┌────┐ │
│ │ Task 1 │ │ Task 2 │ │ T3 │ │
│ │ Easy │ │ Medium │ │Hard│ │
│ └──────────┘ └──────────┘ └────┘ │
│ │
│ Fuzzy Graders + Partial Rewards│
└───────────────────────────────────┘
```
## 🎮 三项任务 — 专为真实评估而设计
### 📗 任务 1:警报分类 `alert_triage` — 简单(最多 8 步)
**场景:** 五个警报在生产微服务堆栈中同时触发。数据库 CPU 达到 98%,触发了下游故障的级联。大多数警报是*症状*。只有一个是*原因*。
**为何不简单:** 智能体必须在 5 个服务中区分根本原因和噪声,正确分类严重性(P1/P2/P3),并清晰阐述级联模式——所有这些都在 8 步之内完成。
**场景变体:**
- `v0` — DB CPU 过载级联至 payment、auth、cache、gateway
- `v1` — Auth 服务内存耗尽级联至 mobile API
```
Services: db-primary → payment-service → auth-service → cache-redis → api-gateway
Cascade: CPU 98% → connection queue 847 → timeouts → latency spikes → 503s
```
**评分(8 个标准,总分 = 1.0):**
| 标准 | 权重 |
|-----------|--------|
| 确认 db-primary 为 P1 根本原因 | 0.15 |
| 将 db-primary 分类为 P1 | 0.15 |
| 将 payment-service 分类为 P1 | 0.10 |
| 将 auth-service 分类为 P2 | 0.10 |
| 将 cache-redis 分类为 P2 | 0.10 |
| 将 api-gateway 分类为 P3 | 0.10 |
| 诊断 DB CPU 过载为根本原因 | 0.15 |
| 识别级联故障模式 | 0.15 |
### 📙 任务 2:根本原因诊断 `root_cause_diagnosis` — 中等(最多 10 步)
**场景:** 支付服务完全宕机(HTTP 503)。事故始于 2 小时前。故障链并不明显:一次糟糕的部署引入了慢 SQL 查询 → 耗尽数据库连接池 → 503 错误。
**为何不简单:** 智能体必须在诊断之前使用 `run_query` 主动*调查*。跳过调查的被动智能体将失败。证据分散在部署日志、慢查询日志和连接池指标中。
**场景变体:**
- `v0` — 带有慢 SQL 查询的糟糕部署 v2.4.1 → 连接池耗尽
- `v1` — 磁盘空间耗尽 → PostgreSQL 进入只读模式
**可用的 `run_query` 响应:**
```
"slow queries" → 47.3s query from deploy v2.4.1
"recent deploy" → v2.4.1 deployed 2h 7m ago
"connection pool" → 490/500 connections in use (98%)
"payment logs" → FATAL: Could not acquire DB connection
"disk" → /var/lib/postgresql at 99.1%
"wal" → WAL archive lag 127 minutes
```
**评分(5 个标准,总分 = 1.0):**
| 标准 | 权重 |
|-----------|--------|
| 识别慢查询 / 磁盘问题 | 0.20 |
| 将问题与根本原因关联(部署 / 磁盘) | 0.20 |
| 识别连接池 / 只读模式 | 0.20 |
| 确认正确的根本原因警报 | 0.20 |
| 建议正确的修复 | 0.20 |
### 📕 任务 3:完整事故手册 `full_incident_runbook` — 困难(最多 20 步)
**场景:** 全公司登录中断。三个服务同时发生故障。级联链被设计为非显而易见。根本原因:Redis `maxmemory-policy` 设置为 `noeviction`。
**级联链:**
```
Redis OOM (noeviction policy)
↓ cache writes rejected
Auth service retry storm → CPU 94%
↓ DB fallback also fails
Mobile API receives 503s from auth
↓ circuit breaker opens
100% of logins failing — SEV1 declared
```
**三个虚假警报**会浪费智能体的步数:
- `WARNING: api-gateway connection pool at 75%` — 非原因
- `INFO: payment-service heap memory at 78%` — 非原因
- `WARNING: db-primary replication lag 2.3s` — 非原因
**需要严格的修复顺序:**
```
Step 1: Fix Redis (maxmemory-policy) ← must come first
Step 2: Restart auth-service ← must come second
Step 3: Reset mobile-api circuit breaker ← must come third
Wrong order = no ordering reward
```
**需要特定的技术知识:**
智能体必须知道 Redis 配置命令。通用的“修复 redis”无法获得奖励。必须使用:`maxmemory-policy`、`allkeys-lru`、`CONFIG SET maxmemory` 等。
**需要完整的事后分析(4 个部分):**
| 部分 | 必需关键词 | 权重 |
|---------|------------------|--------|
| 时间线 | "timeline", "chronology" | 0.05 |
| 根本原因分析 | "root cause", "rca" | 0.05 |
| 行动项 | "action items", "follow-up", "remediation" | 0.05 |
| 预防 | "prevention", "prevent", "mitigation" | 0.05 |
**评分(13 个标准,总分 = 1.0):**
| 标准 | 权重 |
|-----------|--------|
| 将 redis 分类为 P1 根本原因 | 0.08 |
| 将 auth-service 分类为 P1 次要原因 | 0.08 |
| 诊断 Redis OOM 为起源 | 0.12 |
| 诊断完整的级联链 | 0.12 |
| 应用特定的 Redis 配置修复 | 0.10 |
| 应用 auth-service 恢复 | 0.08 |
| 应用 mobile-api 熔断器重置 | 0.07 |
| 按正确顺序应用修复 | 0.10 |
| 事后分析:时间线 | 0.05 |
| 事后分析:根本原因 | 0.05 |
| 事后分析:行动项 | 0.05 |
| 事后分析:预防 | 0.05 |
| 从未指责错误的服务 | 0.05 |
**惩罚:** 如果智能体在诊断 Redis OOM 之前对 api-gateway 或 payment 应用修复,则 `-0.10`。
## 📊 基线分数
### 使用 Llama 3.3 70B(通过 Groq)— Zero-Shot
| 任务 | 已用步数 | 最终得分 | 成功 |
|------|-----------|-------------|---------|
| `alert_triage` | 4 / 8 | **0.99** | ✅ |
| `root_cause_diagnosis` | 5 / 10 | **0.99** | ✅ |
| `full_incident_runbook` | 20 / 20 | **0.50** | ✅ |
| **平均** | **9.7** | **0.83** | **3/3** |
### 使用 Qwen 2.5 72B(通过 HF Router)— Zero-Shot
| 任务 | 已用步数 | 最终得分 | 成功 |
|------|-----------|-------------|---------|
| `alert_triage` | 5 / 8 | **1.00** | ✅ |
| `root_cause_diagnosis` | 4 / 10 | **1.00** | ✅ |
| `full_incident_runbook` | 6 / 20 | **0.41** | ✅ |
| **平均** | **5** | **0.80** | **3/3** |
## 🌟 关键设计决策
### 1. 模糊评分 — 从不要求精确字符串
```
def matches_any(text: str, keywords: List[str]) -> bool:
"""Case-insensitive substring matching — generous by design."""
text_lower = text.lower()
return any(kw.lower() in text_lower for kw in keywords)
# "db cpu is really high" → 匹配 ["db-primary", "cpu", "database"]
# "DATABASE OVERLOAD" → 匹配(不区分大小写)
# "connection exhausted" → 匹配 ["connection pool", "pool"]
```
### 2. 线程安全的会话管理
```
# 每个 /reset 创建一个完全隔离的 session
# 支持最多 50 个并发 session
# 最旧的 session 会自动驱逐 (FIFO)
sessions: OrderedDict[str, SREEnvironment] = OrderedDict()
MAX_SESSIONS = 50
# Session ID 会在响应 header 和 body 中返回
response.headers["X-Session-ID"] = session_id
observation.session_id = session_id
```
### 3. 虚假警报以增加现实难度
任务 3 故意包含看似重要但并非如此的误导性警报。这测试了智能体是否能够抵制调查无关信号的冲动——这是现实世界中 SRE 的一项关键技能。
### 4. 严格的修复顺序
真实的事故响应存在依赖关系。在修复 Redis 之前重启 auth 是无效的——auth 会立即再次崩溃。顺序标准测试了智能体是否理解修复*为什么*必须按顺序进行。
### 5. 场景变体以实现可重玩性
每个任务都有多个场景变体,在重置时随机选择。这可以防止智能体死记硬背答案,并确保分数反映真实的推理能力。
### 6. 全面的测试套件
```
pytest tests/ -v --tb=short
# 29 passed in 0.25s
```
每个评分标准都经过独立测试。模糊匹配、惩罚逻辑、修复顺序、事后分析完整性、会话隔离——均已验证。
## 💰 奖励函数
**累积且部分奖励 — 绝非二进制。**
```
reset() → reward = 0.00
step 1 → reward = 0.15 (acknowledged root cause)
step 2 → reward = 0.30 (classified P1)
step 3 → reward = 0.45 (diagnosed root cause)
step 4 → reward = 0.70 (classified remaining alerts)
step 5 → reward = 0.85 (identified cascade)
step 6 → reward = 0.99 (complete) → done=True
```
**惩罚:**
```
-0.10 Apply fix to wrong service before root cause identified
-0.05 Escalate when reward already > 0.5 (unnecessary escalation)
-0.05 Blame wrong service as root cause (Task 3)
-0.02 Noop after step 5 (penalizes stalling)
0.00 Minimum floor — reward never goes negative
```
**Episode 结束条件:** reward ≥ 0.95 或达到 max_steps
## 🔌 完整 API 参考
### `GET /health`
```
{
"status": "ok",
"environment": "sre-incident-response",
"version": "1.0.0",
"tasks_available": 3,
"active_sessions": 2
}
```
### `GET /metrics`
```
{
"total_resets": 47,
"total_steps": 312,
"total_episodes_completed": 41,
"average_final_reward": 0.847,
"active_sessions": 2
}
```
### `POST /reset`
```
curl -X POST /reset \
-H "Content-Type: application/json" \
-d '{"task_id": "alert_triage"}'
```
返回 `ObservationModel` + `X-Session-ID` 响应头
### `POST /step`
```
curl -X POST /step \
-H "Content-Type: application/json" \
-d '{"action_type": "diagnose", "value": "db-primary CPU overload root cause"}'
```
返回包含 `reward`、`done`、`success`、`info.grader_breakdown` 的 `StepResultModel`
### `GET /state`
返回当前任务、episode ID、步数、累积奖励、按标准划分的评分
### `GET /tasks`
返回所有 3 个任务定义,包括难度、max_steps、描述
### `GET /docs`
所有端点的交互式 Swagger UI
## 📁 项目结构
```
sre-incident-response/
│
├── main.py ← FastAPI app — all 7 endpoints, session management
├── environment.py ← SREEnvironment — loop detection, state management
├── models.py ← Pydantic v2 models — fully typed
├── inference.py ← Baseline LLM agent — OpenAI client
├── openenv.yaml ← OpenEnv spec metadata
├── Dockerfile ← Production image (python:3.11-slim, port 7860)
├── requirements.txt ← Pinned dependencies
├── pyproject.toml ← Package metadata + openenv entry points
├── uv.lock ← Reproducible dependency lock
│
├── tasks/
│ ├── __init__.py ← Task registry
│ ├── base_task.py ← Abstract Task base class
│ ├── alert_triage.py ← Task 1: Alert Triage (Easy)
│ ├── root_cause.py ← Task 2: Root Cause Diagnosis (Medium)
│ └── full_runbook.py ← Task 3: Full Incident Runbook (Hard)
│ Red herrings, strict ordering, 4-section postmortem
│
├── graders/
│ ├── __init__.py
│ └── base_grader.py ← Fuzzy matching grader engine
│
├── data/
│ ├── __init__.py
│ └── scenarios.py ← All scenario data + variants (random selection on reset)
│
├── server/
│ ├── __init__.py
│ └── app.py ← OpenEnv server entry point
│
└── tests/
├── __init__.py
├── conftest.py ← Pytest fixtures
└── test_graders.py ← 29 tests covering all graders
├── TestAlertTriageGrader (10 tests)
├── TestRootCauseDiagnosisGrader (5 tests)
├── TestFullRunbookGrader (7 tests)
└── TestEnvironmentCore (7 tests)
```
## 🚀 设置与安装
### 本地 (pip)
```
git clone https://github.com/KartikAneja5/sre-incident-response.git
cd sre-incident-response
pip install -r requirements.txt
uvicorn main:app --host 0.0.0.0 --port 8000
curl http://localhost:8000/health
```
### Docker
```
docker build -t sre-env .
docker run -p 8000:7860 sre-env
curl http://localhost:8000/health
# {"status":"ok","environment":"sre-incident-response","version":"1.0.0"}
```
### HuggingFace Space (Live)
```
curl https://kartikaneja5-sre-incident-response.hf.space/health
```
## 🧪 运行测试
```
pip install pytest
pytest tests/ -v --tb=short
# 预期输出:
# 29 passed in 0.25s
```
测试覆盖:部分奖励、模糊匹配、修复顺序、事后分析完整性、会话隔离、场景变体、惩罚逻辑、episode 边界。
## 🤖 运行基线
```
# 使用 HuggingFace router
export HF_TOKEN=your_hf_token
export API_BASE_URL=https://router.huggingface.co/v1
export MODEL_NAME=Qwen/Qwen2.5-72B-Instruct
export ENV_BASE_URL=http://localhost:8000
python inference.py
```
**预期标准输出:**
```
[START] task=alert_triage env=sre-incident-response model=Qwen/Qwen2.5-72B-Instruct
[STEP] step=1 action=acknowledge_alert('CRITICAL: db-primary CPU > 95%') reward=0.30 done=false error=null
[STEP] step=2 action=diagnose('db-primary CPU overload cascading failures') reward=0.45 done=false error=null
[STEP] step=3 action=diagnose('payment-service P1 downstream') reward=0.70 done=false error=null
[STEP] step=4 action=diagnose('cascade from db to all services') reward=0.99 done=true error=null
[END] success=true steps=4 score=0.99 rewards=0.30,0.45,0.70,0.99
```
### 环境变量
| 变量 | 默认值 | 描述 |
|----------|---------|-------------|
| `API_BASE_URL` | `https://router.huggingface.co/v1` | LLM API 端点 |
| `MODEL_NAME` | `Qwen/Qwen2.5-72B-Instruct` | 模型标识符 |
| `HF_TOKEN` | — | API 密钥 |
| `ENV_BASE_URL` | `http://localhost:8000` | 环境服务器 URL |
## ✅ OpenEnv 规范合规性
```
$ openenv validate
[OK] sre-incident-response: Ready for multi-mode deployment
```
| 要求 | 状态 |
|-------------|--------|
| 类型化的 Pydantic v2 模型 | ✅ |
| `POST /reset` → `ObservationModel` | ✅ |
| `POST /step` → `StepResultModel` | ✅ |
| `GET /state` → `StateModel` | ✅ |
| `openenv.yaml` 有效 | ✅ |
| 带有服务器入口点的 `pyproject.toml` | ✅ |
| 存在 `uv.lock` | ✅ |
| 3 个以上带评分器的任务 | ✅ |
| 分数严格在 `[0.0, 1.0]` 范围内 | ✅ |
| Docker 构建干净 | ✅ |
| HF Space 在线且响应 | ✅ |
| 29 个测试通过 | ✅ |
| 线程安全的会话管理 | ✅ |
## 🧠 为什么前沿模型在任务 3 上表现困难
|挑战 | 原因 |
|-----------|---------------|
| **3 个虚假警报** | 模型在 api-gateway 和 payment-service 上浪费步数 |
| **特定的技术知识** | 必须知道 `maxmemory-policy allkeys-lru` — 通用答案失败 |
| **严格的修复顺序** | 在 Redis 之前修复 auth 会导致 auth 立即再次失败 |
| **4 部分的事后分析** | 必须包含时间线 + RCA + 行动项 + 预防 |
| **级联推理** | 必须追踪 Redis OOM → auth 重试风暴 → 熔断器 → 登录中断 |
| **错误服务惩罚** | 指责错误的服务会扣除 -0.10 的奖励 |
即使是 GPT-4 级别的模型在此任务上通常也只能获得 0.40-0.65 的分数——这使其对评估具有真正的价值。
## 📄 许可证
MIT — 由 [Kartik Aneja](https://github.com/KartikAneja5) 和 [Nihal Joshi](https://github.com/Nihal040806) 为 Meta × Hugging Face OpenEnv Hackathon 2026 构建标签:Agent, AIOps, AI智能体, DLL 劫持, Docker, Hugging Face, LLM, Meta, OpenEnv, Python, RL, SRE, Unmanaged PE, 事故处理, 人工智能, 偏差过滤, 告警分类, 大语言模型, 安全防御评估, 开源, 强化学习, 性能评估, 故障响应, 无后门, 根因分析, 模拟环境, 环境仿真, 用户模式Hook绕过, 站点可靠性工程, 自动运维, 请求拦截, 运维, 逆向工具, 黑客松