hugsbun commited on
Commit
2058884
Β·
1 Parent(s): ba52031

feat: complete debugging workflow with HuggingFace Inference API and OpenEnv Stage 1

Browse files
.dockerignore ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .venv/
2
+ __pycache__/
3
+ *.pyc
4
+ *.pyo
5
+ *.pyd
6
+ .git/
7
+ .gitignore
8
+ *.egg-info/
9
+ .env
10
+ .env.*
11
+ !.env.example
12
+ results_*.json
13
+ *.db
14
+ .cursor/
15
+ .vscode/
16
+ *.md
17
+ !README.md
.gitignore CHANGED
@@ -9,6 +9,7 @@ QUICKSTART.md
9
  COMPETITION_CHECKLIST.md
10
  IMPLEMENTATION_SUMMARY.md
11
  TECHNOLOGY_INTEGRATION.md
 
12
  .cursorrules
13
  .windsurfrules
14
  .mcp.json
@@ -38,8 +39,6 @@ env/
38
  .coverage
39
  htmlcov/
40
 
41
- # uv
42
- uv.lock
43
 
44
  # Environment variables
45
  .env
 
9
  COMPETITION_CHECKLIST.md
10
  IMPLEMENTATION_SUMMARY.md
11
  TECHNOLOGY_INTEGRATION.md
12
+ STACK_REFERENCE.md
13
  .cursorrules
14
  .windsurfrules
15
  .mcp.json
 
39
  .coverage
40
  htmlcov/
41
 
 
 
42
 
43
  # Environment variables
44
  .env
