Spaces:
Sleeping
Sleeping
feat: add SRE incident benchmark (Pivot 2 - Scenario A)
Browse filesAdd live incident diagnosis flow with ServiceManager, SRE tools
(query_logs, curl_endpoint, execute_sql, restart_service), incident
grader, and incident1 task (poisoned database record).
- debug_env/models.py +8 -1
- debug_env/server/app.py +12 -0
- debug_env/server/debug_env_environment.py +120 -4
- debug_env/server/graders/__init__.py +3 -0
- debug_env/server/graders/incident_grader.py +150 -0
- debug_env/server/services/__init__.py +3 -0
- debug_env/server/services/manager.py +149 -0
- debug_env/server/services/traffic.py +53 -0
- debug_env/server/tasks/data.py +32 -0
- debug_env/server/tasks/loader.py +27 -0
- debug_env/server/tools/__init__.py +14 -1
- debug_env/server/tools/curl_endpoint/__init__.py +3 -0
- debug_env/server/tools/curl_endpoint/tool.py +83 -0
- debug_env/server/tools/execute_sql/__init__.py +3 -0
- debug_env/server/tools/execute_sql/tool.py +97 -0
- debug_env/server/tools/query_logs/__init__.py +3 -0
- debug_env/server/tools/query_logs/tool.py +78 -0
- debug_env/server/tools/restart_service/__init__.py +3 -0
- debug_env/server/tools/restart_service/tool.py +52 -0
- debug_env/tasks/incident1/__init__.py +0 -0
- debug_env/tasks/incident1/buggy_server.py +109 -0
- debug_env/tasks/incident1/seed_data.py +61 -0
- debug_env/tasks/incident1/worker.py +39 -0
debug_env/models.py
CHANGED
|
@@ -2,7 +2,14 @@ from openenv.core.env_server.types import Action, Observation
|
|
| 2 |
from pydantic import Field
|
| 3 |
|
| 4 |
class DebugAction(Action):
|
| 5 |
-
tool: str = Field(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
args: dict = Field(default_factory=dict, description="Arguments for the tool")
|
| 7 |
|
| 8 |
class DebugObservation(Observation):
|
|
|
|
| 2 |
from pydantic import Field
|
| 3 |
|
| 4 |
class DebugAction(Action):
|
| 5 |
+
tool: str = Field(
|
| 6 |
+
...,
|
| 7 |
+
description=(
|
| 8 |
+
"Tool to use. Debug tasks: run_tests, read_file, edit_file, list_files. "
|
| 9 |
+
"Incident tasks (SRE): query_logs, curl_endpoint, execute_sql, "
|
| 10 |
+
"restart_service, read_file, edit_file, list_files."
|
| 11 |
+
),
|
| 12 |
+
)
|
| 13 |
args: dict = Field(default_factory=dict, description="Arguments for the tool")
|
| 14 |
|
| 15 |
class DebugObservation(Observation):
|
debug_env/server/app.py
CHANGED
|
@@ -59,6 +59,18 @@ async def startup_event():
|
|
| 59 |
"""Initialize database and seed task registry on startup."""
|
| 60 |
init_db()
|
| 61 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
@app.get("/")
|
| 63 |
async def root():
|
| 64 |
"""Root endpoint for HF Spaces health checks."""
|
|
|
|
| 59 |
"""Initialize database and seed task registry on startup."""
|
| 60 |
init_db()
|
| 61 |
|
| 62 |
+
|
| 63 |
+
@app.on_event("shutdown")
|
| 64 |
+
async def shutdown_event():
|
| 65 |
+
"""Stop any running incident service subprocess on server shutdown."""
|
| 66 |
+
sm = DebugEnvironment._shared.get("service_manager")
|
| 67 |
+
if sm is not None:
|
| 68 |
+
try:
|
| 69 |
+
sm.stop()
|
| 70 |
+
except Exception:
|
| 71 |
+
pass
|
| 72 |
+
|
| 73 |
+
|
| 74 |
@app.get("/")
|
| 75 |
async def root():
|
| 76 |
"""Root endpoint for HF Spaces health checks."""
|
debug_env/server/debug_env_environment.py
CHANGED
|
@@ -9,7 +9,16 @@ from debug_env.models import DebugAction, DebugObservation
|
|
| 9 |
from debug_env.server.grader import grade_with_steps
|
| 10 |
from debug_env.server.schemas import ToolResult
|
| 11 |
from debug_env.server.tasks import TaskLoader
|
| 12 |
-
from debug_env.server.tools import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
logger = logging.getLogger(__name__)
|
| 15 |
|
|
@@ -38,6 +47,11 @@ class DebugEnvironment(Environment):
|
|
| 38 |
"task": "task1",
|
| 39 |
"step_count": 0,
|
| 40 |
"episode_id": "",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
}
|
| 42 |
|
| 43 |
def __init__(self):
|
|
@@ -53,11 +67,20 @@ class DebugEnvironment(Environment):
|
|
| 53 |
if task is not None:
|
| 54 |
self.current_task = task
|
| 55 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
new_episode_id = episode_id or str(uuid4())
|
| 57 |
old_workdir = DebugEnvironment._shared["workdir"]
|
| 58 |
self.workdir = TaskLoader.load(self.current_task, old_workdir)
|
| 59 |
|
| 60 |
-
# Persist
|
| 61 |
DebugEnvironment._shared["task"] = self.current_task
|
| 62 |
DebugEnvironment._shared["workdir"] = self.workdir
|
| 63 |
DebugEnvironment._shared["step_count"] = 0
|
|
@@ -65,12 +88,51 @@ class DebugEnvironment(Environment):
|
|
| 65 |
|
| 66 |
self._state = State(episode_id=new_episode_id, step_count=0)
|
| 67 |
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
return DebugObservation(
|
| 70 |
pass_rate=0.0,
|
| 71 |
logs=f"Task '{self.current_task}' loaded. Fix the bugs!",
|
| 72 |
)
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
# ββ Tool dispatch ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 75 |
|
| 76 |
def _handle_run_tests(self, workdir: str) -> ToolResult:
|
|
@@ -86,6 +148,31 @@ class DebugEnvironment(Environment):
|
|
| 86 |
content=args.get("content", ""),
|
| 87 |
)
|
| 88 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
# ββ Core step ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 90 |
|
| 91 |
def step(self, action: DebugAction, timeout_s: float | None = None, **kwargs) -> DebugObservation: # noqa: ARG002
|
|
@@ -110,10 +197,39 @@ class DebugEnvironment(Environment):
|
|
| 110 |
result = self._handle_edit_file(self.workdir, args)
|
| 111 |
elif tool == "list_files":
|
| 112 |
result = list_files(self.workdir)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
else:
|
| 114 |
result = ToolResult(
|
| 115 |
pass_rate=0.0,
|
| 116 |
-
logs=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
success=False,
|
| 118 |
)
|
| 119 |
except Exception as e:
|
|
|
|
| 9 |
from debug_env.server.grader import grade_with_steps
|
| 10 |
from debug_env.server.schemas import ToolResult
|
| 11 |
from debug_env.server.tasks import TaskLoader
|
| 12 |
+
from debug_env.server.tools import (
|
| 13 |
+
curl_endpoint,
|
| 14 |
+
edit_file,
|
| 15 |
+
execute_sql,
|
| 16 |
+
list_files,
|
| 17 |
+
query_logs,
|
| 18 |
+
read_file,
|
| 19 |
+
restart_service,
|
| 20 |
+
run_tests,
|
| 21 |
+
)
|
| 22 |
|
| 23 |
logger = logging.getLogger(__name__)
|
| 24 |
|
|
|
|
| 47 |
"task": "task1",
|
| 48 |
"step_count": 0,
|
| 49 |
"episode_id": "",
|
| 50 |
+
# Incident-task state
|
| 51 |
+
"service_manager": None,
|
| 52 |
+
"task_type": "debug",
|
| 53 |
+
"incident_port": None,
|
| 54 |
+
"server_entrypoint": None,
|
| 55 |
}
|
| 56 |
|
| 57 |
def __init__(self):
|
|
|
|
| 67 |
if task is not None:
|
| 68 |
self.current_task = task
|
| 69 |
|
| 70 |
+
# Stop any previously running service before loading a new task
|
| 71 |
+
old_sm = DebugEnvironment._shared.get("service_manager")
|
| 72 |
+
if old_sm is not None:
|
| 73 |
+
try:
|
| 74 |
+
old_sm.stop()
|
| 75 |
+
except Exception as exc:
|
| 76 |
+
logger.warning("Failed to stop previous service: %s", exc)
|
| 77 |
+
DebugEnvironment._shared["service_manager"] = None
|
| 78 |
+
|
| 79 |
new_episode_id = episode_id or str(uuid4())
|
| 80 |
old_workdir = DebugEnvironment._shared["workdir"]
|
| 81 |
self.workdir = TaskLoader.load(self.current_task, old_workdir)
|
| 82 |
|
| 83 |
+
# Persist common state
|
| 84 |
DebugEnvironment._shared["task"] = self.current_task
|
| 85 |
DebugEnvironment._shared["workdir"] = self.workdir
|
| 86 |
DebugEnvironment._shared["step_count"] = 0
|
|
|
|
| 88 |
|
| 89 |
self._state = State(episode_id=new_episode_id, step_count=0)
|
| 90 |
|
| 91 |
+
# Determine task type and branch accordingly
|
| 92 |
+
from debug_env.server.tasks.data import get_task_by_id
|
| 93 |
+
task_meta = get_task_by_id(self.current_task)
|
| 94 |
+
task_type = task_meta.get("task_type", "debug")
|
| 95 |
+
DebugEnvironment._shared["task_type"] = task_type
|
| 96 |
+
|
| 97 |
+
if task_type == "incident":
|
| 98 |
+
return self._reset_incident(task_meta)
|
| 99 |
+
|
| 100 |
+
# ββ Standard debug task ββββββββββββββββββββββββββββββββββββββββββββ
|
| 101 |
+
DebugEnvironment._shared["incident_port"] = None
|
| 102 |
+
DebugEnvironment._shared["server_entrypoint"] = None
|
| 103 |
+
logger.info("Reset β task=%s workdir=%s", self.current_task, self.workdir)
|
| 104 |
return DebugObservation(
|
| 105 |
pass_rate=0.0,
|
| 106 |
logs=f"Task '{self.current_task}' loaded. Fix the bugs!",
|
| 107 |
)
|
| 108 |
|
| 109 |
+
def _reset_incident(self, task_meta: dict) -> DebugObservation:
|
| 110 |
+
"""Start the buggy server for an incident-type task and return the alert."""
|
| 111 |
+
from debug_env.server.services import ServiceManager
|
| 112 |
+
|
| 113 |
+
entrypoint = task_meta.get("server_entrypoint", "buggy_server.py")
|
| 114 |
+
DebugEnvironment._shared["server_entrypoint"] = entrypoint
|
| 115 |
+
|
| 116 |
+
sm = ServiceManager()
|
| 117 |
+
port = sm.find_free_port()
|
| 118 |
+
try:
|
| 119 |
+
sm.start(self.workdir, entrypoint, port)
|
| 120 |
+
except Exception as exc:
|
| 121 |
+
logger.error("Failed to start incident service: %s", exc, exc_info=True)
|
| 122 |
+
return DebugObservation(
|
| 123 |
+
pass_rate=0.0,
|
| 124 |
+
logs=f"Service failed to start: {exc}\nCheck that fastapi and uvicorn are installed.",
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
DebugEnvironment._shared["service_manager"] = sm
|
| 128 |
+
DebugEnvironment._shared["incident_port"] = sm.port
|
| 129 |
+
|
| 130 |
+
alert = task_meta.get("alert_message", "Incident loaded. Diagnose and fix the service.")
|
| 131 |
+
logger.info(
|
| 132 |
+
"Reset β task=%s workdir=%s port=%s", self.current_task, self.workdir, sm.port
|
| 133 |
+
)
|
| 134 |
+
return DebugObservation(pass_rate=0.0, logs=alert)
|
| 135 |
+
|
| 136 |
# ββ Tool dispatch ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 137 |
|
| 138 |
def _handle_run_tests(self, workdir: str) -> ToolResult:
|
|
|
|
| 148 |
content=args.get("content", ""),
|
| 149 |
)
|
| 150 |
|
| 151 |
+
def _handle_restart_service(self) -> ToolResult:
|
| 152 |
+
"""Restart the buggy server then run the incident grader for the reward signal."""
|
| 153 |
+
sm = DebugEnvironment._shared.get("service_manager")
|
| 154 |
+
entrypoint = DebugEnvironment._shared.get("server_entrypoint", "buggy_server.py")
|
| 155 |
+
|
| 156 |
+
restart_result = restart_service(self.workdir, sm, entrypoint)
|
| 157 |
+
if not restart_result.success:
|
| 158 |
+
return restart_result
|
| 159 |
+
|
| 160 |
+
# Update the port in shared state after restart
|
| 161 |
+
if sm is not None and sm.port is not None:
|
| 162 |
+
DebugEnvironment._shared["incident_port"] = sm.port
|
| 163 |
+
|
| 164 |
+
# Run the incident grader β this IS the reward signal for the episode
|
| 165 |
+
from debug_env.server.graders import grade_incident
|
| 166 |
+
grade_result = grade_incident(self.workdir, sm, entrypoint)
|
| 167 |
+
|
| 168 |
+
# Prepend the restart status to the grader output for clarity
|
| 169 |
+
combined_logs = f"{restart_result.logs}\n\n{grade_result.logs}"
|
| 170 |
+
return ToolResult(
|
| 171 |
+
pass_rate=grade_result.pass_rate,
|
| 172 |
+
logs=combined_logs,
|
| 173 |
+
success=grade_result.success,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
# ββ Core step ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 177 |
|
| 178 |
def step(self, action: DebugAction, timeout_s: float | None = None, **kwargs) -> DebugObservation: # noqa: ARG002
|
|
|
|
| 197 |
result = self._handle_edit_file(self.workdir, args)
|
| 198 |
elif tool == "list_files":
|
| 199 |
result = list_files(self.workdir)
|
| 200 |
+
# ββ SRE / incident tools βββββββββββββββββββββββββββββββββββββββ
|
| 201 |
+
elif tool == "query_logs":
|
| 202 |
+
result = query_logs(
|
| 203 |
+
self.workdir,
|
| 204 |
+
log_file_path=args.get("log_file_path", "app.log"),
|
| 205 |
+
filter_string=args.get("filter_string", ""),
|
| 206 |
+
tail=int(args.get("tail", 100)),
|
| 207 |
+
)
|
| 208 |
+
elif tool == "curl_endpoint":
|
| 209 |
+
port = DebugEnvironment._shared.get("incident_port") or args.get("port")
|
| 210 |
+
result = curl_endpoint(
|
| 211 |
+
port=port,
|
| 212 |
+
method=args.get("method", "GET"),
|
| 213 |
+
path=args.get("path", "/"),
|
| 214 |
+
payload=args.get("payload", ""),
|
| 215 |
+
headers=args.get("headers"),
|
| 216 |
+
)
|
| 217 |
+
elif tool == "execute_sql":
|
| 218 |
+
result = execute_sql(
|
| 219 |
+
self.workdir,
|
| 220 |
+
query=args.get("query", ""),
|
| 221 |
+
)
|
| 222 |
+
elif tool == "restart_service":
|
| 223 |
+
result = self._handle_restart_service()
|
| 224 |
else:
|
| 225 |
result = ToolResult(
|
| 226 |
pass_rate=0.0,
|
| 227 |
+
logs=(
|
| 228 |
+
f"Unknown tool: '{tool}'. "
|
| 229 |
+
"Debug tasks: run_tests, read_file, edit_file, list_files. "
|
| 230 |
+
"Incident tasks: query_logs, curl_endpoint, execute_sql, "
|
| 231 |
+
"restart_service, read_file, edit_file, list_files."
|
| 232 |
+
),
|
| 233 |
success=False,
|
| 234 |
)
|
| 235 |
except Exception as e:
|
debug_env/server/graders/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .incident_grader import grade_incident
|
| 2 |
+
|
| 3 |
+
__all__ = ["grade_incident"]
|
debug_env/server/graders/incident_grader.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Incident grader β verifies that the SRE incident has been fully resolved.
|
| 3 |
+
|
| 4 |
+
Three checks are performed, each worth 1/3 of the total score:
|
| 5 |
+
|
| 6 |
+
1. **Service alive** β GET /health returns HTTP 200.
|
| 7 |
+
2. **DB state clean** β no job rows remain with status='pending'.
|
| 8 |
+
3. **Code hardened** β worker.py contains a try/except block that wraps
|
| 9 |
+
the json.loads call (verified via AST analysis, not text search).
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
import ast
|
| 13 |
+
import logging
|
| 14 |
+
import sqlite3
|
| 15 |
+
import urllib.error
|
| 16 |
+
import urllib.request
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
from debug_env.server.schemas import ToolResult
|
| 20 |
+
|
| 21 |
+
logger = logging.getLogger(__name__)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
# ββ Public API ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def grade_incident(workdir: str, service_manager, entrypoint: str) -> ToolResult:
|
| 28 |
+
"""
|
| 29 |
+
Run the three incident-resolution checks and return a scored ToolResult.
|
| 30 |
+
|
| 31 |
+
Args:
|
| 32 |
+
workdir: Absolute path to the task working directory.
|
| 33 |
+
service_manager: :class:`~debug_env.server.services.ServiceManager` instance.
|
| 34 |
+
entrypoint: Server script filename (unused here, kept for symmetry).
|
| 35 |
+
|
| 36 |
+
Returns:
|
| 37 |
+
:class:`ToolResult` where ``pass_rate = checks_passed / 3``.
|
| 38 |
+
"""
|
| 39 |
+
results: list[str] = []
|
| 40 |
+
checks_passed = 0
|
| 41 |
+
|
| 42 |
+
# ββ Check 1: service liveness ββββββββββββββββββββββββββββββββββββββββββ
|
| 43 |
+
port = service_manager.port if service_manager is not None else None
|
| 44 |
+
if port is not None:
|
| 45 |
+
try:
|
| 46 |
+
with urllib.request.urlopen(
|
| 47 |
+
f"http://localhost:{port}/health", timeout=3
|
| 48 |
+
) as resp:
|
| 49 |
+
if resp.status == 200:
|
| 50 |
+
checks_passed += 1
|
| 51 |
+
results.append("[1/3] PASS Service is healthy (GET /health β 200)")
|
| 52 |
+
else:
|
| 53 |
+
results.append(f"[1/3] FAIL Service returned HTTP {resp.status}")
|
| 54 |
+
except urllib.error.URLError as exc:
|
| 55 |
+
results.append(f"[1/3] FAIL Service unreachable: {exc.reason}")
|
| 56 |
+
except Exception as exc:
|
| 57 |
+
results.append(f"[1/3] FAIL Health check error: {exc}")
|
| 58 |
+
else:
|
| 59 |
+
results.append("[1/3] FAIL Service not started (no port assigned)")
|
| 60 |
+
|
| 61 |
+
# ββ Check 2: database clean (no pending jobs) ββββββββββββββββββββββββββ
|
| 62 |
+
db_path = Path(workdir) / "app.db"
|
| 63 |
+
if db_path.exists():
|
| 64 |
+
try:
|
| 65 |
+
conn = sqlite3.connect(str(db_path))
|
| 66 |
+
(pending_count,) = conn.execute(
|
| 67 |
+
"SELECT COUNT(*) FROM jobs WHERE status='pending'"
|
| 68 |
+
).fetchone()
|
| 69 |
+
conn.close()
|
| 70 |
+
if pending_count == 0:
|
| 71 |
+
checks_passed += 1
|
| 72 |
+
results.append("[2/3] PASS DB is clean β no pending jobs remain")
|
| 73 |
+
else:
|
| 74 |
+
results.append(
|
| 75 |
+
f"[2/3] FAIL DB still has {pending_count} pending job(s) "
|
| 76 |
+
"(fix or delete the poisoned row)"
|
| 77 |
+
)
|
| 78 |
+
except sqlite3.Error as exc:
|
| 79 |
+
results.append(f"[2/3] FAIL DB check error: {exc}")
|
| 80 |
+
else:
|
| 81 |
+
results.append("[2/3] FAIL app.db not found in workdir")
|
| 82 |
+
|
| 83 |
+
# ββ Check 3: worker.py hardened with try/except ββββββββββββββββββββββββ
|
| 84 |
+
worker_path = Path(workdir) / "worker.py"
|
| 85 |
+
if worker_path.exists():
|
| 86 |
+
try:
|
| 87 |
+
source = worker_path.read_text(encoding="utf-8")
|
| 88 |
+
tree = ast.parse(source)
|
| 89 |
+
if _json_loads_inside_try(tree):
|
| 90 |
+
checks_passed += 1
|
| 91 |
+
results.append(
|
| 92 |
+
"[3/3] PASS worker.py has try/except wrapping json.loads"
|
| 93 |
+
)
|
| 94 |
+
else:
|
| 95 |
+
results.append(
|
| 96 |
+
"[3/3] FAIL worker.py still calls json.loads outside a try/except"
|
| 97 |
+
)
|
| 98 |
+
except SyntaxError as exc:
|
| 99 |
+
results.append(f"[3/3] FAIL worker.py has a syntax error: {exc}")
|
| 100 |
+
else:
|
| 101 |
+
results.append("[3/3] FAIL worker.py not found in workdir")
|
| 102 |
+
|
| 103 |
+
pass_rate = checks_passed / 3.0
|
| 104 |
+
summary = (
|
| 105 |
+
f"\nResult: {checks_passed}/3 checks passed "
|
| 106 |
+
f"(pass_rate={pass_rate:.4f})"
|
| 107 |
+
)
|
| 108 |
+
all_output = "\n".join(results) + summary
|
| 109 |
+
|
| 110 |
+
logger.info(
|
| 111 |
+
"grade_incident: %d/3 checks passed (pass_rate=%.4f)", checks_passed, pass_rate
|
| 112 |
+
)
|
| 113 |
+
return ToolResult(pass_rate=pass_rate, logs=all_output, success=True)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# ββ AST helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _json_loads_inside_try(tree: ast.AST) -> bool:
|
| 120 |
+
"""
|
| 121 |
+
Return True if any ``try`` block's body contains a ``json.loads(...)`` call.
|
| 122 |
+
|
| 123 |
+
Accepts both ``json.loads(...)`` and ``loads(...)`` (from ``from json import loads``).
|
| 124 |
+
"""
|
| 125 |
+
for node in ast.walk(tree):
|
| 126 |
+
if not isinstance(node, ast.Try):
|
| 127 |
+
continue
|
| 128 |
+
# Walk only the try body, not the except/else/finally clauses
|
| 129 |
+
for child in _walk_nodes(node.body):
|
| 130 |
+
if not isinstance(child, ast.Call):
|
| 131 |
+
continue
|
| 132 |
+
func = child.func
|
| 133 |
+
if isinstance(func, ast.Attribute):
|
| 134 |
+
# json.loads(...)
|
| 135 |
+
if (
|
| 136 |
+
func.attr == "loads"
|
| 137 |
+
and isinstance(func.value, ast.Name)
|
| 138 |
+
and func.value.id == "json"
|
| 139 |
+
):
|
| 140 |
+
return True
|
| 141 |
+
elif isinstance(func, ast.Name) and func.id == "loads":
|
| 142 |
+
# loads(...) β covers `from json import loads`
|
| 143 |
+
return True
|
| 144 |
+
return False
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _walk_nodes(stmts: list) -> "ast.AST":
|
| 148 |
+
"""Yield all AST nodes reachable from a list of statements."""
|
| 149 |
+
for stmt in stmts:
|
| 150 |
+
yield from ast.walk(stmt)
|
debug_env/server/services/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .manager import ServiceManager
|
| 2 |
+
|
| 3 |
+
__all__ = ["ServiceManager"]
|
debug_env/server/services/manager.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ServiceManager β manages the lifecycle of a buggy server subprocess.
|
| 3 |
+
|
| 4 |
+
Used by incident-type tasks to spin up a realistic service environment
|
| 5 |
+
that the agent can query, diagnose, fix, and restart.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import logging
|
| 9 |
+
import os
|
| 10 |
+
import socket
|
| 11 |
+
import subprocess
|
| 12 |
+
import sys
|
| 13 |
+
import time
|
| 14 |
+
import urllib.error
|
| 15 |
+
import urllib.request
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class ServiceManager:
|
| 21 |
+
"""Manages a single buggy-server subprocess for SRE incident scenarios."""
|
| 22 |
+
|
| 23 |
+
def __init__(self) -> None:
|
| 24 |
+
self._process: subprocess.Popen | None = None
|
| 25 |
+
self._log_file = None
|
| 26 |
+
self._port: int | None = None
|
| 27 |
+
self._workdir: str | None = None
|
| 28 |
+
self._entrypoint: str | None = None
|
| 29 |
+
self._traffic: "TrafficGenerator | None" = None
|
| 30 |
+
|
| 31 |
+
# ββ Public API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 32 |
+
|
| 33 |
+
def find_free_port(self) -> int:
|
| 34 |
+
"""Return a free TCP port by binding to port 0 and releasing it."""
|
| 35 |
+
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
| 36 |
+
s.bind(("", 0))
|
| 37 |
+
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
| 38 |
+
return s.getsockname()[1]
|
| 39 |
+
|
| 40 |
+
def start(self, workdir: str, entrypoint: str, port: int) -> None:
|
| 41 |
+
"""
|
| 42 |
+
Spawn the buggy server subprocess.
|
| 43 |
+
|
| 44 |
+
Opens ``{workdir}/app.log`` for stdout/stderr, injects
|
| 45 |
+
``BUGGY_SERVER_PORT`` into the environment, then polls ``GET /health``
|
| 46 |
+
with exponential backoff (100 ms β 1 600 ms) until the server is
|
| 47 |
+
healthy or a 5-second timeout elapses.
|
| 48 |
+
|
| 49 |
+
Args:
|
| 50 |
+
workdir: Absolute path to the task working directory.
|
| 51 |
+
entrypoint: Filename of the server script (e.g. ``"buggy_server.py"``).
|
| 52 |
+
port: TCP port to bind to.
|
| 53 |
+
"""
|
| 54 |
+
self._workdir = workdir
|
| 55 |
+
self._entrypoint = entrypoint
|
| 56 |
+
self._port = port
|
| 57 |
+
|
| 58 |
+
log_path = os.path.join(workdir, "app.log")
|
| 59 |
+
self._log_file = open(log_path, "w", encoding="utf-8")
|
| 60 |
+
|
| 61 |
+
env = os.environ.copy()
|
| 62 |
+
env["BUGGY_SERVER_PORT"] = str(port)
|
| 63 |
+
|
| 64 |
+
self._process = subprocess.Popen(
|
| 65 |
+
[sys.executable, entrypoint],
|
| 66 |
+
cwd=workdir,
|
| 67 |
+
env=env,
|
| 68 |
+
stdout=self._log_file,
|
| 69 |
+
stderr=self._log_file,
|
| 70 |
+
)
|
| 71 |
+
logger.info("Started buggy server PID=%s on port %s", self._process.pid, port)
|
| 72 |
+
|
| 73 |
+
self._wait_for_health(port, timeout=5.0)
|
| 74 |
+
|
| 75 |
+
# Start background traffic so the log fills with realistic entries
|
| 76 |
+
from debug_env.server.services.traffic import TrafficGenerator
|
| 77 |
+
self._traffic = TrafficGenerator(port)
|
| 78 |
+
self._traffic.start()
|
| 79 |
+
|
| 80 |
+
def stop(self) -> None:
|
| 81 |
+
"""Terminate the subprocess and release resources."""
|
| 82 |
+
if self._traffic is not None:
|
| 83 |
+
self._traffic.stop()
|
| 84 |
+
self._traffic = None
|
| 85 |
+
|
| 86 |
+
if self._process is not None:
|
| 87 |
+
try:
|
| 88 |
+
self._process.terminate()
|
| 89 |
+
self._process.wait(timeout=5)
|
| 90 |
+
except subprocess.TimeoutExpired:
|
| 91 |
+
logger.warning("Process did not terminate gracefully β killing")
|
| 92 |
+
self._process.kill()
|
| 93 |
+
self._process.wait()
|
| 94 |
+
except OSError:
|
| 95 |
+
pass
|
| 96 |
+
logger.info("Stopped buggy server PID=%s", self._process.pid)
|
| 97 |
+
self._process = None
|
| 98 |
+
|
| 99 |
+
if self._log_file is not None:
|
| 100 |
+
try:
|
| 101 |
+
self._log_file.close()
|
| 102 |
+
except OSError:
|
| 103 |
+
pass
|
| 104 |
+
self._log_file = None
|
| 105 |
+
|
| 106 |
+
def restart(self, workdir: str, entrypoint: str) -> int:
|
| 107 |
+
"""
|
| 108 |
+
Stop the current service and start a fresh one on a new free port.
|
| 109 |
+
|
| 110 |
+
Returns:
|
| 111 |
+
The new port the service is listening on.
|
| 112 |
+
"""
|
| 113 |
+
self.stop()
|
| 114 |
+
port = self.find_free_port()
|
| 115 |
+
self.start(workdir, entrypoint, port)
|
| 116 |
+
return port
|
| 117 |
+
|
| 118 |
+
def is_running(self) -> bool:
|
| 119 |
+
"""Return True if the subprocess is alive."""
|
| 120 |
+
return self._process is not None and self._process.poll() is None
|
| 121 |
+
|
| 122 |
+
@property
|
| 123 |
+
def port(self) -> int | None:
|
| 124 |
+
"""The TCP port the service is (or was last) listening on."""
|
| 125 |
+
return self._port
|
| 126 |
+
|
| 127 |
+
# ββ Internal helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 128 |
+
|
| 129 |
+
def _wait_for_health(self, port: int, timeout: float = 5.0) -> None:
|
| 130 |
+
"""Poll GET /health with exponential backoff until healthy or timeout."""
|
| 131 |
+
deadline = time.monotonic() + timeout
|
| 132 |
+
delay = 0.1
|
| 133 |
+
url = f"http://localhost:{port}/health"
|
| 134 |
+
|
| 135 |
+
while time.monotonic() < deadline:
|
| 136 |
+
try:
|
| 137 |
+
with urllib.request.urlopen(url, timeout=1) as resp:
|
| 138 |
+
if resp.status == 200:
|
| 139 |
+
logger.info("Service is healthy on port %s", port)
|
| 140 |
+
return
|
| 141 |
+
except Exception:
|
| 142 |
+
pass
|
| 143 |
+
time.sleep(delay)
|
| 144 |
+
delay = min(delay * 2, 1.6)
|
| 145 |
+
|
| 146 |
+
raise TimeoutError(
|
| 147 |
+
f"Buggy server did not become healthy on port {port} within {timeout}s. "
|
| 148 |
+
"Check app.log for startup errors."
|
| 149 |
+
)
|
debug_env/server/services/traffic.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
TrafficGenerator β sends periodic background requests to the buggy server.
|
| 3 |
+
|
| 4 |
+
Running as a daemon thread, it hits common endpoints every 2-5 seconds so
|
| 5 |
+
that ``app.log`` accumulates realistic-looking access entries that the agent
|
| 6 |
+
can query with the ``query_logs`` tool.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import logging
|
| 10 |
+
import random
|
| 11 |
+
import threading
|
| 12 |
+
import urllib.error
|
| 13 |
+
import urllib.request
|
| 14 |
+
|
| 15 |
+
logger = logging.getLogger(__name__)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class TrafficGenerator:
|
| 19 |
+
"""Daemon thread that generates synthetic HTTP traffic against a local service."""
|
| 20 |
+
|
| 21 |
+
# Endpoints sampled for GET-style traffic
|
| 22 |
+
_GET_ENDPOINTS = ["/health", "/jobs"]
|
| 23 |
+
|
| 24 |
+
def __init__(self, port: int) -> None:
|
| 25 |
+
self._port = port
|
| 26 |
+
self._stop_event = threading.Event()
|
| 27 |
+
self._thread: threading.Thread | None = None
|
| 28 |
+
|
| 29 |
+
def start(self) -> None:
|
| 30 |
+
"""Launch the background traffic daemon thread."""
|
| 31 |
+
self._thread = threading.Thread(target=self._run, daemon=True, name="traffic-gen")
|
| 32 |
+
self._thread.start()
|
| 33 |
+
logger.debug("TrafficGenerator started on port %s", self._port)
|
| 34 |
+
|
| 35 |
+
def stop(self) -> None:
|
| 36 |
+
"""Signal the daemon thread to exit on its next iteration."""
|
| 37 |
+
self._stop_event.set()
|
| 38 |
+
|
| 39 |
+
# ββ Internal βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 40 |
+
|
| 41 |
+
def _run(self) -> None:
|
| 42 |
+
while not self._stop_event.is_set():
|
| 43 |
+
endpoint = random.choice(self._GET_ENDPOINTS)
|
| 44 |
+
url = f"http://localhost:{self._port}{endpoint}"
|
| 45 |
+
try:
|
| 46 |
+
with urllib.request.urlopen(url, timeout=2):
|
| 47 |
+
pass
|
| 48 |
+
except (urllib.error.URLError, OSError):
|
| 49 |
+
pass
|
| 50 |
+
except Exception:
|
| 51 |
+
pass
|
| 52 |
+
# Wait 2β5 s before the next request (or exit early if stopped)
|
| 53 |
+
self._stop_event.wait(random.uniform(2, 5))
|
debug_env/server/tasks/data.py
CHANGED
|
@@ -91,6 +91,38 @@ TASK_REGISTRY: Dict[str, Dict[str, Any]] = {
|
|
| 91 |
"participants": ["alice_senior", "bob_junior", "carol_qa", "dave_lead"],
|
| 92 |
"tools": ["list_directory", "get_file_structure", "get_dependencies", "search_code", "read_file", "edit_file", "run_tests", "run_type_check", "get_test_coverage"],
|
| 93 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
}
|
| 95 |
|
| 96 |
|
|
|
|
| 91 |
"participants": ["alice_senior", "bob_junior", "carol_qa", "dave_lead"],
|
| 92 |
"tools": ["list_directory", "get_file_structure", "get_dependencies", "search_code", "read_file", "edit_file", "run_tests", "run_type_check", "get_test_coverage"],
|
| 93 |
},
|
| 94 |
+
"incident1": {
|
| 95 |
+
"id": "incident1",
|
| 96 |
+
"title": "Poisoned Database Record",
|
| 97 |
+
"description": (
|
| 98 |
+
"ALERT: Background job worker crash-looping. 15% HTTP 500 rate on /checkout. "
|
| 99 |
+
"Users report 'Serialization Error'. Diagnose, fix corrupted DB state, "
|
| 100 |
+
"patch worker code, and restore service."
|
| 101 |
+
),
|
| 102 |
+
"difficulty": "hard",
|
| 103 |
+
"bug_type": "incident",
|
| 104 |
+
"task_type": "incident",
|
| 105 |
+
"files": ["buggy_server.py", "worker.py"],
|
| 106 |
+
"server_entrypoint": "buggy_server.py",
|
| 107 |
+
"tools": [
|
| 108 |
+
"query_logs", "curl_endpoint", "execute_sql", "restart_service",
|
| 109 |
+
"read_file", "edit_file", "list_files",
|
| 110 |
+
],
|
| 111 |
+
"alert_message": (
|
| 112 |
+
"ALERT [P1]: PagerDuty triggered β background job worker is crash-looping.\n\n"
|
| 113 |
+
"Symptoms:\n"
|
| 114 |
+
" * Worker thread restarting every ~0.5 s (app.log shows repeated [WORKER CRASH])\n"
|
| 115 |
+
" * ~15 % HTTP 500 rate on POST /checkout β users see 'Serialization Error'\n"
|
| 116 |
+
" * Jobs queue depth increasing: pending jobs are not being drained\n\n"
|
| 117 |
+
"Your objective:\n"
|
| 118 |
+
" 1. Diagnose the root cause using query_logs, curl_endpoint, and execute_sql\n"
|
| 119 |
+
" 2. Fix the corrupted database state (update or delete the bad job row)\n"
|
| 120 |
+
" 3. Patch worker.py to handle malformed payloads gracefully (add try/except)\n"
|
| 121 |
+
" 4. Call restart_service to restart the server and trigger final verification\n\n"
|
| 122 |
+
"Available tools: query_logs, curl_endpoint, execute_sql, read_file, edit_file,\n"
|
| 123 |
+
" list_files, restart_service\n"
|
| 124 |
+
),
|
| 125 |
+
},
|
| 126 |
}
|
| 127 |
|
| 128 |
|
debug_env/server/tasks/loader.py
CHANGED
|
@@ -16,6 +16,7 @@ Task layout on disk:
|
|
| 16 |
"""
|
| 17 |
|
| 18 |
import shutil
|
|
|
|
| 19 |
import tempfile
|
| 20 |
from pathlib import Path
|
| 21 |
|
|
@@ -73,6 +74,8 @@ class TaskLoader:
|
|
| 73 |
TaskLoader._generate_task8_files(workdir)
|
| 74 |
elif task_id == "task9":
|
| 75 |
TaskLoader._generate_task9_files(workdir)
|
|
|
|
|
|
|
| 76 |
else:
|
| 77 |
# For other tasks, copy from disk
|
| 78 |
task_path = TASKS_DIR / task_id
|
|
@@ -189,6 +192,30 @@ class TaskLoader:
|
|
| 189 |
test_content = get_test_file_content()
|
| 190 |
(Path(workdir) / seed["test_file"]).write_text(test_content, encoding="utf-8")
|
| 191 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 192 |
@staticmethod
|
| 193 |
def list_source_files(task_id: str) -> list[str]:
|
| 194 |
"""
|
|
|
|
| 16 |
"""
|
| 17 |
|
| 18 |
import shutil
|
| 19 |
+
import sqlite3
|
| 20 |
import tempfile
|
| 21 |
from pathlib import Path
|
| 22 |
|
|
|
|
| 74 |
TaskLoader._generate_task8_files(workdir)
|
| 75 |
elif task_id == "task9":
|
| 76 |
TaskLoader._generate_task9_files(workdir)
|
| 77 |
+
elif task_id == "incident1":
|
| 78 |
+
TaskLoader._generate_incident1_files(workdir)
|
| 79 |
else:
|
| 80 |
# For other tasks, copy from disk
|
| 81 |
task_path = TASKS_DIR / task_id
|
|
|
|
| 192 |
test_content = get_test_file_content()
|
| 193 |
(Path(workdir) / seed["test_file"]).write_text(test_content, encoding="utf-8")
|
| 194 |
|
| 195 |
+
@staticmethod
|
| 196 |
+
def _generate_incident1_files(workdir: str) -> None:
|
| 197 |
+
"""Copy incident1 source files and seed the SQLite database."""
|
| 198 |
+
from debug_env.tasks.incident1.seed_data import get_incident1_seed_data
|
| 199 |
+
|
| 200 |
+
seed = get_incident1_seed_data()
|
| 201 |
+
|
| 202 |
+
# Copy the declared source files from the task directory
|
| 203 |
+
from debug_env.server.tasks.data import get_task_by_id
|
| 204 |
+
task_files = get_task_by_id("incident1")["files"]
|
| 205 |
+
task_path = TASKS_DIR / "incident1"
|
| 206 |
+
for filename in task_files:
|
| 207 |
+
src = task_path / filename
|
| 208 |
+
if src.is_file():
|
| 209 |
+
shutil.copy2(src, workdir)
|
| 210 |
+
|
| 211 |
+
# Create and seed the SQLite database
|
| 212 |
+
db_path = Path(workdir) / "app.db"
|
| 213 |
+
conn = sqlite3.connect(str(db_path))
|
| 214 |
+
for sql_stmt in seed["db_seed_sql"]:
|
| 215 |
+
conn.execute(sql_stmt)
|
| 216 |
+
conn.commit()
|
| 217 |
+
conn.close()
|
| 218 |
+
|
| 219 |
@staticmethod
|
| 220 |
def list_source_files(task_id: str) -> list[str]:
|
| 221 |
"""
|
debug_env/server/tools/__init__.py
CHANGED
|
@@ -1,6 +1,19 @@
|
|
|
|
|
| 1 |
from .edit_file import edit_file
|
|
|
|
| 2 |
from .list_files import list_files
|
|
|
|
| 3 |
from .read_file import read_file
|
|
|
|
| 4 |
from .run_tests import run_tests
|
| 5 |
|
| 6 |
-
__all__ = [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .curl_endpoint import curl_endpoint
|
| 2 |
from .edit_file import edit_file
|
| 3 |
+
from .execute_sql import execute_sql
|
| 4 |
from .list_files import list_files
|
| 5 |
+
from .query_logs import query_logs
|
| 6 |
from .read_file import read_file
|
| 7 |
+
from .restart_service import restart_service
|
| 8 |
from .run_tests import run_tests
|
| 9 |
|
| 10 |
+
__all__ = [
|
| 11 |
+
"run_tests",
|
| 12 |
+
"read_file",
|
| 13 |
+
"edit_file",
|
| 14 |
+
"list_files",
|
| 15 |
+
"query_logs",
|
| 16 |
+
"curl_endpoint",
|
| 17 |
+
"execute_sql",
|
| 18 |
+
"restart_service",
|
| 19 |
+
]
|
debug_env/server/tools/curl_endpoint/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .tool import curl_endpoint
|
| 2 |
+
|
| 3 |
+
__all__ = ["curl_endpoint"]
|
debug_env/server/tools/curl_endpoint/tool.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
curl_endpoint tool β send an HTTP request to the running buggy server.
|
| 3 |
+
|
| 4 |
+
Diagnostic tool (pass_rate=0.0): inspecting HTTP responses does not affect
|
| 5 |
+
the score but lets the agent probe endpoints and reproduce error conditions.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import logging
|
| 10 |
+
import urllib.error
|
| 11 |
+
import urllib.request
|
| 12 |
+
from typing import Optional
|
| 13 |
+
|
| 14 |
+
from debug_env.server.schemas import ToolResult
|
| 15 |
+
|
| 16 |
+
logger = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def curl_endpoint(
|
| 20 |
+
port: int,
|
| 21 |
+
method: str = "GET",
|
| 22 |
+
path: str = "/",
|
| 23 |
+
payload: str = "",
|
| 24 |
+
headers: Optional[dict] = None,
|
| 25 |
+
) -> ToolResult:
|
| 26 |
+
"""
|
| 27 |
+
Send an HTTP request to ``http://localhost:{port}{path}`` and return the response.
|
| 28 |
+
|
| 29 |
+
Args:
|
| 30 |
+
port: Port the buggy server is listening on (injected by the environment).
|
| 31 |
+
method: HTTP method β ``"GET"``, ``"POST"``, etc. (case-insensitive).
|
| 32 |
+
path: Request path, e.g. ``"/health"`` or ``"/jobs"``.
|
| 33 |
+
payload: Optional request body (UTF-8 string, typically JSON).
|
| 34 |
+
headers: Extra request headers as a dict. ``Content-Type`` defaults to
|
| 35 |
+
``application/json`` when *payload* is non-empty.
|
| 36 |
+
|
| 37 |
+
Returns:
|
| 38 |
+
:class:`ToolResult` with ``pass_rate=0.0`` and the formatted response in ``logs``.
|
| 39 |
+
"""
|
| 40 |
+
if port is None:
|
| 41 |
+
return ToolResult(
|
| 42 |
+
pass_rate=0.0,
|
| 43 |
+
logs="No service is running. Reset with an incident task first.",
|
| 44 |
+
success=False,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
url = f"http://localhost:{port}{path}"
|
| 48 |
+
method_upper = method.upper()
|
| 49 |
+
data = payload.encode("utf-8") if payload else None
|
| 50 |
+
|
| 51 |
+
req_headers: dict = {}
|
| 52 |
+
if data:
|
| 53 |
+
req_headers["Content-Type"] = "application/json"
|
| 54 |
+
if headers:
|
| 55 |
+
req_headers.update(headers)
|
| 56 |
+
|
| 57 |
+
req = urllib.request.Request(url, data=data, headers=req_headers, method=method_upper)
|
| 58 |
+
|
| 59 |
+
try:
|
| 60 |
+
with urllib.request.urlopen(req, timeout=5) as resp:
|
| 61 |
+
status = resp.status
|
| 62 |
+
body = resp.read().decode("utf-8", errors="replace")
|
| 63 |
+
except urllib.error.HTTPError as exc:
|
| 64 |
+
status = exc.code
|
| 65 |
+
body = exc.read().decode("utf-8", errors="replace")
|
| 66 |
+
except urllib.error.URLError as exc:
|
| 67 |
+
return ToolResult(
|
| 68 |
+
pass_rate=0.0,
|
| 69 |
+
logs=f"Connection failed: {exc.reason}",
|
| 70 |
+
success=False,
|
| 71 |
+
)
|
| 72 |
+
except Exception as exc:
|
| 73 |
+
return ToolResult(pass_rate=0.0, logs=f"Request error: {exc}", success=False)
|
| 74 |
+
|
| 75 |
+
# Pretty-print JSON responses
|
| 76 |
+
try:
|
| 77 |
+
pretty_body = json.dumps(json.loads(body), indent=2)
|
| 78 |
+
except (json.JSONDecodeError, ValueError):
|
| 79 |
+
pretty_body = body
|
| 80 |
+
|
| 81 |
+
output = f"HTTP {status} {method_upper} {path}\n\n{pretty_body}"
|
| 82 |
+
logger.info("curl_endpoint: %s %s β HTTP %s", method_upper, url, status)
|
| 83 |
+
return ToolResult(pass_rate=0.0, logs=output, success=True)
|
debug_env/server/tools/execute_sql/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .tool import execute_sql
|
| 2 |
+
|
| 3 |
+
__all__ = ["execute_sql"]
|
debug_env/server/tools/execute_sql/tool.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
execute_sql tool β run a SQL query against the task's SQLite database.
|
| 3 |
+
|
| 4 |
+
Diagnostic (and repair) tool with pass_rate=0.0: the agent can use this to
|
| 5 |
+
inspect poisoned rows, update statuses, and clean up corrupted state.
|
| 6 |
+
|
| 7 |
+
Dangerous keywords (DROP, ATTACH, DETACH) are blocked to prevent accidental
|
| 8 |
+
destruction of the benchmark environment.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import logging
|
| 12 |
+
import re
|
| 13 |
+
import sqlite3
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
from debug_env.server.schemas import ToolResult
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger(__name__)
|
| 19 |
+
|
| 20 |
+
_BLOCKED_KEYWORDS = frozenset({"DROP", "ATTACH", "DETACH"})
|
| 21 |
+
_BLOCKED_RE = re.compile(
|
| 22 |
+
r"\b(" + "|".join(_BLOCKED_KEYWORDS) + r")\b", re.IGNORECASE
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def execute_sql(workdir: str, query: str) -> ToolResult:
|
| 27 |
+
"""
|
| 28 |
+
Execute *query* against ``{workdir}/app.db`` and return the results.
|
| 29 |
+
|
| 30 |
+
SELECT queries display rows as a plain-text table. DML statements
|
| 31 |
+
(INSERT/UPDATE/DELETE) display the affected row count.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
workdir: Absolute path to the task working directory.
|
| 35 |
+
query: SQL query to execute.
|
| 36 |
+
|
| 37 |
+
Returns:
|
| 38 |
+
:class:`ToolResult` with ``pass_rate=0.0`` and query output in ``logs``.
|
| 39 |
+
"""
|
| 40 |
+
if not query or not query.strip():
|
| 41 |
+
return ToolResult(pass_rate=0.0, logs="No query provided.", success=False)
|
| 42 |
+
|
| 43 |
+
# Block dangerous statements
|
| 44 |
+
match = _BLOCKED_RE.search(query)
|
| 45 |
+
if match:
|
| 46 |
+
keyword = match.group(0).upper()
|
| 47 |
+
return ToolResult(
|
| 48 |
+
pass_rate=0.0,
|
| 49 |
+
logs=f"SQL keyword '{keyword}' is not permitted.",
|
| 50 |
+
success=False,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
db_path = Path(workdir) / "app.db"
|
| 54 |
+
if not db_path.exists():
|
| 55 |
+
return ToolResult(
|
| 56 |
+
pass_rate=0.0,
|
| 57 |
+
logs="No app.db found in the workdir. This task may not use a database.",
|
| 58 |
+
success=False,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
conn = sqlite3.connect(str(db_path))
|
| 62 |
+
conn.row_factory = sqlite3.Row
|
| 63 |
+
try:
|
| 64 |
+
cursor = conn.execute(query)
|
| 65 |
+
if cursor.description:
|
| 66 |
+
rows = cursor.fetchall()
|
| 67 |
+
if not rows:
|
| 68 |
+
result = "(no rows returned)"
|
| 69 |
+
else:
|
| 70 |
+
col_names = [d[0] for d in cursor.description]
|
| 71 |
+
# Compute column widths
|
| 72 |
+
widths = [len(c) for c in col_names]
|
| 73 |
+
str_rows = []
|
| 74 |
+
for row in rows:
|
| 75 |
+
str_row = [str(v) if v is not None else "NULL" for v in row]
|
| 76 |
+
str_rows.append(str_row)
|
| 77 |
+
for i, cell in enumerate(str_row):
|
| 78 |
+
widths[i] = max(widths[i], len(cell))
|
| 79 |
+
|
| 80 |
+
def fmt_row(cells: list) -> str:
|
| 81 |
+
return " | ".join(cell.ljust(widths[i]) for i, cell in enumerate(cells))
|
| 82 |
+
|
| 83 |
+
header = fmt_row(col_names)
|
| 84 |
+
divider = "-+-".join("-" * w for w in widths)
|
| 85 |
+
body = "\n".join(fmt_row(r) for r in str_rows)
|
| 86 |
+
result = f"{header}\n{divider}\n{body}\n({len(rows)} row(s))"
|
| 87 |
+
else:
|
| 88 |
+
conn.commit()
|
| 89 |
+
result = f"OK β {cursor.rowcount} row(s) affected."
|
| 90 |
+
|
| 91 |
+
except sqlite3.Error as exc:
|
| 92 |
+
return ToolResult(pass_rate=0.0, logs=f"SQL error: {exc}", success=False)
|
| 93 |
+
finally:
|
| 94 |
+
conn.close()
|
| 95 |
+
|
| 96 |
+
logger.info("execute_sql: query=%r β %d chars output", query[:80], len(result))
|
| 97 |
+
return ToolResult(pass_rate=0.0, logs=result, success=True)
|
debug_env/server/tools/query_logs/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .tool import query_logs
|
| 2 |
+
|
| 3 |
+
__all__ = ["query_logs"]
|
debug_env/server/tools/query_logs/tool.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
query_logs tool β tail and filter a log file in the task workdir.
|
| 3 |
+
|
| 4 |
+
Diagnostic tool (pass_rate=0.0): reading logs does not affect the score
|
| 5 |
+
but helps the agent locate error messages, stack traces, and crash signatures.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import logging
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
from debug_env.server.schemas import ToolResult
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def query_logs(
|
| 17 |
+
workdir: str,
|
| 18 |
+
log_file_path: str = "app.log",
|
| 19 |
+
filter_string: str = "",
|
| 20 |
+
tail: int = 100,
|
| 21 |
+
) -> ToolResult:
|
| 22 |
+
"""
|
| 23 |
+
Read the last *tail* lines of a log file, optionally filtered.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
workdir: Absolute path to the task working directory.
|
| 27 |
+
log_file_path: Path to the log file, relative to workdir (default: ``"app.log"``).
|
| 28 |
+
filter_string: Case-insensitive substring filter. Only lines containing
|
| 29 |
+
this string are returned. Empty string β no filter.
|
| 30 |
+
tail: Maximum number of lines to return (from the end of the file).
|
| 31 |
+
|
| 32 |
+
Returns:
|
| 33 |
+
:class:`ToolResult` with ``pass_rate=0.0`` and the log content in ``logs``.
|
| 34 |
+
"""
|
| 35 |
+
# Validate path stays inside workdir
|
| 36 |
+
workdir_path = Path(workdir).resolve()
|
| 37 |
+
log_path = (workdir_path / log_file_path).resolve()
|
| 38 |
+
|
| 39 |
+
if not str(log_path).startswith(str(workdir_path)):
|
| 40 |
+
return ToolResult(
|
| 41 |
+
pass_rate=0.0,
|
| 42 |
+
logs=f"Access denied: '{log_file_path}' is outside the task workdir.",
|
| 43 |
+
success=False,
|
| 44 |
+
)
|
| 45 |
+
|
| 46 |
+
if not log_path.exists():
|
| 47 |
+
return ToolResult(
|
| 48 |
+
pass_rate=0.0,
|
| 49 |
+
logs=f"Log file '{log_file_path}' not found in workdir.",
|
| 50 |
+
success=False,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
try:
|
| 54 |
+
content = log_path.read_text(encoding="utf-8", errors="replace")
|
| 55 |
+
except OSError as exc:
|
| 56 |
+
return ToolResult(pass_rate=0.0, logs=f"Failed to read log: {exc}", success=False)
|
| 57 |
+
|
| 58 |
+
lines = content.splitlines()
|
| 59 |
+
|
| 60 |
+
if filter_string:
|
| 61 |
+
needle = filter_string.lower()
|
| 62 |
+
lines = [line for line in lines if needle in line.lower()]
|
| 63 |
+
|
| 64 |
+
lines = lines[-tail:]
|
| 65 |
+
|
| 66 |
+
output = "\n".join(lines) if lines else "(no matching log entries)"
|
| 67 |
+
logger.info(
|
| 68 |
+
"query_logs: file=%s filter=%r tail=%d β %d lines",
|
| 69 |
+
log_file_path,
|
| 70 |
+
filter_string,
|
| 71 |
+
tail,
|
| 72 |
+
len(lines),
|
| 73 |
+
)
|
| 74 |
+
return ToolResult(
|
| 75 |
+
pass_rate=0.0,
|
| 76 |
+
logs=f"# {log_file_path} (last {len(lines)} matching lines)\n{output}",
|
| 77 |
+
success=True,
|
| 78 |
+
)
|
debug_env/server/tools/restart_service/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .tool import restart_service
|
| 2 |
+
|
| 3 |
+
__all__ = ["restart_service"]
|
debug_env/server/tools/restart_service/tool.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
restart_service tool β stop and restart the buggy server subprocess.
|
| 3 |
+
|
| 4 |
+
After the agent has fixed the database state and patched worker.py, calling
|
| 5 |
+
this tool triggers a clean restart. The environment then automatically runs
|
| 6 |
+
the incident grader to check whether all three conditions are met.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import logging
|
| 10 |
+
|
| 11 |
+
from debug_env.server.schemas import ToolResult
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def restart_service(workdir: str, service_manager, entrypoint: str) -> ToolResult:
|
| 17 |
+
"""
|
| 18 |
+
Restart the buggy server via *service_manager*.
|
| 19 |
+
|
| 20 |
+
Args:
|
| 21 |
+
workdir: Absolute path to the task working directory.
|
| 22 |
+
service_manager: A :class:`~debug_env.server.services.ServiceManager` instance
|
| 23 |
+
held in shared environment state.
|
| 24 |
+
entrypoint: Server script filename, e.g. ``"buggy_server.py"``.
|
| 25 |
+
|
| 26 |
+
Returns:
|
| 27 |
+
:class:`ToolResult` with ``pass_rate=0.0`` and a status message.
|
| 28 |
+
The *actual* reward-bearing result is supplied by the incident grader
|
| 29 |
+
which runs immediately after in the ``step()`` handler.
|
| 30 |
+
"""
|
| 31 |
+
if service_manager is None:
|
| 32 |
+
return ToolResult(
|
| 33 |
+
pass_rate=0.0,
|
| 34 |
+
logs="No service manager found. Is this an incident task?",
|
| 35 |
+
success=False,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
new_port = service_manager.restart(workdir, entrypoint)
|
| 40 |
+
logger.info("restart_service: new port=%s", new_port)
|
| 41 |
+
return ToolResult(
|
| 42 |
+
pass_rate=0.0,
|
| 43 |
+
logs=f"Service restarted successfully. Now listening on port {new_port}.",
|
| 44 |
+
success=True,
|
| 45 |
+
)
|
| 46 |
+
except Exception as exc:
|
| 47 |
+
logger.error("restart_service failed: %s", exc, exc_info=True)
|
| 48 |
+
return ToolResult(
|
| 49 |
+
pass_rate=0.0,
|
| 50 |
+
logs=f"Service restart failed: {exc}",
|
| 51 |
+
success=False,
|
| 52 |
+
)
|
debug_env/tasks/incident1/__init__.py
ADDED
|
File without changes
|
debug_env/tasks/incident1/buggy_server.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Buggy FastAPI server for the incident1 scenario.
|
| 3 |
+
|
| 4 |
+
Serves three endpoints and runs a background job worker thread.
|
| 5 |
+
The worker crash-loops because it hits a poisoned DB record.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import json
|
| 9 |
+
import logging
|
| 10 |
+
import os
|
| 11 |
+
import sqlite3
|
| 12 |
+
import sys
|
| 13 |
+
import threading
|
| 14 |
+
import time
|
| 15 |
+
|
| 16 |
+
import uvicorn
|
| 17 |
+
from fastapi import FastAPI
|
| 18 |
+
from fastapi.responses import JSONResponse
|
| 19 |
+
|
| 20 |
+
logging.basicConfig(
|
| 21 |
+
level=logging.INFO,
|
| 22 |
+
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
|
| 23 |
+
stream=sys.stdout,
|
| 24 |
+
)
|
| 25 |
+
logger = logging.getLogger("buggy_server")
|
| 26 |
+
|
| 27 |
+
app = FastAPI()
|
| 28 |
+
|
| 29 |
+
_DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "app.db")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _get_conn() -> sqlite3.Connection:
|
| 33 |
+
conn = sqlite3.connect(_DB_PATH)
|
| 34 |
+
conn.row_factory = sqlite3.Row
|
| 35 |
+
return conn
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
# ββ Endpoints ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 39 |
+
|
| 40 |
+
@app.get("/health")
|
| 41 |
+
def health():
|
| 42 |
+
return {"status": "ok"}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@app.get("/jobs")
|
| 46 |
+
def list_jobs():
|
| 47 |
+
conn = _get_conn()
|
| 48 |
+
rows = conn.execute(
|
| 49 |
+
"SELECT id, payload, status FROM jobs ORDER BY id"
|
| 50 |
+
).fetchall()
|
| 51 |
+
conn.close()
|
| 52 |
+
return {"jobs": [dict(r) for r in rows]}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@app.post("/checkout")
|
| 56 |
+
def checkout():
|
| 57 |
+
"""Process the next pending job. Returns 500 if the payload is malformed."""
|
| 58 |
+
conn = _get_conn()
|
| 59 |
+
row = conn.execute(
|
| 60 |
+
"SELECT * FROM jobs WHERE status='pending' ORDER BY id LIMIT 1"
|
| 61 |
+
).fetchone()
|
| 62 |
+
if not row:
|
| 63 |
+
conn.close()
|
| 64 |
+
return {"status": "no_pending_jobs"}
|
| 65 |
+
try:
|
| 66 |
+
data = json.loads(row["payload"])
|
| 67 |
+
conn.execute(
|
| 68 |
+
"UPDATE jobs SET status='completed' WHERE id=?", (row["id"],)
|
| 69 |
+
)
|
| 70 |
+
conn.commit()
|
| 71 |
+
conn.close()
|
| 72 |
+
return {"status": "ok", "job_id": row["id"], "data": data}
|
| 73 |
+
except Exception as exc:
|
| 74 |
+
conn.close()
|
| 75 |
+
return JSONResponse(
|
| 76 |
+
status_code=500,
|
| 77 |
+
content={"error": f"Serialization Error: {exc}", "job_id": row["id"]},
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# ββ Worker loop ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 82 |
+
|
| 83 |
+
def _worker_loop() -> None:
|
| 84 |
+
"""Run worker.process_jobs() in a tight restart loop (crash-loop visible in logs)."""
|
| 85 |
+
# Ensure the workdir (where worker.py lives) is importable
|
| 86 |
+
workdir = os.path.dirname(os.path.abspath(__file__))
|
| 87 |
+
if workdir not in sys.path:
|
| 88 |
+
sys.path.insert(0, workdir)
|
| 89 |
+
|
| 90 |
+
import worker
|
| 91 |
+
|
| 92 |
+
while True:
|
| 93 |
+
try:
|
| 94 |
+
worker.process_jobs()
|
| 95 |
+
except Exception as exc:
|
| 96 |
+
logger.error("[WORKER CRASH] %s: %s", type(exc).__name__, exc)
|
| 97 |
+
time.sleep(0.5)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
@app.on_event("startup")
|
| 101 |
+
def _start_worker() -> None:
|
| 102 |
+
t = threading.Thread(target=_worker_loop, daemon=True, name="worker-loop")
|
| 103 |
+
t.start()
|
| 104 |
+
logger.info("Worker thread started")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
if __name__ == "__main__":
|
| 108 |
+
port = int(os.environ.get("BUGGY_SERVER_PORT", 9000))
|
| 109 |
+
uvicorn.run(app, host="0.0.0.0", port=port, log_config=None)
|
debug_env/tasks/incident1/seed_data.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Incident 1 seed data β "Poisoned Database Record" scenario.
|
| 3 |
+
|
| 4 |
+
Returns the SQL statements to initialise the SQLite database and the
|
| 5 |
+
PagerDuty-style alert message shown to the agent on reset.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
_ALERT_MESSAGE = """\
|
| 9 |
+
ALERT [P1]: PagerDuty triggered β background job worker is crash-looping.
|
| 10 |
+
|
| 11 |
+
Symptoms:
|
| 12 |
+
* Worker thread restarting every ~0.5 s (app.log shows repeated [WORKER CRASH])
|
| 13 |
+
* ~15 % HTTP 500 rate on POST /checkout β users see "Serialization Error"
|
| 14 |
+
* Jobs queue depth increasing: pending jobs are not being drained
|
| 15 |
+
|
| 16 |
+
Your objective:
|
| 17 |
+
1. Diagnose the root cause using query_logs, curl_endpoint, and execute_sql
|
| 18 |
+
2. Fix the corrupted database state (update or delete the bad job row)
|
| 19 |
+
3. Patch worker.py to handle malformed payloads gracefully (add try/except)
|
| 20 |
+
4. Call restart_service to restart the server and trigger final verification
|
| 21 |
+
|
| 22 |
+
Available tools: query_logs, curl_endpoint, execute_sql, read_file, edit_file,
|
| 23 |
+
list_files, restart_service
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
_DB_SEED_SQL = [
|
| 27 |
+
"PRAGMA journal_mode=WAL",
|
| 28 |
+
(
|
| 29 |
+
"CREATE TABLE IF NOT EXISTS jobs "
|
| 30 |
+
"(id INTEGER PRIMARY KEY, payload TEXT, status TEXT DEFAULT 'pending')"
|
| 31 |
+
),
|
| 32 |
+
# Completed jobs (healthy baseline)
|
| 33 |
+
"INSERT INTO jobs (payload, status) VALUES ('{\"item\": \"widget\", \"qty\": 5}', 'completed')",
|
| 34 |
+
"INSERT INTO jobs (payload, status) VALUES ('{\"item\": \"gadget\", \"qty\": 2}', 'completed')",
|
| 35 |
+
"INSERT INTO jobs (payload, status) VALUES ('{\"item\": \"doohickey\", \"qty\": 10}', 'completed')",
|
| 36 |
+
"INSERT INTO jobs (payload, status) VALUES ('{\"item\": \"thingamajig\", \"qty\": 1}', 'completed')",
|
| 37 |
+
"INSERT INTO jobs (payload, status) VALUES ('{\"item\": \"whatsit\", \"qty\": 7}', 'completed')",
|
| 38 |
+
# Valid pending job processed before the crash
|
| 39 |
+
"INSERT INTO jobs (payload, status) VALUES ('{\"item\": \"widget_6\", \"qty\": 3}', 'pending')",
|
| 40 |
+
# ββ POISONED ROW ββ truncated JSON; json.loads raises JSONDecodeError
|
| 41 |
+
"INSERT INTO jobs (payload, status) VALUES ('{\"item\": \"toxic_widget\", \"qty\":', 'pending')",
|
| 42 |
+
# Further pending jobs β never reached due to crash above
|
| 43 |
+
"INSERT INTO jobs (payload, status) VALUES ('{\"item\": \"widget_8\", \"qty\": 4}', 'pending')",
|
| 44 |
+
"INSERT INTO jobs (payload, status) VALUES ('{\"item\": \"widget_9\", \"qty\": 6}', 'pending')",
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def get_incident1_seed_data() -> dict:
|
| 49 |
+
"""
|
| 50 |
+
Return the seed data dict for the incident1 scenario.
|
| 51 |
+
|
| 52 |
+
Keys:
|
| 53 |
+
alert_message (str) PagerDuty-style alert shown to the agent.
|
| 54 |
+
db_seed_sql (list) SQL statements to create and populate app.db.
|
| 55 |
+
server_entrypoint (str) Filename of the FastAPI server script.
|
| 56 |
+
"""
|
| 57 |
+
return {
|
| 58 |
+
"alert_message": _ALERT_MESSAGE,
|
| 59 |
+
"db_seed_sql": _DB_SEED_SQL,
|
| 60 |
+
"server_entrypoint": "buggy_server.py",
|
| 61 |
+
}
|
debug_env/tasks/incident1/worker.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Background job worker β processes pending jobs from the database.
|
| 3 |
+
|
| 4 |
+
BUG: json.loads() is called without try/except. When a job payload is
|
| 5 |
+
malformed (e.g. truncated JSON), this function raises an exception.
|
| 6 |
+
The job remains 'pending' and the worker is restarted, causing an
|
| 7 |
+
infinite crash-loop.
|
| 8 |
+
|
| 9 |
+
Fix: wrap the json.loads call in try/except and mark bad jobs as 'failed'
|
| 10 |
+
so the worker can continue processing the rest of the queue.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
import logging
|
| 15 |
+
import os
|
| 16 |
+
import sqlite3
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger("worker")
|
| 19 |
+
|
| 20 |
+
_DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "app.db")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def process_jobs() -> None:
|
| 24 |
+
"""Fetch and process all pending jobs. Crashes on malformed payloads."""
|
| 25 |
+
conn = sqlite3.connect(_DB_PATH)
|
| 26 |
+
conn.row_factory = sqlite3.Row
|
| 27 |
+
rows = conn.execute(
|
| 28 |
+
"SELECT * FROM jobs WHERE status='pending' ORDER BY id"
|
| 29 |
+
).fetchall()
|
| 30 |
+
|
| 31 |
+
for row in rows:
|
| 32 |
+
data = json.loads(row["payload"]) # BUG: no try/except β raises on bad JSON
|
| 33 |
+
logger.info("Processed job %s: item=%s", row["id"], data.get("item"))
|
| 34 |
+
conn.execute(
|
| 35 |
+
"UPDATE jobs SET status='completed' WHERE id=?", (row["id"],)
|
| 36 |
+
)
|
| 37 |
+
conn.commit()
|
| 38 |
+
|
| 39 |
+
conn.close()
|