Dockerfile ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest
2
+ FROM ${BASE_IMAGE} AS builder
3
+
4
+ WORKDIR /app
5
+
6
+ RUN apt-get update && \
7
+ apt-get install -y --no-install-recommends git && \
8
+ rm -rf /var/lib/apt/lists/*
9
+
10
+ # Copy lock files first β€” maximises layer cache on dependency-only changes
11
+ COPY pyproject.toml uv.lock ./
12
+
13
+ # Ensure uv is available
14
+ RUN if ! command -v uv >/dev/null 2>&1; then \
15
+ curl -LsSf https://astral.sh/uv/install.sh | sh && \
16
+ mv /root/.local/bin/uv /usr/local/bin/uv; \
17
+ fi
18
+
19
+ # Install dependencies (not the project itself yet) β€” cached layer
20
+ RUN --mount=type=cache,target=/root/.cache/uv \
21
+ uv sync --frozen --no-install-project --no-editable
22
+
23
+ # Copy full source and install the project package
24
+ COPY . /app
25
+ RUN --mount=type=cache,target=/root/.cache/uv \
26
+ uv sync --frozen --no-editable --extra dev
27
+
28
+ # ── Runtime stage ──────────────────────────────────────────────────────────────
29
+ FROM ${BASE_IMAGE}
30
+
31
+ WORKDIR /app
32
+
33
+ COPY --from=builder /app/.venv /app/.venv
34
+ COPY --from=builder /app /app
35
+
36
+ ENV PATH="/app/.venv/bin:$PATH"
37
+ ENV PYTHONPATH="/app:$PYTHONPATH"
38
+
39
+ HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
40
+ CMD curl -f http://localhost:7860/health || exit 1
41
+
42
+ CMD ["bash", "start.sh"]
README.md CHANGED
@@ -14,751 +14,344 @@ tags:
14
  - ai-agents
15
  ---
16
 
17
- # Debug Env β€” Production-Grade AI Debugging Benchmark
18
 
19
- A sophisticated debugging benchmark built on [OpenEnv](https://github.com/meta-pytorch/OpenEnv), designed to evaluate AI agents' ability to identify and fix bugs in real-world Python code. Features 9 progressively complex tasks, comprehensive MCP tool support, SQLite persistence, Docker deployment, and Hugging Face integration.
 
 
20
 
21
- **Live Demo**: [debug-env.hf.space](https://debug-env.hf.space)
 
22
 
23
  ---
24
 
25
- ## Table of Contents
26
-
27
- - [Overview](#overview)
28
- - [Key Features](#key-features)
29
- - [Quick Start](#quick-start)
30
- - [Installation](#installation)
31
- - [Usage](#usage)
32
- - [Architecture](#architecture)
33
- - [Deployment](#deployment)
34
- - [Docker](#docker)
35
- - [Hugging Face Spaces](#hugging-face-spaces)
36
- - [API Reference](#api-reference)
37
- - [Tasks](#tasks)
38
- - [MCP Tools](#mcp-tools)
39
- - [Database](#database)
40
- - [Development](#development)
41
- - [Contributing](#contributing)
42
- - [License](#license)
43
 
44
- ---
45
-
46
- ## Overview
 
47
 
48
- Debug Env is a production-ready debugging environment that challenges AI models to locate and fix bugs across various complexity levels. From simple syntax errors to complex multi-file architectural issues, the benchmark provides realistic debugging scenarios with comprehensive tooling for code analysis.
49
-
50
- **Built with:**
51
- - FastAPI + Uvicorn (HTTP server)
52
- - SQLAlchemy (ORM) + SQLite (persistence)
53
- - OpenEnv (environment framework)
54
- - MCP Protocol 2024-11-05 (tool interface)
55
- - Docker (containerization)
56
- - Hugging Face (model integration & hosting)
57
 
58
  ---
59
 
60
- ## Key Features
61
-
62
- | Feature | Details |
63
- |---------|---------|
64
- | **9 Tasks** | From syntax errors to architecture refactoring |
65
- | **9 MCP Tools** | 3 core + 6 advanced analysis tools |
66
- | **Episode Tracking** | Full task lifecycle with status & metrics |
67
- | **Pagination** | Base64 offset tokens + sync tokens |
68
- | **Multi-User Ready** | User-scoped operations, role-based framework |
69
- | **Production Architecture** | FastAPI, SQLAlchemy, SQLite |
70
- | **Generic Tool Dispatch** | Scalable MCP handler pattern |
71
- | **Docker Ready** | Dockerfile + docker-compose.yml included |
72
- | **HF Integration** | Spaces-compatible, model inference ready |
73
- | **Comprehensive Docs** | Google Calendar API v3-style specs |
74
-
75
- ---
76
 
77
- ## Quick Start
 
 
 
 
78
 
79
- ### Via Docker (Recommended)
 
 
 
 
 
80
 
81
- ```bash
82
- # Clone repository
83
- git clone https://github.com/yourorg/debug-env
84
- cd debug-env
85
 
86
- # Build and run with Docker Compose
87
- docker-compose up --build
88
 
89
- # Server runs at http://localhost:8000
 
 
 
 
 
90
  ```
91
 
92
- ### Via Python (Local Development)
93
-
94
- ```bash
95
- # Prerequisites: Python 3.10+, uv package manager
96
- curl -LsSf https://astral.sh/uv/install.sh | sh
97
 
98
- # Clone and install
99
- git clone https://github.com/yourorg/debug-env
100
- cd debug-env
101
- uv sync
102
 
103
- # Initialize database
104
- python -c "from debug_env.server.database.db import init_db; init_db()"
105
 
106
- # Run server
107
- uv run server --port 8000
 
 
 
108
  ```
109
 
110
- ### Verify Installation
 
 
111
 
112
- ```bash
113
- # Check health endpoint
114
- curl http://localhost:8000/health
115
 
116
- # Response:
117
- # {"status":"healthy","service":"debug-env"}
118
- ```
119
 
120
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
- ## Installation
123
 
124
- ### Requirements
125
 
126
- - **Python**: 3.10 or higher
127
- - **Docker**: (optional) For containerized deployment
128
- - **Disk Space**: ~500MB (including dependencies)
129
- - **RAM**: 2GB minimum (4GB recommended)
130
 
131
- ### Option 1: Docker (Recommended for Deployment)
 
132
 
133
  ```bash
134
- docker build -t debug-env:latest .
135
- docker run -p 8000:8000 debug-env:latest
136
  ```
137
 
138
- ### Option 2: Local Development
139
 
140
  ```bash
141
- # Install uv (fast Python package manager)
142
- curl -LsSf https://astral.sh/uv/install.sh | sh
143
 
144
- # Create virtual environment and install
145
  uv sync
 
146
 
147
- # Initialize database
148
- uv run python -c "from debug_env.server.database.db import init_db; init_db()"
149
 
150
- # Run development server
151
- uv run server --reload
 
 
 
 
152
  ```
153
 
154
- ### Option 3: Hugging Face Spaces
155
 
156
- Click the "Duplicate" button on the [Hugging Face Space](https://huggingface.co/spaces/yourorg/debug-env) to deploy your own instance.
 
 
 
157
 
158
  ---
159
 
160
  ## Usage
161
 
162
- ### Web Interface
163
-
164
- Visit `http://localhost:8000` to access:
165
- - **Dashboard**: Environment state, reset/step UI
166
- - **Task Browser**: View all 9 tasks and their metadata
167
- - **Episode Tracker**: Track task runs and performance
168
-
169
- ### Python API (Client)
170
-
171
- ```python
172
- from debug_env import DebugEnvironment, DebugAction
173
-
174
- # Create environment
175
- env = DebugEnvironment()
176
-
177
- # Select task
178
- obs = env.reset(task="task1")
179
- print(f"Task: {env.current_task}")
180
- print(f"Workdir: {env.workdir}")
181
-
182
- # Read a file
183
- obs = env.step(DebugAction(tool="read_file", args={"path": "broken_code.py"}))
184
- print(obs.logs)
185
-
186
- # Edit the file
187
- obs = env.step(DebugAction(tool="edit_file", args={
188
- "path": "broken_code.py",
189
- "content": "fixed_code_here"
190
- }))
191
-
192
- print(f"Pass Rate: {obs.pass_rate}")
193
- print(f"Done: {obs.done}")
194
- print(f"Reward: {obs.reward}")
195
- ```
196
-
197
- ### MCP Interface (Claude, etc.)
198
 
199
  ```bash
200
- # Initialize connection
201
- curl -X POST http://localhost:8000/mcp \
202
- -H "Content-Type: application/json" \
203
- -d '{
204
- "jsonrpc": "2.0",
205
- "method": "initialize",
206
- "params": {"meta": {"task": "task1"}},
207
- "id": 1
208
- }'
209
-
210
- # List available tools
211
- curl -X POST http://localhost:8000/mcp \
212
- -H "Content-Type: application/json" \
213
- -d '{
214
- "jsonrpc": "2.0",
215
- "method": "tools/list",
216
- "id": 2
217
- }'
218
-
219
- # Call a tool (search_code)
220
- curl -X POST http://localhost:8000/mcp \
221
- -H "Content-Type: application/json" \
222
- -d '{
223
- "jsonrpc": "2.0",
224
- "method": "tools/call",
225
- "params": {
226
- "name": "search_code",
227
- "arguments": {"pattern": "def .*bug", "file_types": "py"}
228
- },
229
- "id": 3
230
- }'
231
  ```
232
 
233
- ### REST API (HTTP)
234
 
235
  ```bash
236
- # List tasks with pagination
237
- curl "http://localhost:8000/tasks?maxResults=5"
238
 
239
- # Get single task
240
- curl "http://localhost:8000/tasks/task1"
241
 
242
- # Create episode
243
- curl -X POST "http://localhost:8000/tasks/task1/episodes"
244
-
245
- # Update episode status
246
- curl -X PATCH "http://localhost:8000/tasks/task1/episodes/{episode_id}" \
247
- -H "Content-Type: application/json" \
248
- -d '{"status": "passed", "pass_rate": 1.0}'
249
  ```
250
 
251
- ---
252
-
253
- ## Architecture
254
 
255
- ### System Design
256
-
257
- ```
258
- β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
259
- β”‚ Client Layer β”‚
260
- β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
261
- β”‚ β”‚ Web UI β”‚ MCP Client β”‚ REST API β”‚ β”‚
262
- β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
263
- β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
264
- β”‚
265
- β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
266
- β”‚ FastAPI Server β”‚
267
- β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
268
- β”‚ β”‚ OpenEnv HTTP Server β”‚ β”‚
269
- β”‚ β”‚ POST /reset POST /step GET /state WS /ws β”‚ β”‚
270
- β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
271
- β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
272
- β”‚ β”‚ Core APIs β”‚ Task APIs β”‚ MCP Router β”‚ β”‚
273
- β”‚ β”‚ /health β”‚ /tasks β”‚ POST /mcp β”‚ β”‚
274
- β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
275
- β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
276
- β”‚ β”‚
277
- β”Œβ”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
278
- β”‚ DebugEnvironment β”‚ β”‚ Database Layer β”‚
279
- β”‚ β”œβ”€ reset(task) β”‚ β”‚ β”œβ”€ TaskManager β”‚
280
- β”‚ β”œβ”€ step(action) β”‚ β”‚ β”œβ”€ Models β”‚
281
- β”‚ └─ TaskLoader β”‚ β”‚ └─ Schemas β”‚
282
- β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
283
- β”‚ β”‚
284
- β”Œβ”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
285
- β”‚ Tool Execution β”‚ β”‚ SQLite DB β”‚
286
- β”‚ β”œβ”€ run_tests β”‚ β”‚ β”œβ”€ Tasks β”‚
287
- β”‚ β”œβ”€ read_file β”‚ β”‚ β”œβ”€ Episodes β”‚
288
- β”‚ β”œβ”€ edit_file β”‚ β”‚ └─ Channels β”‚
289
- β”‚ β”œβ”€ search_code β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
290
- β”‚ β”œβ”€ get_coverage β”‚
291
- β”‚ └─ (6 more) β”‚
292
- β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
293
- ```
294
 
295
- ### Directory Structure
 
 
296
 
297
- ```
298
- debug-env/
299
- β”œβ”€β”€ debug_env/
300
- β”‚ β”œβ”€β”€ __init__.py
301
- β”‚ β”œβ”€β”€ models.py # DebugAction, DebugObservation
302
- β”‚ β”œβ”€β”€ client.py # DebugEnv client class
303
- β”‚ β”‚
304
- β”‚ β”œβ”€β”€ server/
305
- β”‚ β”‚ β”œβ”€β”€ app.py # FastAPI app creation
306
- β”‚ β”‚ β”œβ”€β”€ debug_env_environment.py # Core DebugEnvironment
307
- β”‚ β”‚ β”œβ”€β”€ grader.py # Reward calculation
308
- β”‚ β”‚ β”‚
309
- β”‚ β”‚ β”œβ”€β”€ core/
310
- β”‚ β”‚ β”‚ └── apis.py # Health check endpoint
311
- β”‚ β”‚ β”‚
312
- β”‚ β”‚ β”œβ”€β”€ database/ # NEW: Database layer
313
- β”‚ β”‚ β”‚ β”œβ”€β”€ db.py # SQLAlchemy setup
314
- β”‚ β”‚ β”‚ β”œβ”€β”€ models/
315
- β”‚ β”‚ β”‚ β”‚ └── task.py # ORM models
316
- β”‚ β”‚ β”‚ └── managers/
317
- β”‚ β”‚ β”‚ └── task_manager.py # TaskManager class
318
- β”‚ β”‚ β”‚
319
- β”‚ β”‚ β”œβ”€β”€ handlers/
320
- β”‚ β”‚ β”‚ └── mcp_handler.py # MCP JSON-RPC dispatcher
321
- β”‚ β”‚ β”‚
322
- οΏ½οΏ½ β”‚ β”œβ”€β”€ mcp/
323
- β”‚ β”‚ β”‚ β”œβ”€β”€ router.py # MCP endpoint
324
- β”‚ β”‚ β”‚ └── tools/
325
- β”‚ β”‚ β”‚ └── debug_tools.py # Tool definitions
326
- β”‚ β”‚ β”‚
327
- β”‚ β”‚ β”œβ”€β”€ schemas/
328
- β”‚ β”‚ β”‚ β”œβ”€β”€ tool_schemas.py # Tool I/O schemas
329
- β”‚ β”‚ β”‚ └── task_schemas.py # Task/Episode schemas
330
- β”‚ β”‚ β”‚
331
- β”‚ β”‚ β”œβ”€β”€ tasks/
332
- β”‚ β”‚ β”‚ β”œβ”€β”€ data.py # Task registry
333
- β”‚ β”‚ β”‚ β”œβ”€β”€ loader.py # File staging
334
- β”‚ β”‚ β”‚ └── router.py # Task endpoints
335
- β”‚ β”‚ β”‚
336
- β”‚ β”‚ β”œβ”€β”€ tools/
337
- β”‚ β”‚ β”‚ β”œβ”€β”€ advanced_tools.py # 6 analysis tools
338
- β”‚ β”‚ β”‚ β”œβ”€β”€ tool_handlers.py # Generic dispatcher
339
- β”‚ β”‚ β”‚ β”œβ”€β”€ run_tests/
340
- β”‚ β”‚ β”‚ β”œβ”€β”€ read_file/
341
- β”‚ β”‚ β”‚ └── edit_file/
342
- β”‚ β”‚ β”‚
343
- β”‚ β”‚ └── utils/
344
- β”‚ β”‚ └── validation.py # Security checks
345
- β”‚ β”‚
346
- β”‚ β”œβ”€β”€ tasks/ # Task seed data
347
- β”‚ β”‚ β”œβ”€β”€ task1/ β†’ task9/ # 9 tasks
348
- β”‚ β”‚ └── [seed_data.py files]
349
- β”‚ β”‚
350
- β”‚ └── data/
351
- β”‚ └── multi_user_sample.py # User/role models
352
- β”‚
353
- β”œβ”€β”€ tests/ # Test suite
354
- β”‚ β”œβ”€β”€ test_tasks.py
355
- β”‚ β”œβ”€β”€ test_tools.py
356
- β”‚ └── test_database.py
357
- β”‚
358
- β”œβ”€β”€ Dockerfile # Container definition
359
- β”œβ”€β”€ docker-compose.yml # Multi-container setup
360
- β”œβ”€β”€ pyproject.toml # Dependencies
361
- β”œβ”€β”€ README.md # This file
362
- β”œβ”€β”€ LICENSE # BSD license
363
- └── debug_env.db # SQLite database (created)
364
  ```
365
 
366
  ---
367
 
368
- ## Deployment
369
-
370
- ### Docker
371
 
372
- #### Dockerfile
373
 
374
- ```dockerfile
375
- FROM python:3.11-slim
376
 
377
- WORKDIR /app
 
 
 
 
378
 
379
- # Install dependencies
380
- RUN apt-get update && apt-get install -y \
381
- gcc \
382
- && rm -rf /var/lib/apt/lists/*
383
 
384
- # Copy project
385
- COPY . .
386
-
387
- # Install Python dependencies
388
- RUN pip install --no-cache-dir -e .
389
-
390
- # Initialize database
391
- RUN python -c "from debug_env.server.database.db import init_db; init_db()"
392
-
393
- # Expose port
394
- EXPOSE 8000
395
-
396
- # Run server
397
- CMD ["python", "-m", "debug_env.server.app"]
398
  ```
399
-
400
- #### Docker Compose
401
-
402
- ```yaml
403
- version: '3.8'
404
-
405
- services:
406
- debug-env:
407
- build: .
408
- ports:
409
- - "8000:8000"
410
- volumes:
411
- - ./debug_env:/app/debug_env
412
- - ./debug_env.db:/app/debug_env.db
413
- environment:
414
- - PYTHONUNBUFFERED=1
415
- - LOG_LEVEL=INFO
416
- healthcheck:
417
- test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
418
- interval: 10s
419
- timeout: 5s
420
- retries: 3
421
-
422
- # Optional: Nginx reverse proxy
423
- nginx:
424
- image: nginx:latest
425
- ports:
426
- - "80:80"
427
- volumes:
428
- - ./nginx.conf:/etc/nginx/nginx.conf
429
- depends_on:
430
- - debug-env
431
  ```
432
 
433
- #### Build and Deploy
 
 
 
 
 
434
 
435
  ```bash
436
- # Build image
437
- docker build -t debug-env:v1.0.0 .
438
 
439
- # Run container
440
- docker run -p 8000:8000 \
441
- -v $(pwd)/debug_env.db:/app/debug_env.db \
442
- debug-env:v1.0.0
443
 
444
  # With Docker Compose
445
- docker-compose up -d
446
-
447
- # View logs
448
- docker-compose logs -f debug-env
449
  ```
450
 
451
- ### Hugging Face Spaces
452
-
453
- #### Setup
454
-
455
- 1. Go to [Hugging Face Spaces](https://huggingface.co/spaces)
456
- 2. Click **"Create new Space"**
457
- 3. Choose **"Docker"** as the SDK
458
- 4. Configure:
459
- - **Owner**: Your organization
460
- - **Space name**: `debug-env`
461
- - **Visibility**: Public (for demo) or Private (for testing)
462
- - **Persistent Storage**: Enable (for SQLite DB)
463
- - **Hardware**: CPU (free) or GPU
464
-
465
- #### Configuration
466
-
467
- Create `app_config.json`:
468
-
469
- ```json
470
- {
471
- "title": "Debug Env Benchmark",
472
- "description": "AI Debugging Benchmark",
473
- "emoji": "πŸ›",
474
- "colorFrom": "blue",
475
- "colorTo": "indigo",
476
- "sdk": "docker",
477
- "app_port": 8000,
478
- "base_path": "/web",
479
- "persistentStorage": {
480
- "enabled": true,
481
- "mountPath": "/app/data"
482
- },
483
- "tags": ["openenv", "debugging", "benchmark"]
484
- }
485
- ```
486
 
487
- #### Deploy
488
 
489
  ```bash
490
- # Push to Hugging Face
491
- git push https://huggingface.co/spaces/yourorg/debug-env main
492
-
493
- # Spaces automatically builds and deploys
494
- # Access at: https://yourorg-debug-env.hf.space
495
- ```
496
 
497
- #### Integration with HF Hub
 
498
 
499
- ```python
500
- from huggingface_hub import InferenceClient
 
501
 
502
- client = InferenceClient(
503
- model="yourorg/debug-env",
504
- token="hf_xxxxx"
505
- )
506
 
507
- # Make inference calls
508
- result = client.post(
509
- json={"task": "task1", "tool": "search_code", "pattern": "bug"}
510
- )
511
- ```
 
 
512
 
513
  ---
514
 
515
  ## API Reference
516
 
517
- ### REST Endpoints
518
-
519
- #### Health Check
520
- ```
521
- GET /health
522
- Response: {"status": "healthy", "service": "debug-env"}
523
- ```
524
-
525
- #### Task Management
526
 
527
  ```
528
- GET /tasks?maxResults=50&pageToken=<token>&syncToken=<token>
529
- Response: {
530
- "etag": "...",
531
- "items": [{id, title, description, files, tools, ...}],
532
- "nextPageToken": "...",
533
- "nextSyncToken": "..."
534
- }
535
-
536
- GET /tasks/{taskId}
537
- Response: {id, title, description, difficulty, bug_type, files, tools, ...}
538
-
539
- GET /tasks/{taskId}/files
540
- Response: ["broken_code.py", "helper.py"]
541
-
542
- GET /tasks/{taskId}/files/{filename}
543
- Response: {task_id, filename, content}
544
  ```
545
 
546
- #### Episode Management
547
 
548
  ```
549
- POST /tasks/{taskId}/episodes
550
- Response: {id, task_id, status: "active", workdir, etag, created_at, ...}
551
-
552
- GET /tasks/{taskId}/episodes?maxResults=50&pageToken=<token>
553
- Response: {items: [...], nextPageToken: "..."}
554
-
555
- GET /tasks/{taskId}/episodes/{episodeId}
556
- Response: {id, task_id, status, pass_rate, workdir, etag, ...}
557
-
558
- PATCH /tasks/{taskId}/episodes/{episodeId}
559
- Body: {status?: "passed"|"failed"|"abandoned", pass_rate?: 0.0-1.0}
560
- Response: {id, task_id, status, pass_rate, ...}
561
  ```
562
 
563
- ### MCP Tools
564
-
565
- #### Core Tools (3)
566
 
567
- **1. `run_tests`** β€” Execute pytest suite
568
- ```json
569
- {"name": "run_tests", "inputSchema": {"type": "object", "properties": {}}}
570
- ```
571
- Returns: `pass_rate` (0.0-1.0), `logs`, `reward`, `done`
572
-
573
- **2. `read_file`** β€” Read file from workdir
574
- ```json
575
- {
576
- "name": "read_file",
577
- "inputSchema": {
578
- "type": "object",
579
- "properties": {"path": {"type": "string"}},
580
- "required": ["path"]
581
- }
582
- }
583
- ```
584
- Returns: `logs` (file content), `success`
585
-
586
- **3. `edit_file`** β€” Write and test file
587
- ```json
588
- {
589
- "name": "edit_file",
590
- "inputSchema": {
591
- "type": "object",
592
- "properties": {
593
- "path": {"type": "string"},
594
- "content": {"type": "string"}
595
- },
596
- "required": ["path", "content"]
597
- }
598
- }
599
  ```
600
- Returns: `pass_rate`, `logs`, `reward`, `done`
601
-
602
- #### Advanced Tools (6)
603
-
604
- **4. `search_code`** β€” Pattern matching with ripgrep
605
- ```json
606
- {
607
- "name": "search_code",
608
- "inputSchema": {
609
- "properties": {
610
- "pattern": {"type": "string", "minLength": 1, "maxLength": 500},
611
- "file_types": {"enum": ["py", "all", "txt", "json", "md"]},
612
- "max_results": {"type": "integer", "minimum": 1, "maximum": 500}
613
- },
614
- "required": ["pattern"]
615
- }
616
- }
617
  ```
618
 
619
- **5. `get_file_structure`** β€” AST-based code structure
620
- **6. `run_type_check`** β€” Mypy static analysis
621
- **7. `get_test_coverage`** β€” Coverage.py metrics
622
- **8. `list_directory`** β€” Recursive directory listing
623
- **9. `get_dependencies`** β€” Import analysis
624
-
625
- ---
626
-
627
- ## Tasks
628
-
629
- | # | Task | Difficulty | Type | Description |
630
- |---|------|-----------|------|-------------|
631
- | 1 | Syntax Error | Easy | Bug Fix | Fix Python syntax preventing import |
632
- | 2 | Logic Error | Medium | Bug Fix | Fix boolean expression logic |
633
- | 3 | Multi-file Bug | Hard | Bug Fix | Fix bug across multiple modules |
634
- | 4 | Type Errors | Medium | Type Check | Fix mypy type annotation errors |
635
- | 5 | Code Quality | Medium | Cleanup | Remove unused imports/dead code |
636
- | 6 | Architecture | Hard | Refactoring | Multi-file refactoring with circular imports |
637
- | 7 | Code Review | Medium | Collab | Junior submits, senior reviews |
638
- | 8 | Bug Investigation | Hard | Collab | QA reports, team investigates |
639
- | 9 | Team Refactoring | Hard | Collab | Multi-user architecture fix |
640
-
641
  ---
642
 
643
- ## Database
644
-
645
- ### Schema
646
-
647
- **task_records** β€” Task metadata (seeded from registry)
648
- ```sql
649
- CREATE TABLE task_records (
650
- id TEXT PRIMARY KEY,
651
- title TEXT, description TEXT,
652
- difficulty TEXT, bug_type TEXT,
653
- files JSON, tools JSON,
654
- scenario_type TEXT, participants JSON,
655
- etag TEXT, created_at DATETIME, updated_at DATETIME
656
- )
657
- ```
658
-
659
- **episode_records** β€” Task runs (user episodes)
660
- ```sql
661
- CREATE TABLE episode_records (
662
- id TEXT PRIMARY KEY,
663
- task_id TEXT, user_id TEXT,
664
- workdir TEXT, status TEXT,
665
- pass_rate REAL,
666
- etag TEXT, created_at DATETIME, updated_at DATETIME
667
- )
668
- ```
669
-
670
- **watch_channels** β€” Webhook subscriptions
671
- ```sql
672
- CREATE TABLE watch_channels (
673
- id TEXT PRIMARY KEY,
674
- task_id TEXT, user_id TEXT,
675
- webhook_address TEXT, webhook_token TEXT,
676
- expires_at DATETIME, is_active BOOLEAN,
677
- created_at DATETIME
678
- )
679
  ```
680
 
681
  ---
682
 
683
- ## Development
684
 
685
- ### Testing
686
 
687
  ```bash
688
- # Run all tests
689
- pytest
 
690
 
691
- # With coverage
692
- pytest --cov=debug_env
693
 
694
- # Specific test file
695
- pytest tests/test_tasks.py -v
696
  ```
697
 
698
- ### Code Quality
699
-
700
- ```bash
701
- # Format with Black
702
- black debug_env tests
703
-
704
- # Lint with Ruff
705
- ruff check debug_env tests
706
-
707
- # Type check with Mypy
708
- mypy debug_env
709
- ```
710
-
711
- ### Adding Tasks
712
-
713
- 1. Create `debug_env/tasks/taskN/seed_data.py`
714
- 2. Register in `server/tasks/data.py`
715
- 3. Add to `server/tasks/loader.py`
716
- 4. Update `pyproject.toml`
717
-
718
- ### Adding Tools
719
 
720
- 1. Implement in `server/tools/advanced_tools.py`
721
- 2. Add spec to `server/mcp/tools/debug_tools.py`
722
- 3. Update `tool_handlers.py`
723
-
724
- ---
725
-
726
- ## Contributing
727
-
728
- 1. **Fork** the repository
729
- 2. **Create branch**: `git checkout -b feature/xyz`
730
- 3. **Make changes** with tests
731
- 4. **Run tests**: `pytest`
732
- 5. **Submit PR** with description
733
 
734
  ---
735
 
736
  ## License
737
 
738
- BSD 3-Clause License β€” See [LICENSE](LICENSE) file
739
-
740
- ---
741
-
742
- ## Citation
743
-
744
- ```bibtex
745
- @software{debug_env_2026,
746
- title={Debug Env: Production-Grade AI Debugging Benchmark},
747
- author={Your Organization},
748
- year={2026},
749
- url={https://github.com/yourorg/debug-env}
750
- }
751
- ```
752
-
753
- ---
754
-
755
- ## Links
756
-
757
- - **GitHub**: https://github.com/yourorg/debug-env
758
- - **OpenEnv**: https://github.com/meta-pytorch/OpenEnv
759
- - **Hugging Face**: https://huggingface.co/spaces/yourorg/debug-env
760
- - **Issues**: https://github.com/yourorg/debug-env/issues
761
-
762
- ---
763
-
764
- **Last Updated**: April 3, 2026
 
14
  - ai-agents
15
  ---
16
 
17
+ # debug-env β€” AI Code Debugging Benchmark
18
 
19
+ An [OpenEnv](https://github.com/meta-pytorch/OpenEnv) benchmark where LLM agents fix broken Python code.
20
+ Agents use four tools to diagnose and repair bugs across 9 tasks of increasing complexity.
21
+ Rewards are shaped on test pass rate (0.0–1.0) with efficiency bonuses.
22
 
23
+ **Live Space**: [vanshgoel1-debug-env.hf.space](https://vanshgoel1-debug-env.hf.space)
24
+ **GitHub**: [VanshGoel-1/debug-env](https://github.com/VanshGoel-1/debug-env)
25
 
26
  ---
27
 
28
+ ## Environment Description
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
+ Real-world code debugging is a core developer skill and a meaningful benchmark for LLM agents.
31
+ debug-env places agents inside an isolated working directory containing buggy Python code and
32
+ a pytest test suite. The agent must use tools to understand the code, identify the bug, and
33
+ write a corrected file β€” all within a fixed step budget.
34
 
35
+ The environment models genuine debugging scenarios: syntax errors, logic bugs, multi-file
36
+ issues, type errors, code quality problems, and collaborative refactoring tasks. These are
37
+ tasks developers do every day.
 
 
 
 
 
 
38
 
39
  ---
40
 
41
+ ## Action Space
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ ```python
44
+ class DebugAction(Action):
45
+ tool: str # one of: "list_files", "run_tests", "read_file", "edit_file"
46
+ args: dict # tool-specific arguments (see below)
47
+ ```
48
 
49
+ | Tool | Args | Description |
50
+ |------|------|-------------|
51
+ | `list_files` | `{}` | List all editable source files in the task workdir |
52
+ | `run_tests` | `{}` | Run pytest and return pass rate + full output |
53
+ | `read_file` | `{"path": "broken_code.py"}` | Read a source file |
54
+ | `edit_file` | `{"path": "broken_code.py", "content": "..."}` | Overwrite file, then run tests |
55
 
56
+ ---
 
 
 
57
 
58
+ ## Observation Space
 
59
 
60
+ ```python
61
+ class DebugObservation(Observation):
62
+ pass_rate: float # fraction of tests passing (0.0–1.0)
63
+ logs: str # test output, file content, or error message
64
+ reward: float # shaped reward for this step
65
+ done: bool # True when all tests pass (pass_rate == 1.0)
66
  ```
67
 
68
+ ---
 
 
 
 
69
 
70
+ ## Reward Function
 
 
 
71
 
72
+ Defined in `debug_env/server/grader.py`:
 
73
 
74
+ ```
75
+ reward = pass_rate
76
+ βˆ’ min(max(0, (steps βˆ’ 3) Γ— 0.01), 0.3) # step penalty after step 3
77
+ + 0.1 if pass_rate == 1.0 # completion bonus
78
+ + 0.2 Γ— max(0, 1 βˆ’ steps/max_steps) # efficiency bonus on full solve
79
  ```
80
 
81
+ - Partial credit for partial test passage (not sparse)
82
+ - Penalises thrashing (many steps without progress)
83
+ - Rewards solving quickly
84
 
85
+ ---
 
 
86
 
87
+ ## Tasks
 
 
88
 
89
+ | ID | Title | Difficulty | Type | Files |
90
+ |----|-------|-----------|------|-------|
91
+ | task1 | Fix Syntax Error | Easy | Bug fix | `broken_code.py` |
92
+ | task2 | Fix Logic Error | Medium | Bug fix | `broken_code.py` |
93
+ | task3 | Fix Multi-file Bug | Hard | Bug fix | `broken_code.py`, `helper.py` |
94
+ | task4 | Fix Type Errors | Medium | Type check | `typed_code.py` |
95
+ | task5 | Remove Dead Code | Medium | Code quality | `messy_code.py` |
96
+ | task6 | Architecture Refactor | Hard | Refactoring | 4 files |
97
+ | task7 | Code Review Workflow | Medium | Collaborative | `auth.py` |
98
+ | task8 | Cross-team Bug Investigation | Hard | Collaborative | 3 files |
99
+ | task9 | Collaborative Refactoring | Hard | Collaborative | 4 files |
100
+
101
+ Tasks 1–3 cover the mandatory competition range (easy β†’ medium β†’ hard).
102
+ Tasks 4–9 provide additional challenge for frontier models.
103
 
104
+ ---
105
 
106
+ ## Setup
107
 
108
+ ### Prerequisites
 
 
 
109
 
110
+ - Python 3.10+
111
+ - [uv](https://github.com/astral-sh/uv) package manager
112
 
113
  ```bash
114
+ curl -LsSf https://astral.sh/uv/install.sh | sh
 
115
  ```
116
 
117
+ ### Install
118
 
119
  ```bash
120
+ git clone https://github.com/VanshGoel-1/debug-env
121
+ cd debug-env
122
 
 
123
  uv sync
124
+ ```
125
 
126
+ ### Configure
 
127
 
128
+ ```bash
129
+ cp .env.example .env
130
+ # Edit .env and set:
131
+ # HF_TOKEN=hf_... (required)
132
+ # API_BASE_URL=https://router.huggingface.co/v1
133
+ # MODEL_NAME=Qwen/Qwen2.5-72B-Instruct
134
  ```
135
 
136
+ ### Verify
137
 
138
+ ```bash
139
+ python verify_setup.py
140
+ # Expected: 18 passed, 0 failed
141
+ ```
142
 
143
  ---
144
 
145
  ## Usage
146
 
147
+ ### Start the server
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
 
149
  ```bash
150
+ # Terminal 1
151
+ uv run server
152
+ # Server runs at http://localhost:8000
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  ```
154
 
155
+ ### Run the benchmark
156
 
157
  ```bash
158
+ # Terminal 2
159
+ python inference.py
160
 
161
+ # Run a specific task
162
+ TASK=task2 python inference.py
163
 
164
+ # Multiple runs for Pass@k
165
+ TASK=task1 NUMBER_OF_RUNS=3 python inference.py
 
 
 
 
 
166
  ```
167
 
168
+ ### Verify the server manually
 
 
169
 
170
+ ```bash
171
+ curl http://localhost:8000/health
172
+ # {"status":"healthy","service":"debug-env"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
173
 
174
+ curl -X POST http://localhost:8000/reset \
175
+ -H "Content-Type: application/json" \
176
+ -d '{"task": "task1"}'
177
 
178
+ curl -X POST http://localhost:8000/step \
179
+ -H "Content-Type: application/json" \
180
+ -d '{"action": {"tool": "list_files", "args": {}}}'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  ```
182
 
183
  ---
184
 
185
+ ## Inference Script
 
 
186
 
187
+ `inference.py` uses the OpenAI client against any OpenAI-compatible endpoint.
188
 
189
+ **Required environment variables:**
 
190
 
191
+ | Variable | Description |
192
+ |----------|-------------|
193
+ | `HF_TOKEN` | HuggingFace / API key |
194
+ | `API_BASE_URL` | LLM API endpoint (default: `https://router.huggingface.co/v1`) |
195
+ | `MODEL_NAME` | Model identifier (default: `Qwen/Qwen2.5-72B-Instruct`) |
196
 
197
+ **Competition stdout format:**
 
 
 
198
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
199
  ```
200
+ [START] task=task1 env=debug-env model=Qwen/Qwen2.5-72B-Instruct
201
+ [STEP] step=1 action=list_files() reward=0.00 done=false error=null
202
+ [STEP] step=2 action=run_tests() reward=0.00 done=false error=null
203
+ [STEP] step=3 action=read_file('broken_code.py') reward=0.00 done=false error=null
204
+ [STEP] step=4 action=edit_file('broken_code.py') reward=1.10 done=true error=null
205
+ [END] success=true steps=4 score=1.10 rewards=0.00,0.00,0.00,1.10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
206
  ```
207
 
208
+ Results are saved to `results_{task}_{timestamp}.json` with `pass@k`, `success_rate`,
209
+ `avg_steps`, and `avg_final_reward`.
210
+
211
+ ---
212
+
213
+ ## Docker
214
 
215
  ```bash
216
+ # Build
217
+ docker build -t debug-env .
218
 
219
+ # Run
220
+ docker run -p 8000:8000 debug-env
 
 
221
 
222
  # With Docker Compose
223
+ docker-compose up --build
 
 
 
224
  ```
225
 
226
+ The Dockerfile uses a two-stage build: dependencies are installed in the builder stage
227
+ (cache-friendly), source code is copied into the runtime stage. The CMD runs uvicorn
228
+ directly against `debug_env.server.app:app`.
229
+
230
+ ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
231
 
232
+ ## Deployment to Hugging Face Spaces
233
 
234
  ```bash
235
+ # Authenticate
236
+ huggingface-cli login
 
 
 
 
237
 
238
+ # Validate before pushing
239
+ openenv validate
240
 
241
+ # Push
242
+ openenv push --repo-id your-username/debug-env
243
+ ```
244
 
245
+ The `openenv.yaml` at repo root defines the Space configuration. After push, the Space
246
+ auto-builds from `Dockerfile` and exposes:
 
 
247
 
248
+ - `GET /health` β€” health check
249
+ - `POST /reset` β€” start episode
250
+ - `POST /step` β€” execute tool
251
+ - `GET /tasks` β€” list all tasks
252
+ - `POST /mcp` β€” MCP JSON-RPC interface
253
+ - `/web` β€” interactive web UI
254
+ - `/docs` β€” OpenAPI docs
255
 
256
  ---
257
 
258
  ## API Reference
259
 
260
+ ### Core endpoints
 
 
 
 
 
 
 
 
261
 
262
  ```
263
+ GET /health β†’ {"status":"healthy","service":"debug-env"}
264
+ POST /reset {"task":"task1"} β†’ initial observation
265
+ POST /step {"action":{"tool":...}} β†’ observation, reward, done
266
+ GET /state β†’ current episode state
267
+ WS /ws β†’ persistent session (low latency)
 
 
 
 
 
 
 
 
 
 
 
268
  ```
269
 
270
+ ### Task endpoints
271
 
272
  ```
273
+ GET /tasks β†’ paginated task list
274
+ GET /tasks/{taskId} β†’ task metadata
275
+ GET /tasks/{taskId}/files β†’ editable file list
276
+ POST /tasks/{taskId}/episodes β†’ create episode
277
+ GET /tasks/{taskId}/episodes/{id} β†’ get episode
278
+ PATCH /tasks/{taskId}/episodes/{id} β†’ update episode status
 
 
 
 
 
 
279
  ```
280
 
281
+ ### MCP endpoint
 
 
282
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
  ```
284
+ POST /mcp {"jsonrpc":"2.0","method":"initialize","params":{"meta":{"task":"task1"}},"id":1}
285
+ POST /mcp {"jsonrpc":"2.0","method":"tools/list","id":2}
286
+ POST /mcp {"jsonrpc":"2.0","method":"tools/call","params":{"name":"run_tests","arguments":{}},"id":3}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  ```
288
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
289
  ---
290
 
291
+ ## Project Structure
292
+
293
+ ```
294
+ debug-env/ ← repo root, all commands run here
295
+ β”œβ”€β”€ pyproject.toml ← single package definition
296
+ β”œβ”€β”€ uv.lock ← committed lock file
297
+ β”œβ”€β”€ Dockerfile ← single Dockerfile
298
+ β”œβ”€β”€ docker-compose.yml
299
+ β”œβ”€β”€ openenv.yaml ← OpenEnv spec
300
+ β”œβ”€β”€ inference.py ← competition entry point
301
+ β”œβ”€β”€ train.py ← RL training (GRPO)
302
+ β”œβ”€β”€ verify_setup.py
303
+ └── debug_env/
304
+ β”œβ”€β”€ models.py ← DebugAction, DebugObservation
305
+ β”œβ”€β”€ client.py ← DebugEnv HTTP/WS client
306
+ β”œβ”€β”€ server/
307
+ β”‚ β”œβ”€β”€ app.py ← FastAPI entry point
308
+ β”‚ β”œβ”€β”€ debug_env_environment.py
309
+ β”‚ β”œβ”€β”€ grader.py ← reward shaping
310
+ β”‚ β”œβ”€β”€ core/apis.py ← /health
311
+ β”‚ β”œβ”€β”€ database/ ← SQLAlchemy + SQLite
312
+ β”‚ β”œβ”€β”€ handlers/ ← MCP JSON-RPC dispatcher
313
+ β”‚ β”œβ”€β”€ mcp/ ← MCP router + tool specs
314
+ β”‚ β”œβ”€β”€ schemas/ ← Pydantic schemas
315
+ β”‚ β”œβ”€β”€ tasks/ ← registry, loader, API routes
316
+ β”‚ β”œβ”€β”€ tools/ ← run_tests, read_file, edit_file, list_files
317
+ β”‚ β”‚ + 6 advanced analysis tools
318
+ β”‚ └── utils/ ← path validation
319
+ β”œβ”€β”€ rl/
320
+ β”‚ β”œβ”€β”€ dataset.py ← curriculum dataset for GRPO
321
+ β”‚ └── rollout.py ← reward bridge for TRL
322
+ └── tasks/
323
+ β”œβ”€β”€ task1/ – task3/ ← static broken_code.py + test_code.py
324
+ └── task4/ – task9/ ← seed_data.py (generated at runtime)
 
 
325
  ```
326
 
327
  ---
328
 
329
+ ## RL Training (Optional)
330
 
331
+ GRPO training against the live environment using TRL + Unsloth:
332
 
333
  ```bash
334
+ uv sync --extra training
335
+ uv run server # Terminal 1 β€” environment must be running
336
+ python train.py # Terminal 2
337
 
338
+ # Smaller model for low VRAM:
339
+ MODEL=Qwen/Qwen2.5-1.5B-Instruct python train.py
340
 
341
+ # Easy tasks only (recommended starting point):
342
+ TASK_FILTER=easy python train.py
343
  ```
344
 
345
+ VRAM reference (Unsloth 4-bit QLoRA):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
346
 
347
+ | Model | Min VRAM |
348
+ |-------|---------|
349
+ | Qwen2.5-1.5B | ~2 GB |
350
+ | Qwen2.5-7B | ~6 GB |
351
+ | Qwen2.5-14B | ~10 GB |
 
 
 
 
 
 
 
 
352
 
353
  ---
354
 
355
  ## License
356
 
357
+ BSD 3-Clause β€” see [LICENSE](LICENSE)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
debug_env/README.md CHANGED
@@ -1,255 +1,33 @@
1
- ---
2
- title: Debug Env Environment Server
3
- emoji: 🎽
4
- colorFrom: green
5
- colorTo: yellow
6
- sdk: docker
7
- pinned: false
8
- app_port: 8000
9
- base_path: /web
10
- tags:
11
- - openenv
12
- ---
13
 
14
- # Debug Env Environment
15
 
16
- A simple test environment that echoes back messages. Perfect for testing the env APIs as well as demonstrating environment usage patterns.
17
 
18
- ## Quick Start
 
 
 
 
 
 
19
 
20
- The simplest way to use the Debug Env environment is through the `DebugEnv` class:
21
 
22
  ```python
23
- from debug_env import DebugAction, DebugEnv
 
24
 
25
- try:
26
- # Create environment from Docker image
27
- debug_envenv = DebugEnv.from_docker_image("debug_env-env:latest")
28
-
29
- # Reset
30
- result = debug_envenv.reset()
31
- print(f"Reset: {result.observation.echoed_message}")
32
-
33
- # Send multiple messages
34
- messages = ["Hello, World!", "Testing echo", "Final message"]
35
-
36
- for msg in messages:
37
- result = debug_envenv.step(DebugAction(message=msg))
38
- print(f"Sent: '{msg}'")
39
- print(f" β†’ Echoed: '{result.observation.echoed_message}'")
40
- print(f" β†’ Length: {result.observation.message_length}")
41
- print(f" β†’ Reward: {result.reward}")
42
-
43
- finally:
44
- # Always clean up
45
- debug_envenv.close()
46
  ```
47
 
48
- That's it! The `DebugEnv.from_docker_image()` method handles:
49
- - Starting the Docker container
50
- - Waiting for the server to be ready
51
- - Connecting to the environment
52
- - Container cleanup when you call `close()`
53
-
54
- ## Building the Docker Image
55
-
56
- Before using the environment, you need to build the Docker image:
57
 
58
  ```bash
59
- # From project root
60
- docker build -t debug_env-env:latest -f server/Dockerfile .
61
  ```
62
 
63
- ## Deploying to Hugging Face Spaces
64
-
65
- You can easily deploy your OpenEnv environment to Hugging Face Spaces using the `openenv push` command:
66
-
67
- ```bash
68
- # From the environment directory (where openenv.yaml is located)
69
- openenv push
70
-
71
- # Or specify options
72
- openenv push --namespace my-org --private
73
- ```
74
-
75
- The `openenv push` command will:
76
- 1. Validate that the directory is an OpenEnv environment (checks for `openenv.yaml`)
77
- 2. Prepare a custom build for Hugging Face Docker space (enables web interface)
78
- 3. Upload to Hugging Face (ensuring you're logged in)
79
-
80
- ### Prerequisites
81
-
82
- - Authenticate with Hugging Face: The command will prompt for login if not already authenticated
83
-
84
- ### Options
85
-
86
- - `--directory`, `-d`: Directory containing the OpenEnv environment (defaults to current directory)
87
- - `--repo-id`, `-r`: Repository ID in format 'username/repo-name' (defaults to 'username/env-name' from openenv.yaml)
88
- - `--base-image`, `-b`: Base Docker image to use (overrides Dockerfile FROM)
89
- - `--private`: Deploy the space as private (default: public)
90
-
91
- ### Examples
92
-
93
- ```bash
94
- # Push to your personal namespace (defaults to username/env-name from openenv.yaml)
95
- openenv push
96
-
97
- # Push to a specific repository
98
- openenv push --repo-id my-org/my-env
99
-
100
- # Push with a custom base image
101
- openenv push --base-image ghcr.io/meta-pytorch/openenv-base:latest
102
-
103
- # Push as a private space
104
- openenv push --private
105
-
106
- # Combine options
107
- openenv push --repo-id my-org/my-env --base-image custom-base:latest --private
108
- ```
109
-
110
- After deployment, your space will be available at:
111
- `https://huggingface.co/spaces/<repo-id>`
112
-
113
- The deployed space includes:
114
- - **Web Interface** at `/web` - Interactive UI for exploring the environment
115
- - **API Documentation** at `/docs` - Full OpenAPI/Swagger interface
116
- - **Health Check** at `/health` - Container health monitoring
117
- - **WebSocket** at `/ws` - Persistent session endpoint for low-latency interactions
118
-
119
- ## Environment Details
120
-
121
- ### Action
122
- **DebugAction**: Contains a single field
123
- - `message` (str) - The message to echo back
124
-
125
- ### Observation
126
- **DebugObservation**: Contains the echo response and metadata
127
- - `echoed_message` (str) - The message echoed back
128
- - `message_length` (int) - Length of the message
129
- - `reward` (float) - Reward based on message length (length Γ— 0.1)
130
- - `done` (bool) - Always False for echo environment
131
- - `metadata` (dict) - Additional info like step count
132
-
133
- ### Reward
134
- The reward is calculated as: `message_length Γ— 0.1`
135
- - "Hi" β†’ reward: 0.2
136
- - "Hello, World!" β†’ reward: 1.3
137
- - Empty message β†’ reward: 0.0
138
-
139
- ## Advanced Usage
140
-
141
- ### Connecting to an Existing Server
142
-
143
- If you already have a Debug Env environment server running, you can connect directly:
144
-
145
- ```python
146
- from debug_env import DebugEnv
147
-
148
- # Connect to existing server
149
- debug_envenv = DebugEnv(base_url="<ENV_HTTP_URL_HERE>")
150
-
151
- # Use as normal
152
- result = debug_envenv.reset()
153
- result = debug_envenv.step(DebugAction(message="Hello!"))
154
- ```
155
-
156
- Note: When connecting to an existing server, `debug_envenv.close()` will NOT stop the server.
157
-
158
- ### Using the Context Manager
159
-
160
- The client supports context manager usage for automatic connection management:
161
-
162
- ```python
163
- from debug_env import DebugAction, DebugEnv
164
-
165
- # Connect with context manager (auto-connects and closes)
166
- with DebugEnv(base_url="http://localhost:8000") as env:
167
- result = env.reset()
168
- print(f"Reset: {result.observation.echoed_message}")
169
- # Multiple steps with low latency
170
- for msg in ["Hello", "World", "!"]:
171
- result = env.step(DebugAction(message=msg))
172
- print(f"Echoed: {result.observation.echoed_message}")
173
- ```
174
-
175
- The client uses WebSocket connections for:
176
- - **Lower latency**: No HTTP connection overhead per request
177
- - **Persistent session**: Server maintains your environment state
178
- - **Efficient for episodes**: Better for many sequential steps
179
-
180
- ### Concurrent WebSocket Sessions
181
-
182
- The server supports multiple concurrent WebSocket connections. To enable this,
183
- modify `server/app.py` to use factory mode:
184
-
185
- ```python
186
- # In server/app.py - use factory mode for concurrent sessions
187
- app = create_app(
188
- DebugEnvironment, # Pass class, not instance
189
- DebugAction,
190
- DebugObservation,
191
- max_concurrent_envs=4, # Allow 4 concurrent sessions
192
- )
193
- ```
194
-
195
- Then multiple clients can connect simultaneously:
196
-
197
- ```python
198
- from debug_env import DebugAction, DebugEnv
199
- from concurrent.futures import ThreadPoolExecutor
200
-
201
- def run_episode(client_id: int):
202
- with DebugEnv(base_url="http://localhost:8000") as env:
203
- result = env.reset()
204
- for i in range(10):
205
- result = env.step(DebugAction(message=f"Client {client_id}, step {i}"))
206
- return client_id, result.observation.message_length
207
-
208
- # Run 4 episodes concurrently
209
- with ThreadPoolExecutor(max_workers=4) as executor:
210
- results = list(executor.map(run_episode, range(4)))
211
- ```
212
-
213
- ## Development & Testing
214
-
215
- ### Direct Environment Testing
216
-
217
- Test the environment logic directly without starting the HTTP server:
218
-
219
- ```bash
220
- # From the server directory
221
- python3 server/debug_env_environment.py
222
- ```
223
-
224
- This verifies that:
225
- - Environment resets correctly
226
- - Step executes actions properly
227
- - State tracking works
228
- - Rewards are calculated correctly
229
-
230
- ### Running Locally
231
-
232
- Run the server locally for development:
233
-
234
- ```bash
235
- uvicorn server.app:app --reload
236
- ```
237
-
238
- ## Project Structure
239
-
240
- ```
241
- debug_env/
242
- β”œβ”€β”€ .dockerignore # Docker build exclusions
243
- β”œβ”€β”€ __init__.py # Module exports
244
- β”œβ”€β”€ README.md # This file
245
- β”œβ”€β”€ openenv.yaml # OpenEnv manifest
246
- β”œβ”€β”€ pyproject.toml # Project metadata and dependencies
247
- β”œβ”€β”€ uv.lock # Locked dependencies (generated)
248
- β”œβ”€β”€ client.py # DebugEnv client
249
- β”œβ”€β”€ models.py # Action and Observation models
250
- └── server/
251
- β”œβ”€β”€ __init__.py # Server module exports
252
- β”œβ”€β”€ debug_env_environment.py # Core environment logic
253
- β”œβ”€β”€ app.py # FastAPI application (HTTP + WebSocket endpoints)
254
- └── Dockerfile # Container image definition
255
- ```
 
1
+ # debug_env β€” Python Package
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ This directory is the `debug_env` Python package. See the [root README](../README.md) for full documentation.
4
 
5
+ ## Package Contents
6
 
7
+ | Module | Description |
8
+ |--------|-------------|
9
+ | `models.py` | `DebugAction`, `DebugObservation` Pydantic models |
10
+ | `client.py` | `DebugEnv` HTTP/WebSocket client |
11
+ | `server/` | FastAPI server β€” the benchmark environment |
12
+ | `tasks/` | Task source files (task1–task9) |
13
+ | `rl/` | GRPO training utilities (dataset, rollout) |
14
 
15
+ ## Quick usage
16
 
17
  ```python
18
+ from debug_env import DebugAction, DebugObservation
19
+ from debug_env.client import DebugEnvClient
20
 
21
+ client = DebugEnvClient(base_url="http://localhost:8000")
22
+ obs = client.reset(task="task1")
23
+ result = client.step(DebugAction(tool="list_files", args={}))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  ```
25
 
26
+ ## Running the server
 
 
 
 
 
 
 
 
27
 
28
  ```bash
29
+ # From repo root
30
+ uv run server
31
  ```
32
 
33
+ Server exposes `GET /health`, `POST /reset`, `POST /step`, `GET /tasks`, `POST /mcp`, `/web`, `/docs`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
debug_env/client.py CHANGED
@@ -21,62 +21,40 @@ class DebugEnv(
21
  """
22
  Client for the Debug Env Environment.
23
 
24
- This client maintains a persistent WebSocket connection to the environment server,
25
  enabling efficient multi-step interactions with lower latency.
26
- Each client instance has its own dedicated environment session on the server.
27
 
28
  Example:
29
- >>> # Connect to a running server
30
  >>> with DebugEnv(base_url="http://localhost:8000") as client:
31
- ... result = client.reset()
32
- ... print(result.observation.echoed_message)
33
- ...
34
- ... result = client.step(DebugAction(message="Hello!"))
35
- ... print(result.observation.echoed_message)
36
 
37
  Example with Docker:
38
- >>> # Automatically start container and connect
39
  >>> client = DebugEnv.from_docker_image("debug_env-env:latest")
40
  >>> try:
41
- ... result = client.reset()
42
- ... result = client.step(DebugAction(message="Test"))
43
  ... finally:
44
  ... client.close()
45
  """
46
 
47
  def _step_payload(self, action: DebugAction) -> Dict:
48
- """
49
- Convert DebugAction to JSON payload for step message.
50
-
51
- Args:
52
- action: DebugAction instance
53
-
54
- Returns:
55
- Dictionary representation suitable for JSON encoding
56
- """
57
  return {
58
- "message": action.message,
 
59
  }
60
 
61
  def _parse_result(self, payload: Dict) -> StepResult[DebugObservation]:
62
- """
63
- Parse server response into StepResult[DebugObservation].
64
-
65
- Args:
66
- payload: JSON response data from server
67
-
68
- Returns:
69
- StepResult with DebugObservation
70
- """
71
  obs_data = payload.get("observation", {})
72
  observation = DebugObservation(
73
- echoed_message=obs_data.get("echoed_message", ""),
74
- message_length=obs_data.get("message_length", 0),
75
  done=payload.get("done", False),
76
  reward=payload.get("reward"),
77
- metadata=obs_data.get("metadata", {}),
78
  )
79
-
80
  return StepResult(
81
  observation=observation,
82
  reward=payload.get("reward"),
@@ -84,15 +62,7 @@ class DebugEnv(
84
  )
85
 
86
  def _parse_state(self, payload: Dict) -> State:
87
- """
88
- Parse server response into State object.
89
-
90
- Args:
91
- payload: JSON response from state request
92
-
93
- Returns:
94
- State object with episode_id and step_count
95
- """
96
  return State(
97
  episode_id=payload.get("episode_id"),
98
  step_count=payload.get("step_count", 0),
 
21
  """
22
  Client for the Debug Env Environment.
23
 
24
+ Maintains a persistent WebSocket connection to the environment server,
25
  enabling efficient multi-step interactions with lower latency.
 
26
 
27
  Example:
 
28
  >>> with DebugEnv(base_url="http://localhost:8000") as client:
29
+ ... client.reset(task="task1")
30
+ ... result = client.step(DebugAction(tool="run_tests", args={}))
31
+ ... print(result.observation.pass_rate)
 
 
32
 
33
  Example with Docker:
 
34
  >>> client = DebugEnv.from_docker_image("debug_env-env:latest")
35
  >>> try:
36
+ ... client.reset(task="task1")
37
+ ... result = client.step(DebugAction(tool="list_files", args={}))
38
  ... finally:
39
  ... client.close()
40
  """
41
 
42
  def _step_payload(self, action: DebugAction) -> Dict:
43
+ """Convert DebugAction to JSON payload for the step message."""
 
 
 
 
 
 
 
 
44
  return {
45
+ "tool": action.tool,
46
+ "args": action.args,
47
  }
48
 
49
  def _parse_result(self, payload: Dict) -> StepResult[DebugObservation]:
50
+ """Parse server response into StepResult[DebugObservation]."""
 
 
 
 
 
 
 
 
51
  obs_data = payload.get("observation", {})
52
  observation = DebugObservation(
53
+ pass_rate=obs_data.get("pass_rate", 0.0),
54
+ logs=obs_data.get("logs", ""),
55
  done=payload.get("done", False),
56
  reward=payload.get("reward"),
 
57
  )
 
58
  return StepResult(
59
  observation=observation,
60
  reward=payload.get("reward"),
 
62
  )
63
 
64
  def _parse_state(self, payload: Dict) -> State:
65
+ """Parse server response into State object."""
 
 
 
 
 
 
 
 
66
  return State(
67
  episode_id=payload.get("episode_id"),
68
  step_count=payload.get("step_count", 0),
debug_env/pyproject.toml DELETED
@@ -1,70 +0,0 @@
1
- # Copyright (c) Meta Platforms, Inc. and affiliates.
2
- # All rights reserved.
3
- #
4
- # This source code is licensed under the BSD-style license found in the
5
- # LICENSE file in the root directory of this source tree.
6
-
7
- [build-system]
8
- requires = ["setuptools>=45", "wheel"]
9
- build-backend = "setuptools.build_meta"
10
-
11
- [project]
12
- name = "openenv-debug_env"
13
- version = "0.1.0"
14
- description = "Debug Env environment for OpenEnv"
15
- requires-python = ">=3.10"
16
- dependencies = [
17
- # Core OpenEnv runtime (provides FastAPI server + HTTP client types)
18
- # install from github
19
- # "openenv-core[core] @ git+https://github.com/meta-pytorch/OpenEnv.git",
20
- "openenv-core[core]>=0.2.2",
21
- # Inference / benchmark client dependencies
22
- "httpx>=0.27.0",
23
- "langchain-core>=0.3.0",
24
- "langchain-anthropic>=0.3.0",
25
- "langchain-openai>=0.3.0",
26
- "langchain-google-genai>=2.0.0",
27
- # Database ORM for task persistence and episode tracking
28
- "sqlalchemy>=2.0.0",
29
- ]
30
-
31
- [project.optional-dependencies]
32
- dev = [
33
- "pytest>=8.0.0",
34
- "pytest-cov>=4.0.0",
35
- ]
36
-
37
- [project.scripts]
38
- # Server entry point - enables running via: uv run --project . server
39
- # or: python -m debug_env.server.app
40
- server = "debug_env.server.app:main"
41
-
42
- [tool.setuptools]
43
- include-package-data = true
44
- packages = [
45
- "debug_env",
46
- "debug_env.data",
47
- "debug_env.server",
48
- "debug_env.server.core",
49
- "debug_env.server.database",
50
- "debug_env.server.database.managers",
51
- "debug_env.server.database.models",
52
- "debug_env.server.handlers",
53
- "debug_env.server.mcp",
54
- "debug_env.server.mcp.tools",
55
- "debug_env.server.schemas",
56
- "debug_env.server.tools",
57
- "debug_env.server.tools.run_tests",
58
- "debug_env.server.tools.read_file",
59
- "debug_env.server.tools.edit_file",
60
- "debug_env.server.tasks",
61
- "debug_env.server.utils",
62
- "debug_env.tasks",
63
- "debug_env.tasks.task4",
64
- "debug_env.tasks.task5",
65
- "debug_env.tasks.task6",
66
- "debug_env.tasks.task7",
67
- "debug_env.tasks.task8",
68
- "debug_env.tasks.task9",
69
- ]
70
- package-dir = { "debug_env" = ".", "debug_env.server" = "server" }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
debug_env/rl/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .dataset import build_dataset
2
+ from .rollout import debug_reward, run_episode
3
+
4
+ __all__ = ["build_dataset", "debug_reward", "run_episode"]
debug_env/rl/dataset.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Curriculum dataset builder for GRPO training.
3
+
4
+ Converts TASK_REGISTRY into a HuggingFace Dataset ordered by difficulty
5
+ (easy β†’ medium β†’ hard). Each row is one prompt the model will be asked to complete.
6
+
7
+ Easy tasks are repeated more often so the model builds base competence first
8
+ (from Daniel's GPU Mode talk: "probability of good answer must be > 0").
9
+ """
10
+
11
+ from datasets import Dataset
12
+
13
+ from debug_env.server.tasks.data import TASK_REGISTRY
14
+
15
+ DIFFICULTY_ORDER = {"easy": 0, "medium": 1, "hard": 2}
16
+
17
+ PROMPT_TEMPLATE = """You are a Python debugging agent. Fix the broken code in the working directory.
18
+
19
+ Workflow:
20
+ 1. list_files β€” discover what files exist
21
+ 2. run_tests β€” see what is failing
22
+ 3. read_file(path) β€” read each relevant file
23
+ 4. edit_file(path, content) β€” write the complete corrected file
24
+ 5. run_tests β€” confirm all tests pass (reward=1.0)
25
+
26
+ Rules:
27
+ - Read ALL files before editing β€” bugs can span multiple files
28
+ - edit_file replaces the ENTIRE file β€” always provide complete content
29
+ - Do NOT stop until reward=1.0
30
+
31
+ Task: {task_id}
32
+ Difficulty: {difficulty}
33
+ Description: {description}
34
+
35
+ Begin with list_files."""
36
+
37
+
38
+ def build_dataset(repeat_easy: int = 10, repeat_medium: int = 6, repeat_hard: int = 3) -> Dataset:
39
+ """
40
+ Build curriculum-ordered dataset from TASK_REGISTRY.
41
+
42
+ Args:
43
+ repeat_easy: How many times to repeat each easy task row.
44
+ repeat_medium: How many times to repeat each medium task row.
45
+ repeat_hard: How many times to repeat each hard task row.
46
+
47
+ Returns:
48
+ HuggingFace Dataset with columns: prompt, task_id, difficulty.
49
+ """
50
+ rows = []
51
+ repeats = {"easy": repeat_easy, "medium": repeat_medium, "hard": repeat_hard}
52
+
53
+ for task_id, meta in sorted(
54
+ TASK_REGISTRY.items(),
55
+ key=lambda x: DIFFICULTY_ORDER.get(x[1].get("difficulty", "medium"), 1),
56
+ ):
57
+ difficulty = meta.get("difficulty", "medium")
58
+ n = repeats.get(difficulty, 4)
59
+ for _ in range(n):
60
+ rows.append(
61
+ {
62
+ "prompt": PROMPT_TEMPLATE.format(
63
+ task_id=task_id,
64
+ difficulty=difficulty,
65
+ description=meta.get("description", ""),
66
+ ),
67
+ "task_id": task_id,
68
+ "difficulty": difficulty,
69
+ }
70
+ )
71
+
72
+ return Dataset.from_list(rows)
debug_env/rl/rollout.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Episode executor β€” the bridge between TRL's GRPOTrainer and the debug-env server.
3
+
4
+ Takes a model-generated text completion, parses tool calls from it, executes
5
+ them against the running environment server, and returns a scalar reward.
6
+
7
+ The server must be running at ENV_URL before any rollout executes:
8
+ uv run server # or: uvicorn debug_env.server.app:app --port 8000
9
+ """
10
+
11
+ import asyncio
12
+ import json
13
+ import re
14
+
15
+ import httpx
16
+
17
+ from debug_env.server.grader import grade_with_steps
18
+
19
+ ENV_URL = "http://127.0.0.1:8000"
20
+ MAX_STEPS = 15
21
+ REQUEST_DELAY_S = 0.2 # 200 ms between steps to avoid overwhelming the server
22
+
23
+
24
+ # ── Tool-call parser ──────────────────────────────────────────────────────────
25
+
26
+ def parse_tool_calls(text: str) -> list[dict]:
27
+ """
28
+ Extract tool calls from model-generated text.
29
+
30
+ Handles two formats:
31
+
32
+ Format 1 β€” JSON blocks (preferred):
33
+ ```json
34
+ {"tool": "run_tests", "args": {}}
35
+ ```
36
+
37
+ Format 2 β€” Function-style (fallback):
38
+ list_files()
39
+ run_tests()
40
+ read_file("broken_code.py")
41
+ edit_file("broken_code.py", content) followed by a ```python ... ``` block
42
+
43
+ Returns:
44
+ List of {"tool": str, "args": dict} dicts, in order of appearance.
45
+ """
46
+ calls: list[dict] = []
47
+
48
+ # Format 1: JSON fenced blocks
49
+ for match in re.finditer(r"```(?:json)?\s*(\{[^`]+\})\s*```", text, re.DOTALL):
50
+ try:
51
+ obj = json.loads(match.group(1))
52
+ if "tool" in obj:
53
+ calls.append({"tool": obj["tool"], "args": obj.get("args", {})})
54
+ except json.JSONDecodeError:
55
+ pass
56
+
57
+ if calls:
58
+ return calls
59
+
60
+ # Format 2: Function-style (fallback for raw text completions)
61
+
62
+ # No-arg tools
63
+ for tool in ["list_files", "run_tests"]:
64
+ if f"{tool}(" in text:
65
+ calls.append({"tool": tool, "args": {}})
66
+
67
+ # read_file("path")
68
+ for m in re.finditer(r'read_file\(["\']([^"\']+)["\']\)', text):
69
+ calls.append({"tool": "read_file", "args": {"path": m.group(1)}})
70
+
71
+ # edit_file("path", ...) followed by a fenced code block
72
+ edit_match = re.search(
73
+ r'edit_file\(["\']([^"\']+)["\'].*?```(?:python)?\n([\s\S]+?)```',
74
+ text,
75
+ re.DOTALL,
76
+ )
77
+ if edit_match:
78
+ calls.append(
79
+ {
80
+ "tool": "edit_file",
81
+ "args": {"path": edit_match.group(1), "content": edit_match.group(2)},
82
+ }
83
+ )
84
+
85
+ return calls
86
+
87
+
88
+ # ── Episode runner ────────────────────────────────────────────────────────────
89
+
90
+ async def _run_episode(completion: str, task_id: str) -> float:
91
+ """
92
+ Run one full episode asynchronously:
93
+ 1. POST /reset to initialise the task
94
+ 2. Parse tool calls from the completion text
95
+ 3. POST /step for each tool call (up to MAX_STEPS)
96
+ 4. Return the shaped reward from grade_with_steps()
97
+
98
+ Returns 0.0 on any connectivity / parse failure so GRPO training
99
+ is never interrupted by transient server errors.
100
+ """
101
+ async with httpx.AsyncClient(timeout=60) as client:
102
+ try:
103
+ r = await client.post(f"{ENV_URL}/reset", json={"task": task_id})
104
+ r.raise_for_status()
105
+ except Exception:
106
+ return 0.0
107
+
108
+ tool_calls = parse_tool_calls(completion)
109
+ if not tool_calls:
110
+ return 0.0
111
+
112
+ step_count = 0
113
+ final_reward = 0.0
114
+
115
+ for call in tool_calls[:MAX_STEPS]:
116
+ step_count += 1
117
+ await asyncio.sleep(REQUEST_DELAY_S)
118
+ try:
119
+ r = await client.post(
120
+ f"{ENV_URL}/step",
121
+ json={"action": {"tool": call["tool"], "args": call["args"]}},
122
+ )
123
+ r.raise_for_status()
124
+ data = r.json()
125
+ pass_rate = (data.get("observation") or {}).get("pass_rate", 0.0)
126
+ final_reward = grade_with_steps(pass_rate, step_count)
127
+ if data.get("done", False):
128
+ break
129
+ except Exception:
130
+ break
131
+
132
+ return final_reward
133
+
134
+
135
+ def run_episode(completion: str, task_id: str) -> float:
136
+ """Synchronous wrapper around _run_episode β€” called from GRPOTrainer reward_funcs."""
137
+ return asyncio.run(_run_episode(completion, task_id))
138
+
139
+
140
+ # ── GRPOTrainer reward_funcs interface ────────────────────────────────────────
141
+
142
+ def debug_reward(completions: list[str], task_id: list[str], **kwargs) -> list[float]:
143
+ """
144
+ Reward function for TRL's GRPOTrainer.
145
+
146
+ GRPOTrainer calls this once per batch with:
147
+ completions β€” list of model-generated text strings (one per sample)
148
+ task_id β€” dataset column forwarded as a keyword list; one ID per sample
149
+
150
+ Returns:
151
+ List of float rewards in [0.0, 1.0], one per completion.
152
+ """
153
+ return [
154
+ run_episode(completion, tid)
155
+ for completion, tid in zip(completions, task_id)
156
+ ]
debug_env/server/Dockerfile DELETED
@@ -1,80 +0,0 @@
1
- # Copyright (c) Meta Platforms, Inc. and affiliates.
2
- # All rights reserved.
3
- #
4
- # This source code is licensed under the BSD-style license found in the
5
- # LICENSE file in the root directory of this source tree.
6
-
7
- # Multi-stage build using openenv-base
8
- # This Dockerfile is flexible and works for both:
9
- # - In-repo environments (with local OpenEnv sources)
10
- # - Standalone environments (with openenv from PyPI/Git)
11
- # The build script (openenv build) handles context detection and sets appropriate build args.
12
-
13
- ARG BASE_IMAGE=ghcr.io/meta-pytorch/openenv-base:latest
14
- FROM ${BASE_IMAGE} AS builder
15
-
16
- WORKDIR /app
17
-
18
- # Ensure git is available (required for installing dependencies from VCS)
19
- RUN apt-get update && \
20
- apt-get install -y --no-install-recommends git && \
21
- rm -rf /var/lib/apt/lists/*
22
-
23
- # Build argument to control whether we're building standalone or in-repo
24
- ARG BUILD_MODE=in-repo
25
- ARG ENV_NAME=debug_env
26
-
27
- # Copy environment code (always at root of build context)
28
- COPY . /app/env
29
-
30
- # For in-repo builds, openenv is already vendored in the build context
31
- # For standalone builds, openenv will be installed via pyproject.toml
32
- WORKDIR /app/env
33
-
34
- # Ensure uv is available (for local builds where base image lacks it)
35
- RUN if ! command -v uv >/dev/null 2>&1; then \
36
- curl -LsSf https://astral.sh/uv/install.sh | sh && \
37
- mv /root/.local/bin/uv /usr/local/bin/uv && \
38
- mv /root/.local/bin/uvx /usr/local/bin/uvx; \
39
- fi
40
-
41
- # Install dependencies using uv sync
42
- # If uv.lock exists, use it; otherwise resolve on the fly
43
- RUN --mount=type=cache,target=/root/.cache/uv \
44
- if [ -f uv.lock ]; then \
45
- uv sync --frozen --no-install-project --no-editable; \
46
- else \
47
- uv sync --no-install-project --no-editable; \
48
- fi
49
-
50
- RUN --mount=type=cache,target=/root/.cache/uv \
51
- if [ -f uv.lock ]; then \
52
- uv sync --frozen --no-editable; \
53
- else \
54
- uv sync --no-editable; \
55
- fi
56
-
57
- # Final runtime stage
58
- FROM ${BASE_IMAGE}
59
-
60
- WORKDIR /app
61
-
62
- # Copy the virtual environment from builder
63
- COPY --from=builder /app/env/.venv /app/.venv
64
-
65
- # Copy the environment code
66
- COPY --from=builder /app/env /app/env
67
-
68
- # Set PATH to use the virtual environment
69
- ENV PATH="/app/.venv/bin:$PATH"
70
-
71
- # Set PYTHONPATH so imports work correctly
72
- ENV PYTHONPATH="/app/env:$PYTHONPATH"
73
-
74
- # Health check
75
- HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
76
- CMD curl -f http://localhost:8000/health || exit 1
77
-
78
- # Run the FastAPI server
79
- # The module path is constructed to work with the /app/env structure
80
- CMD ["sh", "-c", "cd /app/env && uvicorn server.app:app --host 0.0.0.0 --port 8000"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
debug_env/server/app.py CHANGED
@@ -28,27 +28,14 @@ Usage:
28
  python -m server.app
29
  """
30
 
31
- try:
32
- from openenv.core.env_server.http_server import create_app
33
- except Exception as e: # pragma: no cover
34
- raise ImportError(
35
- "openenv is required for the web interface. Install dependencies with '\n uv sync\n'"
36
- ) from e
37
-
38
- try:
39
- from ..models import DebugAction, DebugObservation
40
- from .core.apis import router as core_router
41
- from .debug_env_environment import DebugEnvironment
42
- from .mcp.router import router as mcp_router
43
- from .tasks.router import router as tasks_router
44
- from .database.db import init_db
45
- except ModuleNotFoundError:
46
- from models import DebugAction, DebugObservation
47
- from server.core.apis import router as core_router
48
- from server.debug_env_environment import DebugEnvironment
49
- from server.mcp.router import router as mcp_router
50
- from server.tasks.router import router as tasks_router
51
- from server.database.db import init_db
52
 
53
 
54
  # Create the app with web interface and README integration
 
28
  python -m server.app
29
  """
30
 
31
+ from openenv.core.env_server.http_server import create_app
32
+
33
+ from debug_env.models import DebugAction, DebugObservation
34
+ from debug_env.server.core.apis import router as core_router
35
+ from debug_env.server.database.db import init_db
36
+ from debug_env.server.debug_env_environment import DebugEnvironment
37
+ from debug_env.server.mcp.router import router as mcp_router
38
+ from debug_env.server.tasks.router import router as tasks_router
 
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
 
41
  # Create the app with web interface and README integration
debug_env/server/debug_env_environment.py CHANGED
@@ -1,14 +1,15 @@
1
  import logging
 
2
  from uuid import uuid4
3
 
4
  from openenv.core.env_server.interfaces import Environment
5
  from openenv.core.env_server.types import State
6
 
7
  from debug_env.models import DebugAction, DebugObservation
8
- from debug_env.server.grader import grade
9
  from debug_env.server.schemas import ToolResult
10
  from debug_env.server.tasks import TaskLoader
11
- from debug_env.server.tools import edit_file, read_file, run_tests
12
 
13
  logger = logging.getLogger(__name__)
14
 
@@ -21,26 +22,49 @@ def _make_error_obs(message: str) -> DebugObservation:
21
  return obs
22
 
23
 
24
- def _obs_from_result(result: ToolResult) -> DebugObservation:
25
  """Convert a ToolResult into a DebugObservation with reward and done flag."""
26
  obs = DebugObservation(pass_rate=result.pass_rate, logs=result.logs)
27
- obs.reward = grade(result.pass_rate)
28
- obs.done = result.pass_rate == 1.0
29
  return obs
30
 
31
 
32
  class DebugEnvironment(Environment):
 
 
 
 
 
 
 
 
33
 
34
  def __init__(self):
35
- self._state = State(episode_id=str(uuid4()), step_count=0)
36
- self.current_task = "task1"
37
- self.workdir: str | None = None
 
 
 
 
38
 
39
  def reset(self, seed: int | None = None, episode_id: str | None = None, task: str | None = None, **kwargs) -> DebugObservation: # noqa: ARG002
40
  if task is not None:
41
  self.current_task = task
42
- self._state = State(episode_id=episode_id or str(uuid4()), step_count=0)
43
- self.workdir = TaskLoader.load(self.current_task, self.workdir)
 
 
 
 
 
 
 
 
 
 
 
44
  logger.info(f"Reset β€” task={self.current_task} workdir={self.workdir}")
45
  return DebugObservation(
46
  pass_rate=0.0,
@@ -65,7 +89,9 @@ class DebugEnvironment(Environment):
65
  # ── Core step ──────────────────────────────────────────────────────────────
66
 
67
  def step(self, action: DebugAction, timeout_s: float | None = None, **kwargs) -> DebugObservation: # noqa: ARG002
68
- self._state.step_count += 1
 
 
69
 
70
  if self.workdir is None:
71
  return _make_error_obs("Environment not initialised β€” call reset first.")
@@ -82,17 +108,19 @@ class DebugEnvironment(Environment):
82
  result = self._handle_read_file(self.workdir, args)
83
  elif tool == "edit_file":
84
  result = self._handle_edit_file(self.workdir, args)
 
 
85
  else:
86
  result = ToolResult(
87
  pass_rate=0.0,
88
- logs=f"Unknown tool: '{tool}'. Use 'run_tests', 'read_file', or 'edit_file'.",
89
  success=False,
90
  )
91
  except Exception as e:
92
  logger.error(f"Unexpected error in tool '{tool}': {e}", exc_info=True)
93
  return _make_error_obs(f"Internal error executing '{tool}'. Contact admin if issue persists.")
94
 
95
- return _obs_from_result(result)
96
 
97
  @property
98
  def state(self) -> State:
 
1
  import logging
2
+ from typing import ClassVar, Dict, Any
3
  from uuid import uuid4
4
 
5
  from openenv.core.env_server.interfaces import Environment
6
  from openenv.core.env_server.types import State
7
 
8
  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 edit_file, list_files, read_file, run_tests
13
 
14
  logger = logging.getLogger(__name__)
15
 
 
22
  return obs
23
 
24
 
25
+ def _obs_from_result(result: ToolResult, step_count: int) -> DebugObservation:
26
  """Convert a ToolResult into a DebugObservation with reward and done flag."""
27
  obs = DebugObservation(pass_rate=result.pass_rate, logs=result.logs)
28
+ obs.reward = grade_with_steps(result.pass_rate, step_count)
29
+ obs.done = result.pass_rate >= 0.99
30
  return obs
31
 
32
 
33
  class DebugEnvironment(Environment):
34
+ # Class-level shared state β€” persists across the fresh instances that the
35
+ # openenv HTTP server creates for every request (safe with max_concurrent_envs=1).
36
+ _shared: ClassVar[Dict[str, Any]] = {
37
+ "workdir": None,
38
+ "task": "task1",
39
+ "step_count": 0,
40
+ "episode_id": "",
41
+ }
42
 
43
  def __init__(self):
44
+ s = DebugEnvironment._shared
45
+ self._state = State(
46
+ episode_id=s["episode_id"] or str(uuid4()),
47
+ step_count=s["step_count"],
48
+ )
49
+ self.current_task: str = s["task"]
50
+ self.workdir: str | None = s["workdir"]
51
 
52
  def reset(self, seed: int | None = None, episode_id: str | None = None, task: str | None = None, **kwargs) -> DebugObservation: # noqa: ARG002
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 state so the next HTTP-request instance picks it up
61
+ DebugEnvironment._shared["task"] = self.current_task
62
+ DebugEnvironment._shared["workdir"] = self.workdir
63
+ DebugEnvironment._shared["step_count"] = 0
64
+ DebugEnvironment._shared["episode_id"] = new_episode_id
65
+
66
+ self._state = State(episode_id=new_episode_id, step_count=0)
67
+
68
  logger.info(f"Reset β€” task={self.current_task} workdir={self.workdir}")
69
  return DebugObservation(
70
  pass_rate=0.0,
 
89
  # ── Core step ──────────────────────────────────────────────────────────────
90
 
91
  def step(self, action: DebugAction, timeout_s: float | None = None, **kwargs) -> DebugObservation: # noqa: ARG002
92
+ # Increment and sync step count in shared state
93
+ DebugEnvironment._shared["step_count"] += 1
94
+ self._state.step_count = DebugEnvironment._shared["step_count"]
95
 
96
  if self.workdir is None:
97
  return _make_error_obs("Environment not initialised β€” call reset first.")
 
108
  result = self._handle_read_file(self.workdir, args)
109
  elif tool == "edit_file":
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=f"Unknown tool: '{tool}'. Use 'run_tests', 'read_file', 'edit_file', or 'list_files'.",
117
  success=False,
118
  )
119
  except Exception as e:
120
  logger.error(f"Unexpected error in tool '{tool}': {e}", exc_info=True)
121
  return _make_error_obs(f"Internal error executing '{tool}'. Contact admin if issue persists.")
122
 
123
+ return _obs_from_result(result, self._state.step_count)
124
 
125
  @property
126
  def state(self) -> State:
debug_env/server/grader.py CHANGED
@@ -1,3 +1,54 @@
1
  def grade(pass_rate: float) -> float:
2
- """Convert test pass rate to reward score in [0.0, 1.0]."""
3
  return float(pass_rate)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  def grade(pass_rate: float) -> float:
2
+ """Baseline reward β€” direct pass rate (used as fallback)."""
3
  return float(pass_rate)
4
+
5
+
6
+ def grade_by_comparison(submitted: str, reference: str) -> float:
7
+ """
8
+ Compare submitted code to reference line-by-line.
9
+ +10 for each matching line, -10 for each non-matching line.
10
+ Normalized to [0, 1] via (score + n*10) / (2*n*10).
11
+ """
12
+ sub_lines = submitted.splitlines()
13
+ ref_lines = reference.splitlines()
14
+ n = max(len(sub_lines), len(ref_lines))
15
+ if n == 0:
16
+ return 0.0
17
+
18
+ score = 0
19
+ for i in range(n):
20
+ sub_line = sub_lines[i] if i < len(sub_lines) else ""
21
+ ref_line = ref_lines[i] if i < len(ref_lines) else ""
22
+ score += 10 if sub_line == ref_line else -10
23
+
24
+ normalized = (score + n * 10) / (2 * n * 10)
25
+ return round(max(0.0, min(1.0, normalized)), 4)
26
+
27
+
28
+ def grade_with_steps(pass_rate: float, step_count: int, max_steps: int = 40) -> float:
29
+ """
30
+ Shaped reward that incentivises efficiency.
31
+
32
+ - Partial credit: linear pass_rate contribution
33
+ - Step penalty: -0.01 per step after the first 3 (discourages thrashing), capped at -0.3
34
+ - Completion bonus: +0.1 flat for reaching pass_rate == 1.0
35
+ - Efficiency bonus: up to +0.2 for solving early (only on full solve)
36
+ """
37
+ if pass_rate == 0.0:
38
+ return 0.0
39
+
40
+ base = float(pass_rate)
41
+
42
+ # Step penalty: starts after step 3, max -0.3
43
+ penalty = min(max(0.0, (step_count - 3) * 0.01), 0.3)
44
+
45
+ # Completion bonus
46
+ completion_bonus = 0.1 if pass_rate == 1.0 else 0.0
47
+
48
+ # Efficiency bonus: only on full solve, scales with how early
49
+ efficiency_bonus = 0.0
50
+ if pass_rate == 1.0 and max_steps > 0:
51
+ efficiency_bonus = 0.2 * max(0.0, 1.0 - step_count / max_steps)
52
+
53
+ reward = base - penalty + completion_bonus + efficiency_bonus
54
+ return round(min(max(reward, 0.0), 1.0), 4)
debug_env/server/requirements.txt DELETED
@@ -1,6 +0,0 @@
1
- openenv[core]>=0.2.0
2
- fastapi>=0.115.0
3
- uvicorn>=0.24.0
4
-
5
-
6
-
 
 
 
 
 
 
 
debug_env/server/tools/__init__.py CHANGED
@@ -1,5 +1,6 @@
1
  from .edit_file import edit_file
 
2
  from .read_file import read_file
3
  from .run_tests import run_tests
4
 
5
- __all__ = ["run_tests", "read_file", "edit_file"]
 
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__ = ["run_tests", "read_file", "edit_file", "list_files"]
debug_env/server/tools/edit_file/tool.py CHANGED
@@ -1,11 +1,17 @@
1
  """
2
- edit_file tool β€” validates the request, writes the file, then re-runs tests.
 
 
 
 
3
  """
4
 
5
  import logging
 
6
 
7
  from pydantic import ValidationError
8
 
 
9
  from debug_env.server.schemas import EditFileArgs, ToolResult
10
  from debug_env.server.tools.run_tests import run_tests
11
  from debug_env.server.utils import validate_workdir_path
@@ -15,7 +21,12 @@ logger = logging.getLogger(__name__)
15
 
16
  def edit_file(workdir: str, path: str, content: str) -> ToolResult:
17
  """
18
- Overwrite *path* (relative to *workdir*) with *content*, then run tests.
 
 
 
 
 
19
 
20
  Args:
21
  workdir: Absolute path to the task working directory.
@@ -44,10 +55,29 @@ def edit_file(workdir: str, path: str, content: str) -> ToolResult:
44
  try:
45
  with open(full_path, "w") as f:
46
  f.write(args.content)
47
- logger.info(f"File written ({len(args.content)} chars) β€” running tests")
48
  except OSError as e:
49
  msg = f"Failed to write '{args.path}': {e}"
50
  logger.error(msg)
51
  return ToolResult(pass_rate=0.0, logs=msg, success=False)
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  return run_tests(workdir)
 
1
  """
2
+ edit_file tool β€” validates the request, writes the file, then grades via comparison.
3
+
4
+ If a *_solution.py canonical reference exists in the workdir, we grade by
5
+ line-by-line comparison instead of running pytest (which is fragile in tmp dirs).
6
+ Falls back to run_tests when no solution file is present.
7
  """
8
 
9
  import logging
10
+ from pathlib import Path
11
 
12
  from pydantic import ValidationError
13
 
14
+ from debug_env.server.grader import grade_by_comparison
15
  from debug_env.server.schemas import EditFileArgs, ToolResult
16
  from debug_env.server.tools.run_tests import run_tests
17
  from debug_env.server.utils import validate_workdir_path
 
21
 
22
  def edit_file(workdir: str, path: str, content: str) -> ToolResult:
23
  """
24
+ Overwrite *path* (relative to *workdir*) with *content*, then grade.
25
+
26
+ Grading strategy:
27
+ 1. Look for ``{stem}_solution.py`` in the same workdir.
28
+ 2. If found β†’ compare submitted content to reference line-by-line.
29
+ 3. If not found β†’ fall back to running pytest via run_tests().
30
 
31
  Args:
32
  workdir: Absolute path to the task working directory.
 
55
  try:
56
  with open(full_path, "w") as f:
57
  f.write(args.content)
58
+ logger.info(f"File written ({len(args.content)} chars)")
59
  except OSError as e:
60
  msg = f"Failed to write '{args.path}': {e}"
61
  logger.error(msg)
62
  return ToolResult(pass_rate=0.0, logs=msg, success=False)
63
 
64
+ # ── Comparison-based grading ──────────────────────────────────────────────
65
+ stem = Path(args.path).stem
66
+ solution_path = Path(workdir) / f"{stem}_solution.py"
67
+
68
+ if solution_path.exists():
69
+ try:
70
+ reference = solution_path.read_text(encoding="utf-8")
71
+ pass_rate = grade_by_comparison(args.content, reference)
72
+ logger.info(f"Comparison grade for '{args.path}': {pass_rate:.4f}")
73
+ return ToolResult(
74
+ pass_rate=pass_rate,
75
+ logs=f"Graded '{args.path}' vs reference: pass_rate={pass_rate:.4f}",
76
+ success=True,
77
+ )
78
+ except OSError as e:
79
+ logger.warning(f"Could not read solution file '{solution_path}': {e} β€” falling back to tests")
80
+
81
+ # ── Fallback: run pytest ──────────────────────────────────────────────────
82
+ logger.info("No solution file found β€” running tests")
83
  return run_tests(workdir)
debug_env/server/tools/list_files/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .tool import list_files
2
+
3
+ __all__ = ["list_files"]
debug_env/server/tools/list_files/tool.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+ from debug_env.server.schemas import ToolResult
4
+
5
+
6
+ def list_files(workdir: str) -> ToolResult:
7
+ """Return the names of all editable source files in the workdir (excludes test files)."""
8
+ p = Path(workdir)
9
+ files = sorted(
10
+ f.name for f in p.iterdir()
11
+ if f.is_file()
12
+ and not f.name.startswith("test_")
13
+ and not f.stem.endswith("_solution")
14
+ )
15
+ listing = "\n".join(files) if files else "(no files found)"
16
+ return ToolResult(pass_rate=0.0, logs=f"Files in workdir:\n{listing}", success=True)
debug_env/tasks/task1/broken_code.py CHANGED
@@ -1,5 +1,6 @@
1
- def add(a, b):
2
  return a + b
3
 
 
4
  def multiply(a, b):
5
- return a * b
 
1
+ def add(a, b) # Bug: missing colon at end of function definition
2
  return a + b
3
 
4
+
5
  def multiply(a, b):
6
+ return a * b
debug_env/tasks/task1/broken_code_solution.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ def add(a, b):
2
+ return a + b
3
+
4
+
5
+ def multiply(a, b):
6
+ return a * b
debug_env/tasks/task2/broken_code_solution.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ def is_even(n):
2
+ return n % 2 == 0
3
+
4
+
5
+ def get_evens(numbers):
6
+ return [n for n in numbers if is_even(n)]
7
+
8
+
9
+ def sum_of_evens(numbers):
10
+ return sum(get_evens(numbers))
debug_env/tasks/task3/helper_solution.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ def clamp(value, min_val, max_val):
2
+ if value < min_val:
3
+ return min_val
4
+ if value > max_val:
5
+ return max_val
6
+ return value
docker-compose.yml CHANGED
@@ -2,27 +2,19 @@ version: '3.8'
2
 
3
  services:
4
  debug-env:
5
- build:
6
- context: ./debug_env
7
- dockerfile: ./server/Dockerfile
8
- args:
9
- BUILD_MODE: standalone
10
- ENV_NAME: debug_env
11
  ports:
12
- - "8000:8000"
13
  environment:
14
  - PYTHONUNBUFFERED=1
15
  - LOG_LEVEL=info
16
  healthcheck:
17
- test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
18
  interval: 30s
19
  timeout: 3s
20
  retries: 3
21
  start_period: 5s
22
  restart: unless-stopped
23
- volumes:
24
- # Optional: mount code for development
25
- - ./debug_env:/app/env:ro
26
  networks:
27
  - debug_env_network
28
 
 
2
 
3
  services:
4
  debug-env:
5
+ build: .
 
 
 
 
 
6
  ports:
7
+ - "8000:7860"
8
  environment:
9
  - PYTHONUNBUFFERED=1
10
  - LOG_LEVEL=info
11
  healthcheck:
12
+ test: ["CMD", "curl", "-f", "http://localhost:7860/health"]
13
  interval: 30s
14
  timeout: 3s
15
  retries: 3
16
  start_period: 5s
17
  restart: unless-stopped
 
 
 
18
  networks:
19
  - debug_env_network
20
 
inference.py CHANGED
@@ -2,37 +2,37 @@
2
  Debug-Env Benchmark Executor (Competition Version)
3
 
4
  Evaluates LLM agents on code debugging tasks via the OpenEnv server.
5
- Fully compliant with OpenEnv competition requirements.
6
 
7
  Usage:
8
- python inference.py # uses env vars
9
  TASK=task2 NUMBER_OF_RUNS=3 python inference.py
10
 
11
  Required Environment Variables:
12
- API_BASE_URL LLM API endpoint (e.g., https://api.openai.com/v1)
13
- MODEL_NAME Model identifier (e.g., gpt-4o-mini)
14
- OPENAI_API_KEY OpenAI API key
15
 
16
  Optional Environment Variables:
17
- ENV_URL OpenEnv server URL (default: http://127.0.0.1:8000)
18
- TASK task1 | task2 | task3 (default: task1)
19
- NUMBER_OF_RUNS how many runs for Pass@k (default: 3)
20
- MAX_STEPS max steps per run (default: 40)
21
- TEMPERATURE LLM temperature (default: 0.0)
22
- MAX_TOKENS max tokens per response (default: 4096)
23
- REQUEST_DELAY_MS delay between requests in ms (default: 500)
24
 
25
  Output:
26
  - Structured [START]/[STEP]/[END] logs to stdout
27
- - Results JSON file: results_{task}_{timestamp}.json
28
  """
29
 
30
  import asyncio
31
  import json
32
  import logging
33
  import os
 
34
  import sys
35
- import time
36
  from datetime import datetime, timezone
37
  from math import comb
38
  from typing import Any, Dict, List, Optional
@@ -42,137 +42,51 @@ from dotenv import load_dotenv
42
  load_dotenv()
43
 
44
  import httpx
45
- from openai import AsyncOpenAI, APIError, RateLimitError
46
 
47
  logging.basicConfig(
48
  level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
49
  )
50
  logger = logging.getLogger(__name__)
51
 
52
- # ── Tool definitions for function calling ──────────────────────────────────────
53
-
54
- TOOLS = [
55
- {
56
- "type": "function",
57
- "function": {
58
- "name": "run_tests",
59
- "description": (
60
- "Execute the pytest test suite against the current code. "
61
- "Returns pass rate and full test output logs."
62
- ),
63
- "parameters": {"type": "object", "properties": {}, "required": []},
64
- },
65
- },
66
- {
67
- "type": "function",
68
- "function": {
69
- "name": "read_file",
70
- "description": (
71
- "Read the current content of a source file in the task working directory. "
72
- "Use this to inspect broken code and helper files."
73
- ),
74
- "parameters": {
75
- "type": "object",
76
- "properties": {
77
- "path": {
78
- "type": "string",
79
- "description": "Filename to read (e.g. 'broken_code.py')",
80
- }
81
- },
82
- "required": ["path"],
83
- },
84
- },
85
- },
86
- {
87
- "type": "function",
88
- "function": {
89
- "name": "edit_file",
90
- "description": (
91
- "Overwrite a source file with corrected content and run tests. "
92
- "Always provide the complete file content (full replacement)."
93
- ),
94
- "parameters": {
95
- "type": "object",
96
- "properties": {
97
- "path": {
98
- "type": "string",
99
- "description": "Filename to edit (e.g. 'broken_code.py')",
100
- },
101
- "content": {
102
- "type": "string",
103
- "description": "Complete new file content (full file replacement)",
104
- },
105
- },
106
- "required": ["path", "content"],
107
- },
108
- },
109
- },
110
- ]
111
-
112
- SYSTEM_PROMPT = (
113
- "Fix broken Python code.\n\n"
114
- "Steps:\n"
115
- "1. run_tests - see errors\n"
116
- "2. read_file('broken_code.py') - see buggy code\n"
117
- "3. edit_file('broken_code.py') - fix it\n"
118
- "4. run_tests - verify\n\n"
119
- "Rules:\n"
120
- "- MUST call edit_file to fix (reading only = reward 0)\n"
121
- "- Always provide COMPLETE file in edit_file\n"
122
- "- Stop when all tests pass (reward = 1.0)"
123
- )
124
-
125
  # ── Configuration ───────────────────────────────────────────────────────────────
126
 
127
  CONFIG = {
128
- "env_url": os.getenv("ENV_URL", "http://127.0.0.1:8000"),
129
- "api_base_url": os.getenv("API_BASE_URL", "https://api.openai.com/v1"),
130
- "model_name": os.getenv("MODEL_NAME", "gpt-4o-mini"),
131
- "openai_api_key": os.getenv("OPENAI_API_KEY", ""),
132
- "task": os.getenv("TASK", "task1"),
133
- "number_of_runs": int(os.getenv("NUMBER_OF_RUNS", "1")), # Testing: 1 run
134
- "max_steps_per_run": int(os.getenv("MAX_STEPS", "10")), # Testing: 10 steps max
135
- "temperature": float(os.getenv("TEMPERATURE", "0.0")),
136
- "max_tokens": int(os.getenv("MAX_TOKENS", "1024")), # Testing: 1K tokens max
137
- "request_delay_ms": int(os.getenv("REQUEST_DELAY_MS", "500")),
138
  }
139
 
140
 
141
  def _validate_config(config: Dict[str, Any]) -> None:
142
- """Validate required environment variables."""
143
- if not config["openai_api_key"]:
144
- raise ValueError(
145
- "OPENAI_API_KEY environment variable is required. "
146
- "Set it via: export OPENAI_API_KEY=sk-..."
147
- )
148
  if not config["model_name"]:
149
- raise ValueError(
150
- "MODEL_NAME environment variable is required. "
151
- "Set it via: export MODEL_NAME=gpt-4o-mini"
152
- )
153
  if not config["api_base_url"]:
154
- raise ValueError(
155
- "API_BASE_URL environment variable is required. "
156
- "Set it via: export API_BASE_URL=https://api.openai.com/v1"
157
- )
158
-
159
 
160
- # ── OpenAI Client Setup ─────────────────────────────────────────────────────────
161
 
 
162
 
163
- async def _init_openai_client(config: Dict[str, Any]) -> AsyncOpenAI:
164
- """Initialize AsyncOpenAI client with proper configuration."""
165
- return AsyncOpenAI(
166
- api_key=config["openai_api_key"],
167
  base_url=config["api_base_url"],
168
  )
169
 
170
 
171
- # ── OpenEnv Environment Client ──────────────────────────────────────────────────
172
-
173
 
174
  async def env_reset(env_url: str, task: str) -> Dict[str, Any]:
175
- """Reset the environment to the initial state for a task."""
176
  async with httpx.AsyncClient(timeout=30) as client:
177
  r = await client.post(f"{env_url}/reset", json={"task": task})
178
  r.raise_for_status()
@@ -182,333 +96,325 @@ async def env_reset(env_url: str, task: str) -> Dict[str, Any]:
182
  async def env_step(
183
  env_url: str, tool: str, args: Dict[str, Any], delay_ms: int = 500
184
  ) -> Dict[str, Any]:
185
- """Execute a tool step with retry logic and rate limiting."""
186
  action = {"tool": tool, "args": args}
187
-
188
- # Rate limiting delay
189
  await asyncio.sleep(delay_ms / 1000.0)
190
 
191
- # Retry logic for transient errors
192
- max_retries = 3
193
- for attempt in range(max_retries):
194
  try:
195
  async with httpx.AsyncClient(timeout=60) as client:
196
  r = await client.post(f"{env_url}/step", json={"action": action})
197
  r.raise_for_status()
198
  return r.json()
199
  except httpx.HTTPStatusError as e:
200
- if e.response.status_code == 429: # Rate limited
201
- wait_time = 2**attempt # Exponential backoff: 1s, 2s, 4s
202
- logger.warning(
203
- f"Rate limited. Retrying in {wait_time}s (attempt {attempt+1}/{max_retries})"
204
- )
205
- await asyncio.sleep(wait_time)
206
  else:
207
  raise
208
  except Exception as e:
209
- if attempt == max_retries - 1:
210
  raise
211
- logger.warning(
212
- f"Request failed: {e}. Retrying (attempt {attempt+1}/{max_retries})"
213
- )
214
  await asyncio.sleep(1)
215
 
216
- raise RuntimeError(f"Failed to execute {tool} after {max_retries} retries")
 
217
 
 
218
 
219
- # ── Single Run Execution ────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
220
 
221
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
  async def execute_run(
223
  run_number: int,
224
- client: AsyncOpenAI,
225
  config: Dict[str, Any],
226
  ) -> Dict[str, Any]:
227
- """Execute a single run of the debugging task."""
228
- from copy import deepcopy
229
-
 
 
 
 
 
 
230
  env_url = config["env_url"]
231
- task = config["task"]
232
- max_steps = config["max_steps_per_run"]
233
- model = config["model_name"]
234
-
235
- # Structured logging: [START]
236
- print(f"[START] run={run_number} task={task} model={model}")
237
-
238
- # Reset environment
239
- reset_data = await env_reset(env_url, task)
240
- initial_logs = (reset_data.get("observation") or {}).get("logs", "")
241
-
242
- # Initialize message history
243
- messages = [
244
- {
245
- "role": "system",
246
- "content": SYSTEM_PROMPT,
247
- },
248
- {
249
- "role": "user",
250
- "content": (
251
- f"Task: {task}\n\n"
252
- f"Tests:\n{initial_logs}\n\n"
253
- f"Fix broken_code.py. Start with run_tests."
254
- ),
255
- },
256
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
257
 
258
- rewards: List[float] = []
259
- tools_used: List[str] = []
260
- steps_detail: List[Dict] = []
261
- success = False
262
- start_ts = datetime.now(timezone.utc)
 
 
 
 
 
 
 
 
263
 
264
- for step in range(1, max_steps + 1):
265
  try:
266
- # LLM call with function calling
267
- response = await client.chat.completions.create(
268
  model=model,
269
- messages=messages,
270
- tools=TOOLS,
271
- tool_choice="auto",
272
  temperature=config["temperature"],
273
  max_tokens=config["max_tokens"],
274
  )
 
 
 
 
275
 
276
- # Check if LLM finished without tool calls
277
- assistant_message = response.choices[0].message
278
- has_tool_calls = hasattr(assistant_message, 'tool_calls') and assistant_message.tool_calls
279
-
280
- # Debug: Log what tools the model is trying to call
281
- if has_tool_calls:
282
- tool_names = [tc.function.name for tc in assistant_message.tool_calls]
283
- logger.debug(f"Model trying to call: {tool_names}")
284
-
285
- if not has_tool_calls:
286
- logger.info("LLM finished reasoning without tool calls")
287
- break
288
-
289
- # Process tool calls
290
- messages.append({
291
- "role": "assistant",
292
- "content": assistant_message.content or "",
293
- "tool_calls": [
294
- {
295
- "id": tc.id,
296
- "type": "function",
297
- "function": {
298
- "name": tc.function.name,
299
- "arguments": tc.function.arguments,
300
- }
301
- }
302
- for tc in assistant_message.tool_calls
303
- ] if assistant_message.tool_calls else None
304
- })
305
 
306
- tool_results = []
307
- for tc in assistant_message.tool_calls:
308
- tool_name = tc.function.name
309
- tool_args = json.loads(tc.function.arguments)
310
-
311
- # Execute tool in environment
312
- res = await env_step(
313
- env_url,
314
- tool_name,
315
- tool_args,
316
- delay_ms=config["request_delay_ms"],
317
- )
318
- reward = res.get("reward", 0.0)
319
- done = res.get("done", False)
320
- logs = (res.get("observation") or {}).get("logs", "")
321
-
322
- rewards.append(reward)
323
- if tool_name not in tools_used:
324
- tools_used.append(tool_name)
325
-
326
- steps_detail.append(
327
- {
328
- "step": step,
329
- "tool": tool_name,
330
- "args": {
331
- k: v[:120] + "…"
332
- if isinstance(v, str) and len(v) > 120
333
- else v
334
- for k, v in tool_args.items()
335
- },
336
- "reward": reward,
337
- "done": done,
338
- }
339
- )
340
-
341
- # Structured logging: [STEP]
342
- print(
343
- f"[STEP] run={run_number} step={step} "
344
- f"tool={tool_name} reward={reward:.2f} done={done}"
345
- )
346
-
347
- # Add tool result to messages
348
- tool_results.append(
349
- {
350
- "role": "tool",
351
- "tool_call_id": tc.id,
352
- "content": f"reward={reward}, done={done}\n\n{logs}",
353
- }
354
- )
355
-
356
- if done:
357
- success = True
358
- break
359
-
360
- # Add all tool results to messages
361
- messages.extend(tool_results)
362
-
363
- if success:
364
- break
365
 
366
- except (RateLimitError, APIError) as e:
367
- logger.error(f"OpenAI API error at step {step}: {e}")
368
- if step < max_steps:
369
- await asyncio.sleep(2)
370
- else:
371
- break
372
- except Exception as e:
373
- logger.error(f"Unexpected error at step {step}: {e}", exc_info=True)
374
- break
375
 
376
- elapsed_ms = int(
377
- (datetime.now(timezone.utc) - start_ts).total_seconds() * 1000
378
- )
379
  final_reward = rewards[-1] if rewards else 0.0
 
380
 
381
- # Structured logging: [END]
382
  print(
383
- f"[END] run={run_number} success={success} "
384
- f"steps={len(rewards)} final_reward={final_reward:.2f} elapsed_ms={elapsed_ms}"
385
  )
386
 
387
  return {
388
- "run_number": run_number,
389
- "success": success,
390
  "final_reward": final_reward,
391
- "rewards": rewards,
392
- "steps": steps_detail,
393
- "tools_used": tools_used,
394
- "elapsed_ms": elapsed_ms,
395
  }
396
 
397
 
398
- # ── Statistics Calculation ──────────────────────────────────────────────────────
399
-
400
 
401
  def calculate_statistics(runs: List[Dict[str, Any]]) -> Dict[str, Any]:
402
- """Calculate Pass@k and other metrics from run results."""
403
- total = len(runs)
404
- successes = [r for r in runs if r["success"]]
405
- n_success = len(successes)
406
 
407
- # Pass@k: probability that at least one of k runs succeeds
408
  pass_at = {}
409
  for k in range(1, total + 1):
410
  if total - n_success < k:
411
  pass_at[f"pass@{k}"] = 1.0
412
  else:
413
- pass_at[f"pass@{k}"] = (
414
- 1.0 - comb(total - n_success, k) / comb(total, k)
415
- )
416
-
417
- avg_steps = sum(len(r["rewards"]) for r in runs) / total if total else 0
418
- avg_final_reward = sum(r["final_reward"] for r in runs) / total if total else 0
419
- mean_time_ms = sum(r["elapsed_ms"] for r in runs) / total if total else 0
420
 
421
- # Tool usage across all runs
422
  tool_counts: Dict[str, int] = {}
423
  for r in runs:
424
  for t in r["tools_used"]:
425
  tool_counts[t] = tool_counts.get(t, 0) + 1
426
 
427
  return {
428
- "total_runs": total,
429
- "successful_runs": n_success,
430
- "success_rate": n_success / total if total else 0.0,
431
  **pass_at,
432
- "avg_steps_per_run": round(avg_steps, 2),
433
- "avg_final_reward": round(avg_final_reward, 4),
434
- "mean_elapsed_ms": round(mean_time_ms, 0),
435
- "tool_usage": tool_counts,
436
  }
437
 
438
 
439
- # ── Main ────────────────────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
440
 
441
 
 
 
442
  async def main(config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
443
- """Main benchmark execution."""
444
  if config is None:
445
  config = CONFIG
446
 
447
- # Validate configuration
448
  try:
449
  _validate_config(config)
450
  except ValueError as e:
451
  logger.error(f"Configuration error: {e}")
452
  sys.exit(1)
453
 
454
- task = config["task"]
455
  n_runs = config["number_of_runs"]
456
 
457
  logger.info("=" * 70)
458
- logger.info(f"DEBUG-ENV BENCHMARK - OPENAI COMPETITION VERSION")
459
- logger.info(
460
- f"task={task} model={config['model_name']} "
461
- f"runs={n_runs} max_steps={config['max_steps_per_run']}"
462
- )
463
  logger.info("=" * 70)
464
 
465
- # Initialize OpenAI client
466
- client = await _init_openai_client(config)
467
  all_runs: List[Dict[str, Any]] = []
 
 
468
 
469
- # Execute runs
470
  for run_number in range(1, n_runs + 1):
471
  try:
472
  result = await execute_run(run_number, client, config)
473
  all_runs.append(result)
474
  except Exception as e:
475
  logger.error(f"Run {run_number} failed: {e}", exc_info=True)
476
- all_runs.append(
477
- {
478
- "run_number": run_number,
479
- "success": False,
480
- "final_reward": 0.0,
481
- "rewards": [],
482
- "steps": [],
483
- "tools_used": [],
484
- "elapsed_ms": 0,
485
- "error": str(e),
486
- }
487
- )
488
-
489
- # Calculate statistics
490
- stats = calculate_statistics(all_runs)
491
 
492
- output = {
493
- "benchmark_config": {
494
- "task": task,
495
- "model": config["model_name"],
496
- "api_base_url": config["api_base_url"],
497
- "number_of_runs": n_runs,
498
- "max_steps_per_run": config["max_steps_per_run"],
499
- "temperature": config["temperature"],
500
- },
501
- "runs": all_runs,
502
- "statistics": stats,
503
- }
504
 
505
- # Save results to JSON file
506
- ts = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
507
- out_file = f"results_{task}_{ts}.json"
508
- with open(out_file, "w") as f:
509
- json.dump(output, f, indent=2, default=str)
510
 
511
- # Print summary
512
  print()
513
  print("=" * 70)
514
  print("BENCHMARK SUMMARY")
@@ -528,8 +434,11 @@ async def main(config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
528
  print(f"Results file: {out_file}")
529
  print("=" * 70)
530
 
531
- return output
532
 
533
 
534
  if __name__ == "__main__":
535
- asyncio.run(main())
 
 
 
 
2
  Debug-Env Benchmark Executor (Competition Version)
3
 
4
  Evaluates LLM agents on code debugging tasks via the OpenEnv server.
5
+ Uses the OpenAI client pointed at Hugging Face's OpenAI-compatible router.
6
 
7
  Usage:
8
+ python inference.py # task1, 1 run
9
  TASK=task2 NUMBER_OF_RUNS=3 python inference.py
10
 
11
  Required Environment Variables:
12
+ HF_TOKEN Hugging Face API key
13
+ API_BASE_URL LLM API endpoint (default: https://router.huggingface.co/v1)
14
+ MODEL_NAME Model identifier (default: Qwen/Qwen2.5-72B-Instruct)
15
 
16
  Optional Environment Variables:
17
+ ENV_URL OpenEnv server URL (default: http://127.0.0.1:8000)
18
+ TASK task1–task3 (default: task1)
19
+ NUMBER_OF_RUNS runs for Pass@k (default: 1)
20
+ MAX_STEPS max steps per run (default: 10)
21
+ TEMPERATURE LLM temperature (default: 0.0)
22
+ MAX_TOKENS max tokens per call (default: 2048)
23
+ REQUEST_DELAY_MS ms between requests (default: 500)
24
 
25
  Output:
26
  - Structured [START]/[STEP]/[END] logs to stdout
27
+ - results_{task}_{timestamp}.json (written after every run, not just at end)
28
  """
29
 
30
  import asyncio
31
  import json
32
  import logging
33
  import os
34
+ import re
35
  import sys
 
36
  from datetime import datetime, timezone
37
  from math import comb
38
  from typing import Any, Dict, List, Optional
 
42
  load_dotenv()
43
 
44
  import httpx
45
+ from openai import OpenAI, APIError, RateLimitError
46
 
47
  logging.basicConfig(
48
  level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
49
  )
50
  logger = logging.getLogger(__name__)
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  # ── Configuration ───────────────────────────────────────────────────────────────
53
 
54
  CONFIG = {
55
+ "env_url": os.getenv("ENV_URL", "http://localhost:7860"),
56
+ "api_base_url": os.getenv("API_BASE_URL", "https://router.huggingface.co/v1"),
57
+ "model_name": os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct"),
58
+ "hf_token": os.getenv("HF_TOKEN"),
59
+ "task": os.getenv("TASK", "task1"),
60
+ "number_of_runs": int(os.getenv("NUMBER_OF_RUNS", "1")),
61
+ "max_steps_per_run": int(os.getenv("MAX_STEPS", "10")),
62
+ "temperature": float(os.getenv("TEMPERATURE", "0.0")),
63
+ "max_tokens": int(os.getenv("MAX_TOKENS", "2048")),
64
+ "request_delay_ms": int(os.getenv("REQUEST_DELAY_MS", "500")),
65
  }
66
 
67
 
68
  def _validate_config(config: Dict[str, Any]) -> None:
69
+ if not config["hf_token"]:
70
+ raise ValueError("HF_TOKEN is required. Set it in .env or export HF_TOKEN=hf_...")
 
 
 
 
71
  if not config["model_name"]:
72
+ raise ValueError("MODEL_NAME is required.")
 
 
 
73
  if not config["api_base_url"]:
74
+ raise ValueError("API_BASE_URL is required.")
 
 
 
 
75
 
 
76
 
77
+ # ── LLM client (OpenAI SDK β†’ HuggingFace router) ────────────────────────────────
78
 
79
+ def _init_client(config: Dict[str, Any]) -> OpenAI:
80
+ """OpenAI client pointed at the HuggingFace OpenAI-compatible endpoint."""
81
+ return OpenAI(
82
+ api_key=config["hf_token"],
83
  base_url=config["api_base_url"],
84
  )
85
 
86
 
87
+ # ── OpenEnv HTTP helpers ─────────────────────────────────────────────────────────
 
88
 
89
  async def env_reset(env_url: str, task: str) -> Dict[str, Any]:
 
90
  async with httpx.AsyncClient(timeout=30) as client:
91
  r = await client.post(f"{env_url}/reset", json={"task": task})
92
  r.raise_for_status()
 
96
  async def env_step(
97
  env_url: str, tool: str, args: Dict[str, Any], delay_ms: int = 500
98
  ) -> Dict[str, Any]:
99
+ """Execute one tool step with rate-limiting delay and retry on transient errors."""
100
  action = {"tool": tool, "args": args}
 
 
101
  await asyncio.sleep(delay_ms / 1000.0)
102
 
103
+ for attempt in range(3):
 
 
104
  try:
105
  async with httpx.AsyncClient(timeout=60) as client:
106
  r = await client.post(f"{env_url}/step", json={"action": action})
107
  r.raise_for_status()
108
  return r.json()
109
  except httpx.HTTPStatusError as e:
110
+ if e.response.status_code == 429:
111
+ wait = 2 ** attempt
112
+ logger.warning(f"Rate limited β€” retrying in {wait}s")
113
+ await asyncio.sleep(wait)
 
 
114
  else:
115
  raise
116
  except Exception as e:
117
+ if attempt == 2:
118
  raise
119
+ logger.warning(f"Request failed: {e} β€” retrying")
 
 
120
  await asyncio.sleep(1)
121
 
122
+ raise RuntimeError(f"Failed to execute {tool} after 3 retries")
123
+
124
 
125
+ # ── Helpers ──────────────────────────────────────────────────────────────────────
126
 
127
+ def _log_step(step, tool_name, tool_args, reward, done, error=None):
128
+ """Emit competition-format [STEP] line."""
129
+ if tool_args:
130
+ args_str = ", ".join(
131
+ f"'{v}'" if isinstance(v, str) and len(v) <= 40
132
+ else f"'{v[:40]}...'" if isinstance(v, str)
133
+ else str(v)
134
+ for v in tool_args.values()
135
+ )
136
+ action_str = f"{tool_name}({args_str})"
137
+ else:
138
+ action_str = f"{tool_name}()"
139
+ print(f"[STEP] step={step} action={action_str} reward={reward:.2f} done={str(done).lower()} error={error or 'null'}")
140
+
141
+
142
+ def _parse_file_list(logs: str) -> List[str]:
143
+ """Extract .py filenames from list_files output."""
144
+ return [
145
+ line.strip() for line in logs.splitlines()
146
+ if line.strip().endswith(".py") and not line.strip().startswith("#")
147
+ ]
148
 
149
 
150
+ def _extract_code(raw: str) -> str:
151
+ """
152
+ Extract Python code from an LLM response.
153
+ Handles:
154
+ - Raw code (no fences)
155
+ - ```python ... ``` fences
156
+ - ``` ... ``` fences
157
+ Returns the cleaned code string.
158
+ """
159
+ raw = raw.strip()
160
+
161
+ # Try to extract from a code fence
162
+ fence_match = re.search(r'```(?:python)?\n(.*?)```', raw, re.DOTALL)
163
+ if fence_match:
164
+ return fence_match.group(1).strip()
165
+
166
+ # Strip leading/trailing fence markers if present without newline
167
+ if raw.startswith("```"):
168
+ lines = raw.split("\n")
169
+ # Remove first line (``` or ```python) and last ``` line
170
+ inner = lines[1:] if len(lines) > 1 else lines
171
+ if inner and inner[-1].strip() == "```":
172
+ inner = inner[:-1]
173
+ return "\n".join(inner).strip()
174
+
175
+ return raw
176
+
177
+
178
+ # ── Single run ───────────────────────────────────────────────────────────────────
179
+
180
  async def execute_run(
181
  run_number: int,
182
+ client: OpenAI,
183
  config: Dict[str, Any],
184
  ) -> Dict[str, Any]:
185
+ """
186
+ Single-shot debugging workflow per run:
187
+ 1. list_files β€” discover editable files (solution files hidden by server)
188
+ 2. run_tests β€” see initial failures
189
+ 3. read_file β€” read each source file
190
+ 4. LLM call β€” ask for fixed code (one call per file, raw Python output)
191
+ 5. edit_file β€” submit fix; server grades via line-by-line comparison
192
+ No retry loop β€” one shot per run.
193
+ """
194
  env_url = config["env_url"]
195
+ task = config["task"]
196
+ model = config["model_name"]
197
+
198
+ print(f"[START] task={task} env=debug-env model={model}")
199
+
200
+ rewards: List[float] = []
201
+ tools_used: List[str] = []
202
+ steps_detail: List[Dict] = []
203
+ success = False
204
+ global_step = 0
205
+ start_ts = datetime.now(timezone.utc)
206
+
207
+ def _record(tool_name, tool_args, reward, done):
208
+ nonlocal global_step, success
209
+ global_step += 1
210
+ rewards.append(reward)
211
+ if tool_name not in tools_used:
212
+ tools_used.append(tool_name)
213
+ steps_detail.append({
214
+ "step": global_step, "tool": tool_name,
215
+ "args": tool_args, "reward": reward, "done": done,
216
+ })
217
+ _log_step(global_step, tool_name, tool_args, reward, done)
218
+ if done:
219
+ success = True
220
+
221
+ async def _call(tool_name, tool_args=None):
222
+ return await env_step(env_url, tool_name, tool_args or {}, delay_ms=config["request_delay_ms"])
223
+
224
+ # ── Reset ──────────────────────────────────────────────────────────────────
225
+ await env_reset(env_url, task)
226
+
227
+ # ── Step 1: list_files ─────────────────────────────────────────────────────
228
+ res = await _call("list_files")
229
+ reward, done = res.get("reward", 0.0), res.get("done", False)
230
+ file_list_logs = (res.get("observation") or {}).get("logs", "")
231
+ _record("list_files", {}, reward, done)
232
+
233
+ files = _parse_file_list(file_list_logs)
234
+ if not files:
235
+ logger.warning("list_files returned no .py files β€” falling back to broken_code.py")
236
+ files = ["broken_code.py"]
237
+
238
+ # ── Step 2: run_tests (initial) ────────────────────────────────────────────
239
+ if not success:
240
+ res = await _call("run_tests")
241
+ reward, done = res.get("reward", 0.0), res.get("done", False)
242
+ test_logs = (res.get("observation") or {}).get("logs", "")
243
+ _record("run_tests", {}, reward, done)
244
+ else:
245
+ test_logs = ""
246
+
247
+ # ── Step 3: read every source file ────────────────────────────────────────
248
+ file_contents: Dict[str, str] = {}
249
+ for f in files:
250
+ if success:
251
+ break
252
+ res = await _call("read_file", {"path": f})
253
+ reward, done = res.get("reward", 0.0), res.get("done", False)
254
+ content = (res.get("observation") or {}).get("logs", "")
255
+ _record("read_file", {"path": f}, reward, done)
256
+ file_contents[f] = content
257
+
258
+ # ── Step 4+5: LLM fix β†’ edit_file (one shot per file) ────────────────────
259
+ for fname in files:
260
+ if success:
261
+ break
262
 
263
+ current_content = file_contents.get(fname, "(file not yet read)")
264
+ prompt = (
265
+ f"You are a Python bug fixer. Fix the file '{fname}'.\n\n"
266
+ f"Test failures:\n{test_logs}\n\n"
267
+ f"Current content of '{fname}':\n{current_content}\n\n"
268
+ f"Output ONLY the complete corrected Python code for '{fname}'.\n"
269
+ "Rules:\n"
270
+ "- Do NOT include any explanation or comments about the fix.\n"
271
+ "- Do NOT use markdown fences (no ``` markers).\n"
272
+ "- Write the FULL file content from the first line to the last.\n"
273
+ "- If the fix is a missing colon, add it. If it is wrong logic, correct it.\n"
274
+ "- Do NOT add a filename comment (e.g. # broken_code.py) at the top.\n"
275
+ )
276
 
 
277
  try:
278
+ response = client.chat.completions.create(
 
279
  model=model,
280
+ messages=[{"role": "user", "content": prompt}],
 
 
281
  temperature=config["temperature"],
282
  max_tokens=config["max_tokens"],
283
  )
284
+ raw = response.choices[0].message.content or ""
285
+ except (RateLimitError, APIError) as e:
286
+ logger.error(f"LLM error for '{fname}': {e}")
287
+ continue
288
 
289
+ logger.info(f"LLM raw response for '{fname}': {raw[:300]!r}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290
 
291
+ new_content = _extract_code(raw)
292
+ if not new_content:
293
+ logger.warning(f"LLM returned empty content for '{fname}' β€” skipping")
294
+ continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295
 
296
+ res = await _call("edit_file", {"path": fname, "content": new_content})
297
+ reward, done = res.get("reward", 0.0), res.get("done", False)
298
+ _record("edit_file", {"path": fname}, reward, done)
 
 
 
 
 
 
299
 
300
+ elapsed_ms = int((datetime.now(timezone.utc) - start_ts).total_seconds() * 1000)
 
 
301
  final_reward = rewards[-1] if rewards else 0.0
302
+ rewards_str = ",".join(f"{r:.2f}" for r in rewards)
303
 
 
304
  print(
305
+ f"[END] success={str(success).lower()} steps={global_step} "
306
+ f"score={final_reward:.2f} rewards={rewards_str}"
307
  )
308
 
309
  return {
310
+ "run_number": run_number,
311
+ "success": success,
312
  "final_reward": final_reward,
313
+ "rewards": rewards,
314
+ "steps": steps_detail,
315
+ "tools_used": tools_used,
316
+ "elapsed_ms": elapsed_ms,
317
  }
318
 
319
 
320
+ # ── Statistics ───────────────────────────────────────────────────────────────────
 
321
 
322
  def calculate_statistics(runs: List[Dict[str, Any]]) -> Dict[str, Any]:
323
+ total = len(runs)
324
+ n_success = sum(1 for r in runs if r["success"])
 
 
325
 
 
326
  pass_at = {}
327
  for k in range(1, total + 1):
328
  if total - n_success < k:
329
  pass_at[f"pass@{k}"] = 1.0
330
  else:
331
+ pass_at[f"pass@{k}"] = 1.0 - comb(total - n_success, k) / comb(total, k)
 
 
 
 
 
 
332
 
 
333
  tool_counts: Dict[str, int] = {}
334
  for r in runs:
335
  for t in r["tools_used"]:
336
  tool_counts[t] = tool_counts.get(t, 0) + 1
337
 
338
  return {
339
+ "total_runs": total,
340
+ "successful_runs": n_success,
341
+ "success_rate": n_success / total if total else 0.0,
342
  **pass_at,
343
+ "avg_steps_per_run": round(sum(len(r["rewards"]) for r in runs) / total if total else 0, 2),
344
+ "avg_final_reward": round(sum(r["final_reward"] for r in runs) / total if total else 0, 4),
345
+ "mean_elapsed_ms": round(sum(r["elapsed_ms"] for r in runs) / total if total else 0, 0),
346
+ "tool_usage": tool_counts,
347
  }
348
 
349
 
350
+ def _save_results(all_runs: List[Dict], config: Dict, out_file: str) -> None:
351
+ """Write partial or final results to JSON β€” called after every run."""
352
+ stats = calculate_statistics(all_runs)
353
+ output = {
354
+ "benchmark_config": {
355
+ "task": config["task"],
356
+ "model": config["model_name"],
357
+ "api_base_url": config["api_base_url"],
358
+ "number_of_runs": config["number_of_runs"],
359
+ "max_steps_per_run": config["max_steps_per_run"],
360
+ "temperature": config["temperature"],
361
+ },
362
+ "runs": all_runs,
363
+ "statistics": stats,
364
+ }
365
+ with open(out_file, "w") as f:
366
+ json.dump(output, f, indent=2, default=str)
367
 
368
 
369
+ # ── Main ─────────────────────────────────────────────────────────────────────────
370
+
371
  async def main(config: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
 
372
  if config is None:
373
  config = CONFIG
374
 
 
375
  try:
376
  _validate_config(config)
377
  except ValueError as e:
378
  logger.error(f"Configuration error: {e}")
379
  sys.exit(1)
380
 
381
+ task = config["task"]
382
  n_runs = config["number_of_runs"]
383
 
384
  logger.info("=" * 70)
385
+ logger.info("DEBUG-ENV BENCHMARK")
386
+ logger.info(f"task={task} model={config['model_name']} runs={n_runs} max_steps={config['max_steps_per_run']}")
387
+ logger.info(f"endpoint={config['api_base_url']}")
 
 
388
  logger.info("=" * 70)
389
 
390
+ client = _init_client(config)
 
391
  all_runs: List[Dict[str, Any]] = []
392
+ ts = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S")
393
+ out_file = f"results_{task}_{ts}.json"
394
 
 
395
  for run_number in range(1, n_runs + 1):
396
  try:
397
  result = await execute_run(run_number, client, config)
398
  all_runs.append(result)
399
  except Exception as e:
400
  logger.error(f"Run {run_number} failed: {e}", exc_info=True)
401
+ all_runs.append({
402
+ "run_number": run_number,
403
+ "success": False,
404
+ "final_reward": 0.0,
405
+ "rewards": [],
406
+ "steps": [],
407
+ "tools_used": [],
408
+ "elapsed_ms": 0,
409
+ "error": str(e),
410
+ })
 
 
 
 
 
411
 
412
+ # Save after every run so partial results are never lost
413
+ _save_results(all_runs, config, out_file)
414
+ logger.info(f"Results saved β†’ {out_file} (run {run_number}/{n_runs})")
 
 
 
 
 
 
 
 
 
415
 
416
+ stats = calculate_statistics(all_runs)
 
 
 
 
417
 
 
418
  print()
419
  print("=" * 70)
420
  print("BENCHMARK SUMMARY")
 
434
  print(f"Results file: {out_file}")
435
  print("=" * 70)
436
 
437
+ return {"benchmark_config": config, "runs": all_runs, "statistics": stats}
438
 
439
 
440
  if __name__ == "__main__":
441
+ try:
442
+ asyncio.run(main())
443
+ except KeyboardInterrupt:
444
+ logger.info("Interrupted β€” partial results already saved to disk.")
debug_env/openenv.yaml β†’ openenv.yaml RENAMED
@@ -2,12 +2,12 @@ spec_version: 1
2
  name: debug_env
3
  type: space
4
  runtime: fastapi
5
- app: server.app:app
6
  port: 8000
7
  description: >
8
  A real-world debugging environment where LLM agents fix broken Python code.
9
  Tasks range from simple syntax errors to complex logic bugs. Agents use
10
- read_file, edit_file, and run_tests tools to identify and fix issues.
11
  Rewards are based on test pass rate (0.0-1.0).
12
 
13
  author: Meta Platforms, Inc.
@@ -41,7 +41,7 @@ action_schema:
41
  properties:
42
  tool:
43
  type: string
44
- enum: ["run_tests", "read_file", "edit_file"]
45
  description: Name of the tool to execute
46
  args:
47
  type: object
@@ -91,9 +91,9 @@ performance_metrics:
91
 
92
  deployment:
93
  huggingface_space: true
94
- dockerfile: ./debug_env/server/Dockerfile
95
  docker_compose: ./docker-compose.yml
96
  health_check: /health
97
  max_runtime_minutes: 20
98
  min_vcpu: 2
99
- min_memory_gb: 8
 
2
  name: debug_env
3
  type: space
4
  runtime: fastapi
5
+ app: debug_env.server.app:app
6
  port: 8000
7
  description: >
8
  A real-world debugging environment where LLM agents fix broken Python code.
9
  Tasks range from simple syntax errors to complex logic bugs. Agents use
10
+ read_file, edit_file, list_files, and run_tests tools to identify and fix issues.
11
  Rewards are based on test pass rate (0.0-1.0).
12
 
13
  author: Meta Platforms, Inc.
 
41
  properties:
42
  tool:
43
  type: string
44
+ enum: ["run_tests", "read_file", "edit_file", "list_files"]
45
  description: Name of the tool to execute
46
  args:
47
  type: object
 
91
 
92
  deployment:
93
  huggingface_space: true
94
+ dockerfile: ./Dockerfile
95
  docker_compose: ./docker-compose.yml
96
  health_check: /health
97
  max_runtime_minutes: 20
98
  min_vcpu: 2
99
+ min_memory_gb: 8
pushignore.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Patterns excluded when running: openenv push --exclude pushignore.txt
2
+ # Syntax: one glob pattern per line, # = comment
3
+
4
+ # Moved planning/reference docs β€” not needed on HF Space
5
+ unnecessary/
6
+
7
+ # Runtime SQLite database β€” recreated fresh on startup
8
+ debug_env/server/debug_env.db
9
+
10
+ # Python cache (also covered by defaults, but explicit for clarity)
11
+ **/__pycache__/
12
+ **/*.pyc
pyproject.toml CHANGED
@@ -71,19 +71,23 @@ dev = [
71
  "black>=24.0.0",
72
  "ruff>=0.3.0",
73
  ]
 
 
 
 
 
 
 
 
 
74
 
75
  [project.scripts]
76
- # Server entry point - enables running via: python -m debug_env.server.app
77
  server = "debug_env.server.app:main"
78
 
79
- # Inference entry point
80
- inference = "inference:main"
81
-
82
  [tool.setuptools]
83
  include-package-data = true
84
 
85
  [tool.setuptools.packages.find]
86
- where = ["debug_env"]
87
  include = ["debug_env*"]
88
 
89
  [tool.black]
 
71
  "black>=24.0.0",
72
  "ruff>=0.3.0",
73
  ]
74
+ training = [
75
+ "trl>=0.12.0",
76
+ "datasets>=2.20.0",
77
+ "transformers>=4.45.0",
78
+ "peft>=0.13.0",
79
+ "accelerate>=0.34.0",
80
+ "torch>=2.4.0",
81
+ "unsloth",
82
+ ]
83
 
84
  [project.scripts]
 
85
  server = "debug_env.server.app:main"
86
 
 
 
 
87
  [tool.setuptools]
88
  include-package-data = true
89
 
90
  [tool.setuptools.packages.find]
 
91
  include = ["debug_env*"]
92
 
93
  [tool.black]
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ openenv-core[core]>=0.2.2
2
+ fastapi>=0.104.0
3
+ uvicorn[standard]>=0.24.0
4
+ httpx>=0.27.0
5
+ openai>=1.29.0
6
+ python-dotenv>=1.0.0
7
+ pydantic>=2.0.0
8
+ pytest>=8.0.0
server/__init__.py ADDED
File without changes
server/app.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Required by `openenv validate` / `openenv push`.
2
+ # All logic lives in debug_env/server/app.py.
3
+ from debug_env.server.app import app # noqa: F401
4
+ from debug_env.server.app import main as _main
5
+
6
+
7
+ def main():
8
+ _main()
9
+
10
+
11
+ if __name__ == "__main__":
12
+ main()
start.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+
4
+ uvicorn debug_env.server.app:app --host 0.0.0.0 --port 7860 &
5
+ sleep 3
6
+ python inference.py
train.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ RL Training: debug-env + TRL GRPOTrainer + Unsloth
3
+
4
+ Prerequisites:
5
+ pip install -e ".[training]"
6
+ pip install "unsloth[cu124-torch240] @ git+https://github.com/unslothai/unsloth.git"
7
+ # OR: pip install unsloth --torch-backend=auto
8
+
9
+ # Server must be running in a separate terminal:
10
+ uv run server
11
+
12
+ Usage:
13
+ python train.py # all tasks, curriculum order
14
+ TASK_FILTER=easy python train.py # only easy tasks (start here)
15
+ MODEL=Qwen/Qwen2.5-1.5B-Instruct python train.py # smaller model for low VRAM
16
+ TRAIN_STEPS=50 TASK_FILTER=easy python train.py # quick sanity check
17
+
18
+ Environment variables:
19
+ MODEL HuggingFace model ID (default: Qwen/Qwen2.5-7B-Instruct)
20
+ MAX_SEQ_LEN Max token length (default: 2048)
21
+ OUTPUT_DIR Where to save the trained model (default: debug-env-grpo)
22
+ TRAIN_STEPS Number of gradient steps (default: 600)
23
+ BATCH_SIZE Per-device train batch size (default: 1)
24
+ NUM_GEN GRPO group size β€” completions per prompt (default: 4)
25
+ LR Learning rate (default: 2e-4)
26
+ TASK_FILTER "easy" | "medium" | "hard" | unset (all tasks)
27
+
28
+ VRAM reference (Unsloth 4-bit QLoRA):
29
+ Qwen2.5-1.5B β†’ ~2 GB (any modern GPU)
30
+ Qwen2.5-7B β†’ ~6 GB (RTX 3060+)
31
+ Qwen2.5-14B β†’ ~10 GB (RTX 3080+)
32
+ """
33
+
34
+ import os
35
+
36
+ from trl import GRPOConfig, GRPOTrainer
37
+ from unsloth import FastLanguageModel
38
+
39
+ from debug_env.rl.dataset import build_dataset
40
+ from debug_env.rl.rollout import debug_reward
41
+
42
+ # ── Config ────────────────────────────────────────────────────────────────────
43
+
44
+ MODEL_NAME = os.getenv("MODEL", "Qwen/Qwen2.5-7B-Instruct")
45
+ MAX_SEQ_LEN = int(os.getenv("MAX_SEQ_LEN", "2048"))
46
+ OUTPUT_DIR = os.getenv("OUTPUT_DIR", "debug-env-grpo")
47
+ MAX_STEPS = int(os.getenv("TRAIN_STEPS", "600"))
48
+ BATCH_SIZE = int(os.getenv("BATCH_SIZE", "1"))
49
+ NUM_GENERATIONS = int(os.getenv("NUM_GEN", "4")) # GRPO group size
50
+ LR = float(os.getenv("LR", "2e-4"))
51
+ TASK_FILTER = os.getenv("TASK_FILTER") # "easy" | "medium" | "hard" | None
52
+
53
+ # ── Model ─────────────────────────────────────────────────────────────────────
54
+
55
+ model, tokenizer = FastLanguageModel.from_pretrained(
56
+ MODEL_NAME,
57
+ max_seq_length=MAX_SEQ_LEN,
58
+ load_in_4bit=True, # QLoRA β€” halves VRAM vs full precision
59
+ )
60
+
61
+ model = FastLanguageModel.get_peft_model(
62
+ model,
63
+ r=16,
64
+ target_modules=[
65
+ "q_proj", "v_proj", "k_proj", "o_proj",
66
+ "gate_proj", "up_proj", "down_proj",
67
+ ],
68
+ lora_alpha=16,
69
+ lora_dropout=0.0,
70
+ bias="none",
71
+ use_gradient_checkpointing="unsloth", # Unsloth's custom checkpointing (saves ~30% VRAM)
72
+ )
73
+
74
+ # ── Dataset ───────────────────────────────────────────────────────────────────
75
+
76
+ dataset = build_dataset()
77
+ if TASK_FILTER:
78
+ dataset = dataset.filter(lambda x: x["difficulty"] == TASK_FILTER)
79
+
80
+ print(f"Dataset: {len(dataset)} prompts")
81
+ print(f"Difficulty breakdown: {dataset.to_pandas()['difficulty'].value_counts().to_dict()}")
82
+
83
+ # ── Trainer ───────────────────────────────────────────────────────────────────
84
+
85
+ trainer = GRPOTrainer(
86
+ model=model,
87
+ reward_funcs=debug_reward, # calls debug-env server at http://127.0.0.1:8000
88
+ train_dataset=dataset,
89
+ args=GRPOConfig(
90
+ output_dir=OUTPUT_DIR,
91
+ max_steps=MAX_STEPS,
92
+ per_device_train_batch_size=BATCH_SIZE,
93
+ num_generations=NUM_GENERATIONS,
94
+ learning_rate=LR,
95
+ lr_scheduler_type="linear",
96
+ warmup_ratio=0.1,
97
+ logging_steps=10,
98
+ save_steps=100,
99
+ bf16=True,
100
+ report_to="none", # set to "wandb" if you have Weights & Biases configured
101
+ ),
102
+ )
103
+
104
+ trainer.train()
105
+
106
+ # ── Save ──────────────────────────────────────────────────────────────────────
107
+
108
+ model.save_pretrained(OUTPUT_DIR)
109
+ tokenizer.save_pretrained(OUTPUT_DIR)
110
+ print(f"Model saved to {OUTPUT_DIR}/")
111
+
112
+ # Push to HF Hub (optional β€” uncomment and set your username):
113
+ # model.push_to_hub("your-username/debug-env-grpo")
114
+ # tokenizer.push_to_hub("your-username/debug-env-grpo")
uv.lock ADDED
The diff for this file is too large to render. See raw diff
 
verify_setup.py CHANGED
@@ -63,7 +63,7 @@ def check_task_files() -> Tuple[bool, str]:
63
 
64
  def check_docker_file() -> Tuple[bool, str]:
65
  """Check Dockerfile exists and is readable."""
66
- dockerfile = "debug_env/server/Dockerfile"
67
  if Path(dockerfile).exists():
68
  try:
69
  with open(dockerfile) as f:
@@ -83,14 +83,13 @@ def main():
83
 
84
  # 1. File structure
85
  print("1. Checking file structure...")
86
- checks.append(check_file_exists("debug_env/openenv.yaml", "openenv.yaml"))
87
  checks.append(check_file_exists("inference.py", "inference.py (competition entry point)"))
88
  checks.append(check_file_exists(".env", ".env configuration"))
89
  checks.append(check_file_exists(".env.example", ".env.example template"))
90
  checks.append(check_file_exists("README.md", "README.md"))
91
- checks.append(check_file_exists("QUICKSTART.md", "QUICKSTART.md"))
92
- checks.append(check_file_exists("COMPETITION_CHECKLIST.md", "COMPETITION_CHECKLIST.md"))
93
  checks.append(check_file_exists("pyproject.toml", "pyproject.toml (root)"))
 
94
  checks.append(check_file_exists("docker-compose.yml", "docker-compose.yml"))
95
  checks.append(check_docker_file())
96
 
@@ -111,7 +110,7 @@ def main():
111
 
112
  # 5. Environment variables
113
  print("\n5. Checking environment configuration...")
114
- checks.append(check_env_var("OPENAI_API_KEY"))
115
  checks.append(check_env_var("API_BASE_URL"))
116
  checks.append(check_env_var("MODEL_NAME"))
117
 
@@ -137,18 +136,19 @@ def main():
137
  if failed == 0:
138
  print("[SUCCESS] All checks passed! Your setup is ready for competition.\n")
139
  print("Next steps:")
140
- print(" 1. Set OPENAI_API_KEY in .env with your actual API key")
141
- print(" 2. Run: python inference.py")
142
- print(" 3. Check results in results_task1_*.json")
143
- print(" 4. Deploy to Hugging Face Spaces")
 
144
  return 0
145
  else:
146
  print(f"[ERROR] {failed} checks failed. Please fix the issues above.\n")
147
  if failed >= 2:
148
  print("Start with:")
149
- print(" 1. pip install -e .")
150
  print(" 2. cp .env.example .env")
151
- print(" 3. Edit .env with your OPENAI_API_KEY")
152
  return 1
153
 
154
  if __name__ == "__main__":
 
63
 
64
  def check_docker_file() -> Tuple[bool, str]:
65
  """Check Dockerfile exists and is readable."""
66
+ dockerfile = "Dockerfile"
67
  if Path(dockerfile).exists():
68
  try:
69
  with open(dockerfile) as f:
 
83
 
84
  # 1. File structure
85
  print("1. Checking file structure...")
86
+ checks.append(check_file_exists("openenv.yaml", "openenv.yaml"))
87
  checks.append(check_file_exists("inference.py", "inference.py (competition entry point)"))
88
  checks.append(check_file_exists(".env", ".env configuration"))
89
  checks.append(check_file_exists(".env.example", ".env.example template"))
90
  checks.append(check_file_exists("README.md", "README.md"))
 
 
91
  checks.append(check_file_exists("pyproject.toml", "pyproject.toml (root)"))
92
+ checks.append(check_file_exists("uv.lock", "uv.lock (dependency lock file)"))
93
  checks.append(check_file_exists("docker-compose.yml", "docker-compose.yml"))
94
  checks.append(check_docker_file())
95
 
 
110
 
111
  # 5. Environment variables
112
  print("\n5. Checking environment configuration...")
113
+ checks.append(check_env_var("HF_TOKEN"))
114
  checks.append(check_env_var("API_BASE_URL"))
115
  checks.append(check_env_var("MODEL_NAME"))
116
 
 
136
  if failed == 0:
137
  print("[SUCCESS] All checks passed! Your setup is ready for competition.\n")
138
  print("Next steps:")
139
+ print(" 1. Ensure HF_TOKEN is set in .env")
140
+ print(" 2. Run: uv run server (Terminal 1)")
141
+ print(" 3. Run: python inference.py (Terminal 2)")
142
+ print(" 4. Check results in results_task1_*.json")
143
+ print(" 5. Deploy: openenv push --repo-id your-username/debug-env")
144
  return 0
145
  else:
146
  print(f"[ERROR] {failed} checks failed. Please fix the issues above.\n")
147
  if failed >= 2:
148
  print("Start with:")
149
+ print(" 1. uv sync")
150
  print(" 2. cp .env.example .env")
151
+ print(" 3. Edit .env with your HF_TOKEN")
152
  return 1
153
 
154
  if __name__ == "__main__":