Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse files- Dockerfile +12 -0
- README.md +295 -5
- inference.py +174 -0
- openenv.yaml +29 -0
- server/Dockerfile +12 -0
- server/env.py +195 -0
- server/graders.py +153 -0
- server/main.py +111 -0
- server/models.py +28 -0
- server/requirements.txt +3 -0
- server/tasks/__init__.py +14 -0
- server/tasks/__pycache__/__init__.cpython-314.pyc +0 -0
- server/tasks/__pycache__/task_easy.cpython-314.pyc +0 -0
- server/tasks/__pycache__/task_hard.cpython-314.pyc +0 -0
- server/tasks/__pycache__/task_medium.cpython-314.pyc +0 -0
- server/tasks/task_easy.py +58 -0
- server/tasks/task_hard.py +88 -0
- server/tasks/task_medium.py +73 -0
- test_env.py +277 -0
Dockerfile
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
COPY server/requirements.txt .
|
| 5 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 6 |
+
|
| 7 |
+
# Copy the remaining server files
|
| 8 |
+
COPY server/ .
|
| 9 |
+
|
| 10 |
+
# Expose port and run uvicorn
|
| 11 |
+
EXPOSE 7860
|
| 12 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
README.md
CHANGED
|
@@ -1,10 +1,300 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
colorTo: indigo
|
| 6 |
sdk: docker
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: OpenENV — SQL Query Debugging Environment
|
| 3 |
+
emoji: 🛠️
|
| 4 |
+
colorFrom: blue
|
| 5 |
colorTo: indigo
|
| 6 |
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
tags:
|
| 9 |
+
- openenv
|
| 10 |
+
- reinforcement-learning
|
| 11 |
+
- sql
|
| 12 |
+
- nlp
|
| 13 |
---
|
| 14 |
|
| 15 |
+
# OpenENV — SQL Query Debugging Environment
|
| 16 |
+
|
| 17 |
+
[](https://openenv.dev)
|
| 18 |
+
[](https://huggingface.co/spaces)
|
| 19 |
+
[](https://python.org)
|
| 20 |
+
|
| 21 |
+
An **OpenEnv-compliant reinforcement learning environment** where an AI agent learns to debug and fix broken SQL queries against an in-memory SQLite database. This simulates a real-world data analyst task performed daily by developers worldwide.
|
| 22 |
+
|
| 23 |
+
---
|
| 24 |
+
|
| 25 |
+
## Environment Description
|
| 26 |
+
|
| 27 |
+
The agent is given a scenario: a SQL query is broken (syntax error, wrong join, bad aggregate) and must be fixed. At each step, the agent submits a corrected SQL query. The environment executes it against a live SQLite database and returns:
|
| 28 |
+
|
| 29 |
+
- Whether the query executed without errors
|
| 30 |
+
- The actual output of the query (stringified rows)
|
| 31 |
+
- A reward score reflecting correctness progression
|
| 32 |
+
|
| 33 |
+
This is **dense reward** design — the agent receives partial credit for partial progress, encouraging systematic debugging rather than random guessing.
|
| 34 |
+
|
| 35 |
+
---
|
| 36 |
+
|
| 37 |
+
## Observation Space
|
| 38 |
+
|
| 39 |
+
| Field | Type | Description |
|
| 40 |
+
|--------------------|----------------|----------------------------------------------------|
|
| 41 |
+
| `schema_str` | `string` | CREATE TABLE definitions for the task's database |
|
| 42 |
+
| `task_description` | `string` | Natural language description of the desired result |
|
| 43 |
+
| `broken_query` | `string` | The original buggy SQL query (shown at reset) |
|
| 44 |
+
| `last_error` | `string\|null` | SQL error from the previous step, or null |
|
| 45 |
+
| `last_output` | `string\|null` | Stringified query output from last step, or null |
|
| 46 |
+
| `step_number` | `integer` | Current step within the episode (starts at 0) |
|
| 47 |
+
|
| 48 |
+
---
|
| 49 |
+
|
| 50 |
+
## Action Space
|
| 51 |
+
|
| 52 |
+
| Type | Description |
|
| 53 |
+
|----------|----------------------------------------------------|
|
| 54 |
+
| `text` | A SQL query string submitted by the agent as a fix |
|
| 55 |
+
|
| 56 |
+
**Action schema:**
|
| 57 |
+
```json
|
| 58 |
+
{ "query": "SELECT id, name FROM users WHERE active = 1;" }
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
---
|
| 62 |
+
|
| 63 |
+
## Tasks
|
| 64 |
+
|
| 65 |
+
### Task 1: `fix-syntax` — Easy
|
| 66 |
+
**Scenario:** A `SELECT` statement is missing a comma between column names.
|
| 67 |
+
|
| 68 |
+
```sql
|
| 69 |
+
-- Broken
|
| 70 |
+
SELECT id name FROM users WHERE active = 1;
|
| 71 |
+
|
| 72 |
+
-- Fixed
|
| 73 |
+
SELECT id, name FROM users WHERE active = 1;
|
| 74 |
+
```
|
| 75 |
+
|
| 76 |
+
**Grading:**
|
| 77 |
+
| Score | Condition |
|
| 78 |
+
|-------|-----------|
|
| 79 |
+
| `1.0` | Query runs AND output matches reference exactly |
|
| 80 |
+
| `0.5` | Query runs but output partially correct |
|
| 81 |
+
| `0.0` | Query fails with an error |
|
| 82 |
+
|
| 83 |
+
---
|
| 84 |
+
|
| 85 |
+
### Task 2: `fix-logic` — Medium
|
| 86 |
+
**Scenario:** `INNER JOIN` should be `LEFT JOIN`; date filter uses `>` instead of `>=`.
|
| 87 |
+
|
| 88 |
+
```sql
|
| 89 |
+
-- Broken
|
| 90 |
+
SELECT u.name, o.total
|
| 91 |
+
FROM users u
|
| 92 |
+
INNER JOIN orders o ON u.id = o.user_id
|
| 93 |
+
WHERE o.created_at > '2024-01-01';
|
| 94 |
+
|
| 95 |
+
-- Fixed
|
| 96 |
+
SELECT u.name, o.total
|
| 97 |
+
FROM users u
|
| 98 |
+
LEFT JOIN orders o ON u.id = o.user_id AND o.created_at >= '2024-01-01';
|
| 99 |
+
```
|
| 100 |
+
|
| 101 |
+
**Grading:**
|
| 102 |
+
| Score | Condition |
|
| 103 |
+
|-------|-----------|
|
| 104 |
+
| `1.0` | Both bugs fixed AND output matches |
|
| 105 |
+
| `0.6` | One of the two bugs fixed |
|
| 106 |
+
| `0.2` | Query runs but output is wrong |
|
| 107 |
+
| `0.0` | Query fails |
|
| 108 |
+
| `-0.1/error` | Penalty for each error step (capped at 0.0) |
|
| 109 |
+
|
| 110 |
+
---
|
| 111 |
+
|
| 112 |
+
### Task 3: `fix-and-optimize` — Hard
|
| 113 |
+
**Scenario:** Correlated subquery uses wrong alias (`e.dept` undefined inside subquery) + outer query missing `GROUP BY`.
|
| 114 |
+
|
| 115 |
+
```sql
|
| 116 |
+
-- Broken
|
| 117 |
+
SELECT dept, AVG(salary)
|
| 118 |
+
FROM employees
|
| 119 |
+
WHERE salary > (SELECT AVG(salary) FROM employees WHERE dept = e.dept);
|
| 120 |
+
|
| 121 |
+
-- Fixed (correlated subquery approach)
|
| 122 |
+
SELECT dept, AVG(salary)
|
| 123 |
+
FROM employees e
|
| 124 |
+
WHERE salary > (SELECT AVG(salary) FROM employees WHERE dept = e.dept)
|
| 125 |
+
GROUP BY dept;
|
| 126 |
+
|
| 127 |
+
-- Bonus: CTE approach (+0.05)
|
| 128 |
+
WITH dept_avgs AS (
|
| 129 |
+
SELECT dept, AVG(salary) AS dept_avg FROM employees GROUP BY dept
|
| 130 |
+
)
|
| 131 |
+
SELECT e.dept, AVG(e.salary)
|
| 132 |
+
FROM employees e JOIN dept_avgs d ON e.dept = d.dept
|
| 133 |
+
WHERE e.salary > d.dept_avg
|
| 134 |
+
GROUP BY e.dept;
|
| 135 |
+
```
|
| 136 |
+
|
| 137 |
+
**Grading:**
|
| 138 |
+
| Score | Condition |
|
| 139 |
+
|-------|-----------|
|
| 140 |
+
| `1.0` | Alias fixed + GROUP BY + output matches |
|
| 141 |
+
| `0.7` | Alias fixed + runs but no GROUP BY |
|
| 142 |
+
| `0.4` | Runs with partial output |
|
| 143 |
+
| `0.0` | Query fails |
|
| 144 |
+
| `+0.05` | Bonus for using a CTE (`WITH` clause) |
|
| 145 |
+
|
| 146 |
+
---
|
| 147 |
+
|
| 148 |
+
## Reward Function
|
| 149 |
+
|
| 150 |
+
Dense reward — partial credit given at every step:
|
| 151 |
+
|
| 152 |
+
```
|
| 153 |
+
reward = correctness_score × (1.0 - 0.05 × step_penalty_factor)
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
- `correctness_score` ∈ `[0.0, 1.0]` — from the task-specific grader
|
| 157 |
+
- `step_penalty_factor` = `max(0, step_number - 1)` — small discount per step to discourage thrashing
|
| 158 |
+
- Final episode score = reward at the step where `done=True`, or last reward if `max_steps` reached
|
| 159 |
+
|
| 160 |
+
---
|
| 161 |
+
|
| 162 |
+
## Setup & Usage
|
| 163 |
+
|
| 164 |
+
### Prerequisites
|
| 165 |
+
- Docker (for containerized deployment)
|
| 166 |
+
- Python 3.11+ (for local development)
|
| 167 |
+
|
| 168 |
+
### Local Development
|
| 169 |
+
|
| 170 |
+
```powershell
|
| 171 |
+
# Install dependencies
|
| 172 |
+
cd server
|
| 173 |
+
pip install -r requirements.txt
|
| 174 |
+
|
| 175 |
+
# Start the server
|
| 176 |
+
uvicorn main:app --host 0.0.0.0 --port 7860
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
### Docker Build & Run
|
| 180 |
+
|
| 181 |
+
```bash
|
| 182 |
+
# Build image
|
| 183 |
+
docker build server/ -t sql-debug-env
|
| 184 |
+
|
| 185 |
+
# Run
|
| 186 |
+
docker run -p 7860:7860 sql-debug-env
|
| 187 |
+
```
|
| 188 |
+
|
| 189 |
+
### Testing the API
|
| 190 |
+
|
| 191 |
+
```powershell
|
| 192 |
+
# Health check
|
| 193 |
+
Invoke-RestMethod -Uri http://localhost:7860/health
|
| 194 |
+
|
| 195 |
+
# Reset to easy task
|
| 196 |
+
Invoke-RestMethod -Method POST -Uri "http://localhost:7860/reset?task=fix-syntax"
|
| 197 |
+
|
| 198 |
+
# Submit a fix
|
| 199 |
+
$body = '{"query": "SELECT id, name FROM users WHERE active = 1"}'
|
| 200 |
+
Invoke-RestMethod -Method POST -Uri http://localhost:7860/step -Body $body -ContentType "application/json"
|
| 201 |
+
```
|
| 202 |
+
|
| 203 |
+
### API Reference
|
| 204 |
+
|
| 205 |
+
| Method | Path | Description |
|
| 206 |
+
|--------|--------------------|--------------------------------------------------|
|
| 207 |
+
| GET | `/health` | Returns `{"status": "ok"}` |
|
| 208 |
+
| POST | `/reset?task=<t>` | Reset env, returns initial `SQLObservation` |
|
| 209 |
+
| POST | `/step` | Body: `SQLAction`, returns `StepResult` |
|
| 210 |
+
| GET | `/state` | Returns current `SQLObservation` (no side effect)|
|
| 211 |
+
| GET | `/docs` | Interactive Swagger UI |
|
| 212 |
+
|
| 213 |
+
---
|
| 214 |
+
|
| 215 |
+
## Running inference.py
|
| 216 |
+
|
| 217 |
+
```powershell
|
| 218 |
+
# Required
|
| 219 |
+
$env:HF_TOKEN = "hf_your_token_here"
|
| 220 |
+
|
| 221 |
+
# Optional overrides
|
| 222 |
+
$env:API_BASE_URL = "https://router.huggingface.co/v1"
|
| 223 |
+
$env:MODEL_NAME = "Qwen/Qwen2.5-72B-Instruct"
|
| 224 |
+
$env:ENV_BASE_URL = "http://localhost:7860"
|
| 225 |
+
|
| 226 |
+
python inference.py
|
| 227 |
+
```
|
| 228 |
+
|
| 229 |
+
**Expected log format:**
|
| 230 |
+
```
|
| 231 |
+
[START fix-syntax]
|
| 232 |
+
[STEP 1 | reward=0.0000 | done=False]
|
| 233 |
+
[STEP 2 | reward=1.0000 | done=True]
|
| 234 |
+
[END fix-syntax | final_reward=1.0000]
|
| 235 |
+
```
|
| 236 |
+
|
| 237 |
+
### Required Environment Variables
|
| 238 |
+
|
| 239 |
+
| Variable | Description | Default |
|
| 240 |
+
|----------------|--------------------------|--------------------------------------|
|
| 241 |
+
| `HF_TOKEN` | Hugging Face API key | *(required)* |
|
| 242 |
+
| `API_BASE_URL` | LLM API endpoint | `https://router.huggingface.co/v1` |
|
| 243 |
+
| `MODEL_NAME` | Model identifier | `Qwen/Qwen2.5-72B-Instruct` |
|
| 244 |
+
| `ENV_BASE_URL` | OpenENV server base URL | `http://localhost:7860` |
|
| 245 |
+
|
| 246 |
+
---
|
| 247 |
+
|
| 248 |
+
## Baseline Scores
|
| 249 |
+
|
| 250 |
+
Scores obtained by running `inference.py` with `Qwen/Qwen2.5-72B-Instruct` via HF router:
|
| 251 |
+
|
| 252 |
+
| Task | Difficulty | Typical Score | Notes |
|
| 253 |
+
|-------------------|-----------|---------------|--------------------------------|
|
| 254 |
+
| `fix-syntax` | Easy | 0.90–1.00 | Usually solved in 1–2 steps |
|
| 255 |
+
| `fix-logic` | Medium | 0.50–0.80 | Left join insight required |
|
| 256 |
+
| `fix-and-optimize`| Hard | 0.40–0.70 | CTE approach yields bonus |
|
| 257 |
+
|
| 258 |
+
*Scores are stochastic; re-run to reproduce.*
|
| 259 |
+
|
| 260 |
+
---
|
| 261 |
+
|
| 262 |
+
## OpenEnv Validation
|
| 263 |
+
|
| 264 |
+
```bash
|
| 265 |
+
openenv validate .
|
| 266 |
+
```
|
| 267 |
+
|
| 268 |
+
Expected output:
|
| 269 |
+
```
|
| 270 |
+
✅ openenv.yaml found and valid
|
| 271 |
+
✅ /reset endpoint responds 200
|
| 272 |
+
✅ /step endpoint responds 200
|
| 273 |
+
✅ /state endpoint responds 200
|
| 274 |
+
✅ /health endpoint responds 200
|
| 275 |
+
✅ inference.py found at project root
|
| 276 |
+
```
|
| 277 |
+
|
| 278 |
+
---
|
| 279 |
+
|
| 280 |
+
## Project Structure
|
| 281 |
+
|
| 282 |
+
```
|
| 283 |
+
OpenENV/
|
| 284 |
+
├── server/
|
| 285 |
+
│ ├── Dockerfile
|
| 286 |
+
│ ├── requirements.txt
|
| 287 |
+
│ ├── main.py # FastAPI server
|
| 288 |
+
│ ├── env.py # Core environment logic
|
| 289 |
+
│ ├── graders.py # Per-task grader functions
|
| 290 |
+
│ ├── models.py # Pydantic models
|
| 291 |
+
│ └── tasks/
|
| 292 |
+
│ ├── __init__.py
|
| 293 |
+
│ ├── task_easy.py
|
| 294 |
+
│ ├── task_medium.py
|
| 295 |
+
│ └── task_hard.py
|
| 296 |
+
├── openenv.yaml # OpenEnv spec metadata
|
| 297 |
+
├── inference.py # Baseline inference script
|
| 298 |
+
├── README.md
|
| 299 |
+
└── project.md
|
| 300 |
+
```
|
inference.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
inference.py — Baseline inference script for OpenENV SQL Debugging environment.
|
| 3 |
+
|
| 4 |
+
Location: project root (mandatory per OpenEnv spec).
|
| 5 |
+
|
| 6 |
+
Usage:
|
| 7 |
+
export HF_TOKEN=hf_...
|
| 8 |
+
export API_BASE_URL=https://router.huggingface.co/v1 # optional
|
| 9 |
+
export MODEL_NAME=Qwen/Qwen2.5-72B-Instruct # optional
|
| 10 |
+
export ENV_BASE_URL=http://localhost:7860 # optional
|
| 11 |
+
python inference.py
|
| 12 |
+
|
| 13 |
+
Log format:
|
| 14 |
+
[START <task_name>]
|
| 15 |
+
[STEP <n> | reward=<r> | done=<d>]
|
| 16 |
+
[END <task_name> | final_reward=<r>]
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
+
import json
|
| 21 |
+
import sys
|
| 22 |
+
import requests
|
| 23 |
+
from openai import OpenAI
|
| 24 |
+
|
| 25 |
+
# ---------------------------------------------------------------------------
|
| 26 |
+
# Configuration
|
| 27 |
+
# ---------------------------------------------------------------------------
|
| 28 |
+
API_BASE_URL = os.environ.get("API_BASE_URL", "https://router.huggingface.co/v1")
|
| 29 |
+
MODEL_NAME = os.environ.get("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
|
| 30 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 31 |
+
ENV_BASE_URL = os.environ.get("ENV_BASE_URL", "http://localhost:7860")
|
| 32 |
+
MAX_STEPS = int(os.environ.get("MAX_STEPS", "8"))
|
| 33 |
+
|
| 34 |
+
TASKS = ["fix-syntax", "fix-logic", "fix-and-optimize"]
|
| 35 |
+
|
| 36 |
+
if not HF_TOKEN:
|
| 37 |
+
print("ERROR: HF_TOKEN environment variable is required.", file=sys.stderr)
|
| 38 |
+
sys.exit(1)
|
| 39 |
+
|
| 40 |
+
# ---------------------------------------------------------------------------
|
| 41 |
+
# OpenAI client (pointing at HF inference router)
|
| 42 |
+
# ---------------------------------------------------------------------------
|
| 43 |
+
client = OpenAI(
|
| 44 |
+
base_url=API_BASE_URL,
|
| 45 |
+
api_key=HF_TOKEN,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
# ---------------------------------------------------------------------------
|
| 49 |
+
# Prompt helpers
|
| 50 |
+
# ---------------------------------------------------------------------------
|
| 51 |
+
|
| 52 |
+
SYSTEM_PROMPT = """\
|
| 53 |
+
You are an expert SQL developer and debugger. Your job is to fix broken SQL queries.
|
| 54 |
+
|
| 55 |
+
You will be given:
|
| 56 |
+
- A database SCHEMA (CREATE TABLE statements)
|
| 57 |
+
- A TASK DESCRIPTION explaining what the correct query should return
|
| 58 |
+
- The BROKEN QUERY that you need to fix
|
| 59 |
+
- (After the first attempt) the ERROR or OUTPUT from your last attempt
|
| 60 |
+
|
| 61 |
+
Rules:
|
| 62 |
+
- Respond with ONLY the corrected SQL query — no explanations, no markdown fences, no preamble.
|
| 63 |
+
- Your response must be valid SQL that can be executed directly.
|
| 64 |
+
- Fix ALL bugs in the query, not just one at a time.
|
| 65 |
+
- If you receive partial credit, re-read the task description and try harder.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def build_user_prompt(obs: dict) -> str:
|
| 70 |
+
lines = [
|
| 71 |
+
"## SCHEMA",
|
| 72 |
+
obs["schema_str"],
|
| 73 |
+
"",
|
| 74 |
+
"## TASK DESCRIPTION",
|
| 75 |
+
obs["task_description"],
|
| 76 |
+
"",
|
| 77 |
+
"## BROKEN QUERY (original, for reference)",
|
| 78 |
+
obs["broken_query"],
|
| 79 |
+
"",
|
| 80 |
+
f"## STEP {obs['step_number']}",
|
| 81 |
+
]
|
| 82 |
+
if obs.get("last_error"):
|
| 83 |
+
lines += ["### Last Error", obs["last_error"]]
|
| 84 |
+
if obs.get("last_output"):
|
| 85 |
+
lines += ["### Last Output", obs["last_output"]]
|
| 86 |
+
lines += ["", "Write your corrected SQL query below:"]
|
| 87 |
+
return "\n".join(lines)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# ---------------------------------------------------------------------------
|
| 91 |
+
# Environment client helpers
|
| 92 |
+
# ---------------------------------------------------------------------------
|
| 93 |
+
|
| 94 |
+
def env_reset(task: str) -> dict:
|
| 95 |
+
resp = requests.post(f"{ENV_BASE_URL}/reset", params={"task": task}, timeout=30)
|
| 96 |
+
resp.raise_for_status()
|
| 97 |
+
return resp.json()
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def env_step(query: str) -> dict:
|
| 101 |
+
payload = {"query": query}
|
| 102 |
+
resp = requests.post(
|
| 103 |
+
f"{ENV_BASE_URL}/step",
|
| 104 |
+
data=json.dumps(payload),
|
| 105 |
+
headers={"Content-Type": "application/json"},
|
| 106 |
+
timeout=30,
|
| 107 |
+
)
|
| 108 |
+
resp.raise_for_status()
|
| 109 |
+
return resp.json()
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# ---------------------------------------------------------------------------
|
| 113 |
+
# Main inference loop
|
| 114 |
+
# ---------------------------------------------------------------------------
|
| 115 |
+
|
| 116 |
+
def run_task(task_name: str) -> float:
|
| 117 |
+
print(f"[START {task_name}]")
|
| 118 |
+
|
| 119 |
+
obs = env_reset(task_name)
|
| 120 |
+
final_reward = 0.0
|
| 121 |
+
|
| 122 |
+
for step_num in range(1, MAX_STEPS + 1):
|
| 123 |
+
user_prompt = build_user_prompt(obs)
|
| 124 |
+
|
| 125 |
+
# Call the LLM
|
| 126 |
+
response = client.chat.completions.create(
|
| 127 |
+
model=MODEL_NAME,
|
| 128 |
+
messages=[
|
| 129 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 130 |
+
{"role": "user", "content": user_prompt},
|
| 131 |
+
],
|
| 132 |
+
temperature=0.2,
|
| 133 |
+
max_tokens=512,
|
| 134 |
+
)
|
| 135 |
+
query = response.choices[0].message.content.strip()
|
| 136 |
+
|
| 137 |
+
# Submit to environment
|
| 138 |
+
result = env_step(query)
|
| 139 |
+
reward = result["reward"]
|
| 140 |
+
done = result["done"]
|
| 141 |
+
obs = result["observation"]
|
| 142 |
+
|
| 143 |
+
final_reward = reward
|
| 144 |
+
print(f"[STEP {step_num} | reward={reward:.4f} | done={done}]")
|
| 145 |
+
|
| 146 |
+
if done:
|
| 147 |
+
break
|
| 148 |
+
|
| 149 |
+
print(f"[END {task_name} | final_reward={final_reward:.4f}]")
|
| 150 |
+
return final_reward
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def main():
|
| 154 |
+
print("=" * 60)
|
| 155 |
+
print("OpenENV SQL Debugging — Baseline Inference")
|
| 156 |
+
print(f"Model : {MODEL_NAME}")
|
| 157 |
+
print(f"Server : {ENV_BASE_URL}")
|
| 158 |
+
print("=" * 60)
|
| 159 |
+
|
| 160 |
+
all_scores = {}
|
| 161 |
+
for task_name in TASKS:
|
| 162 |
+
score = run_task(task_name)
|
| 163 |
+
all_scores[task_name] = score
|
| 164 |
+
print()
|
| 165 |
+
|
| 166 |
+
print("=" * 60)
|
| 167 |
+
print("Summary:")
|
| 168 |
+
for task_name, score in all_scores.items():
|
| 169 |
+
print(f" {task_name}: {score:.4f}")
|
| 170 |
+
print("=" * 60)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
main()
|
openenv.yaml
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: sql-debug-env
|
| 2 |
+
version: "1.0.0"
|
| 3 |
+
description: >
|
| 4 |
+
An environment where an AI agent debugs and fixes broken SQL queries
|
| 5 |
+
against an in-memory SQLite database. Real-world data analyst task.
|
| 6 |
+
author: "OpenENV Contributor"
|
| 7 |
+
tasks:
|
| 8 |
+
- name: fix-syntax
|
| 9 |
+
difficulty: easy
|
| 10 |
+
description: Fix a SQL query with a simple syntax error (missing comma between column names).
|
| 11 |
+
- name: fix-logic
|
| 12 |
+
difficulty: medium
|
| 13 |
+
description: Fix a query with wrong JOIN type (INNER→LEFT) and incorrect date filter (>→>=).
|
| 14 |
+
- name: fix-and-optimize
|
| 15 |
+
difficulty: hard
|
| 16 |
+
description: Fix a multi-step correlated subquery (wrong alias + missing GROUP BY); bonus for CTE rewrite.
|
| 17 |
+
action_space:
|
| 18 |
+
type: text
|
| 19 |
+
description: A SQL query string submitted by the agent as its fix attempt.
|
| 20 |
+
observation_space:
|
| 21 |
+
schema_str: string
|
| 22 |
+
task_description: string
|
| 23 |
+
broken_query: string
|
| 24 |
+
last_error: string or null
|
| 25 |
+
last_output: string or null
|
| 26 |
+
step_number: integer
|
| 27 |
+
episode:
|
| 28 |
+
max_steps: 8
|
| 29 |
+
reset_on_done: true
|
server/Dockerfile
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 7 |
+
|
| 8 |
+
COPY . .
|
| 9 |
+
|
| 10 |
+
EXPOSE 7860
|
| 11 |
+
|
| 12 |
+
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]
|
server/env.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Core environment logic for the OpenENV SQL Debugging environment.
|
| 3 |
+
Manages SQLite in-memory databases, query execution, and reward computation.
|
| 4 |
+
"""
|
| 5 |
+
import sqlite3
|
| 6 |
+
from typing import Optional, Any
|
| 7 |
+
|
| 8 |
+
from models import SQLAction, SQLObservation, StepResult
|
| 9 |
+
from tasks import TASK_REGISTRY
|
| 10 |
+
import graders as grader_module
|
| 11 |
+
|
| 12 |
+
MAX_STEPS = 8
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _stringify_output(rows: Optional[list]) -> str:
|
| 16 |
+
"""Convert query result rows to a human-readable string."""
|
| 17 |
+
if rows is None:
|
| 18 |
+
return ""
|
| 19 |
+
if not rows:
|
| 20 |
+
return "(empty result)"
|
| 21 |
+
return "\n".join(str(row) for row in rows)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _execute_query(conn: sqlite3.Connection, query: str):
|
| 25 |
+
"""
|
| 26 |
+
Execute a SQL query against the given connection.
|
| 27 |
+
Returns (rows, error_string). rows is None on error.
|
| 28 |
+
"""
|
| 29 |
+
try:
|
| 30 |
+
cursor = conn.execute(query)
|
| 31 |
+
rows = cursor.fetchall()
|
| 32 |
+
return rows, None
|
| 33 |
+
except Exception as exc:
|
| 34 |
+
return None, str(exc)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class SQLEnvironment:
|
| 38 |
+
"""
|
| 39 |
+
OpenENV-compliant SQL debugging environment.
|
| 40 |
+
|
| 41 |
+
Call reset(task_name) to start a new episode.
|
| 42 |
+
Call step(action) to submit a query and receive a StepResult.
|
| 43 |
+
Call state() to get the current observation without advancing the episode.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
def __init__(self):
|
| 47 |
+
self._conn: Optional[sqlite3.Connection] = None
|
| 48 |
+
self._task: Optional[dict] = None
|
| 49 |
+
self._step_number: int = 0
|
| 50 |
+
self._last_error: Optional[str] = None
|
| 51 |
+
self._last_output: Optional[str] = None
|
| 52 |
+
self._done: bool = False
|
| 53 |
+
self._cumulative_errors: int = 0
|
| 54 |
+
self._reference_rows: list = []
|
| 55 |
+
self._current_task_name: str = "fix-syntax"
|
| 56 |
+
|
| 57 |
+
# ------------------------------------------------------------------
|
| 58 |
+
# Public API
|
| 59 |
+
# ------------------------------------------------------------------
|
| 60 |
+
|
| 61 |
+
def reset(self, task_name: str = "fix-syntax") -> SQLObservation:
|
| 62 |
+
"""Reset the environment for the given task. Returns the initial observation."""
|
| 63 |
+
if task_name not in TASK_REGISTRY:
|
| 64 |
+
raise ValueError(
|
| 65 |
+
f"Unknown task '{task_name}'. Valid tasks: {list(TASK_REGISTRY.keys())}"
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
self._task = TASK_REGISTRY[task_name]
|
| 69 |
+
self._current_task_name = task_name
|
| 70 |
+
self._step_number = 0
|
| 71 |
+
self._last_error = None
|
| 72 |
+
self._last_output = None
|
| 73 |
+
self._done = False
|
| 74 |
+
self._cumulative_errors = 0
|
| 75 |
+
|
| 76 |
+
# Build a fresh in-memory SQLite database
|
| 77 |
+
self._conn = sqlite3.connect(":memory:")
|
| 78 |
+
self._conn.isolation_level = None # autocommit
|
| 79 |
+
|
| 80 |
+
for sql in self._task["setup_sql"]:
|
| 81 |
+
self._conn.execute(sql)
|
| 82 |
+
|
| 83 |
+
# Pre-compute the reference result
|
| 84 |
+
ref_rows, ref_err = _execute_query(self._conn, self._task["reference_query"])
|
| 85 |
+
if ref_err:
|
| 86 |
+
raise RuntimeError(
|
| 87 |
+
f"Reference query failed for task '{task_name}': {ref_err}\n"
|
| 88 |
+
f"Query: {self._task['reference_query']}"
|
| 89 |
+
)
|
| 90 |
+
self._reference_rows = ref_rows or []
|
| 91 |
+
|
| 92 |
+
return self._build_observation()
|
| 93 |
+
|
| 94 |
+
def step(self, action: SQLAction) -> StepResult:
|
| 95 |
+
"""Execute the agent's SQL query and return a StepResult."""
|
| 96 |
+
if self._task is None:
|
| 97 |
+
raise RuntimeError("Call reset() before step().")
|
| 98 |
+
if self._done:
|
| 99 |
+
# Episode already finished — return last state with 0 reward
|
| 100 |
+
return StepResult(
|
| 101 |
+
observation=self._build_observation(),
|
| 102 |
+
reward=0.0,
|
| 103 |
+
done=True,
|
| 104 |
+
info={"message": "Episode already done. Call reset() to start a new episode."},
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
self._step_number += 1
|
| 108 |
+
|
| 109 |
+
# Execute the submitted query
|
| 110 |
+
rows, error = _execute_query(self._conn, action.query)
|
| 111 |
+
|
| 112 |
+
if error:
|
| 113 |
+
self._cumulative_errors += 1
|
| 114 |
+
self._last_error = error
|
| 115 |
+
self._last_output = None
|
| 116 |
+
else:
|
| 117 |
+
self._last_error = None
|
| 118 |
+
self._last_output = _stringify_output(rows)
|
| 119 |
+
|
| 120 |
+
# Compute reward via the task-specific grader
|
| 121 |
+
reward = self._compute_reward(action.query, rows, error)
|
| 122 |
+
|
| 123 |
+
# Episode ends on perfect score or max_steps reached
|
| 124 |
+
perfect = (reward >= 1.0)
|
| 125 |
+
max_reached = (self._step_number >= MAX_STEPS)
|
| 126 |
+
self._done = perfect or max_reached
|
| 127 |
+
|
| 128 |
+
obs = self._build_observation()
|
| 129 |
+
info = {
|
| 130 |
+
"task": self._current_task_name,
|
| 131 |
+
"step": self._step_number,
|
| 132 |
+
"error": error,
|
| 133 |
+
"perfect": perfect,
|
| 134 |
+
"max_steps_reached": max_reached,
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
return StepResult(observation=obs, reward=round(reward, 4), done=self._done, info=info)
|
| 138 |
+
|
| 139 |
+
def state(self) -> SQLObservation:
|
| 140 |
+
"""Return the current observation without advancing the episode."""
|
| 141 |
+
if self._task is None:
|
| 142 |
+
raise RuntimeError("Call reset() before state().")
|
| 143 |
+
return self._build_observation()
|
| 144 |
+
|
| 145 |
+
# ------------------------------------------------------------------
|
| 146 |
+
# Private helpers
|
| 147 |
+
# ------------------------------------------------------------------
|
| 148 |
+
|
| 149 |
+
def _build_observation(self) -> SQLObservation:
|
| 150 |
+
return SQLObservation(
|
| 151 |
+
schema_str=self._task["schema_str"],
|
| 152 |
+
task_description=self._task["task_description"],
|
| 153 |
+
broken_query=self._task["broken_query"],
|
| 154 |
+
last_error=self._last_error,
|
| 155 |
+
last_output=self._last_output,
|
| 156 |
+
step_number=self._step_number,
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
def _compute_reward(
|
| 160 |
+
self,
|
| 161 |
+
query_str: str,
|
| 162 |
+
rows: Optional[list],
|
| 163 |
+
error: Optional[str],
|
| 164 |
+
) -> float:
|
| 165 |
+
grader_name = self._task["grader"]
|
| 166 |
+
|
| 167 |
+
if grader_name == "grade_easy":
|
| 168 |
+
raw = grader_module.grade_easy(
|
| 169 |
+
output=rows,
|
| 170 |
+
reference=self._reference_rows,
|
| 171 |
+
error=error,
|
| 172 |
+
)
|
| 173 |
+
elif grader_name == "grade_medium":
|
| 174 |
+
raw = grader_module.grade_medium(
|
| 175 |
+
output=rows,
|
| 176 |
+
reference=self._reference_rows,
|
| 177 |
+
error=error,
|
| 178 |
+
query_str=query_str,
|
| 179 |
+
cumulative_errors=self._cumulative_errors,
|
| 180 |
+
)
|
| 181 |
+
elif grader_name == "grade_hard":
|
| 182 |
+
raw = grader_module.grade_hard(
|
| 183 |
+
output=rows,
|
| 184 |
+
reference=self._reference_rows,
|
| 185 |
+
error=error,
|
| 186 |
+
query_str=query_str,
|
| 187 |
+
)
|
| 188 |
+
else:
|
| 189 |
+
raise ValueError(f"Unknown grader: {grader_name}")
|
| 190 |
+
|
| 191 |
+
# Dense reward formula from spec:
|
| 192 |
+
# reward = correctness_score * (1.0 - 0.05 * step_penalty_factor)
|
| 193 |
+
step_penalty_factor = max(0, self._step_number - 1)
|
| 194 |
+
reward = raw * (1.0 - 0.05 * step_penalty_factor)
|
| 195 |
+
return max(0.0, min(1.0, reward))
|
server/graders.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Graders for each OpenENV SQL task.
|
| 3 |
+
All grader functions return a float in [0.0, 1.0].
|
| 4 |
+
|
| 5 |
+
Grader signatures:
|
| 6 |
+
grade_easy(output, reference, error) -> float
|
| 7 |
+
grade_medium(output, reference, error, query_str, step_errors) -> float
|
| 8 |
+
grade_hard(output, reference, error, query_str) -> float
|
| 9 |
+
"""
|
| 10 |
+
from typing import Optional
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# ---------------------------------------------------------------------------
|
| 14 |
+
# Helpers
|
| 15 |
+
# ---------------------------------------------------------------------------
|
| 16 |
+
|
| 17 |
+
def _normalize_rows(rows: list) -> list:
|
| 18 |
+
"""Normalize a list-of-tuples to lowercase stripped strings for comparison."""
|
| 19 |
+
return [tuple(str(v).strip().lower() if v is not None else "none" for v in row) for row in rows]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _rows_match(a: list, b: list) -> bool:
|
| 23 |
+
"""Return True if two result sets are equal (order-insensitive)."""
|
| 24 |
+
return sorted(_normalize_rows(a)) == sorted(_normalize_rows(b))
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _partial_overlap(a: list, b: list) -> float:
|
| 28 |
+
"""
|
| 29 |
+
Return fraction of reference rows that appear in agent output.
|
| 30 |
+
Used for partial credit scoring.
|
| 31 |
+
"""
|
| 32 |
+
if not b:
|
| 33 |
+
return 1.0 if not a else 0.0
|
| 34 |
+
norm_a = set(map(tuple, _normalize_rows(a)))
|
| 35 |
+
norm_b = set(map(tuple, _normalize_rows(b)))
|
| 36 |
+
overlap = len(norm_a & norm_b)
|
| 37 |
+
return overlap / len(norm_b)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# ---------------------------------------------------------------------------
|
| 41 |
+
# Task 1: fix-syntax (Easy)
|
| 42 |
+
# ---------------------------------------------------------------------------
|
| 43 |
+
|
| 44 |
+
def grade_easy(
|
| 45 |
+
output: Optional[list],
|
| 46 |
+
reference: list,
|
| 47 |
+
error: Optional[str],
|
| 48 |
+
) -> float:
|
| 49 |
+
"""
|
| 50 |
+
Scoring:
|
| 51 |
+
1.0 — query runs AND output matches reference exactly
|
| 52 |
+
0.5 — query runs but output is partially correct
|
| 53 |
+
0.0 — query fails with an error
|
| 54 |
+
"""
|
| 55 |
+
if error is not None:
|
| 56 |
+
return 0.0
|
| 57 |
+
|
| 58 |
+
if _rows_match(output or [], reference):
|
| 59 |
+
return 1.0
|
| 60 |
+
|
| 61 |
+
# Partial credit: right columns present, possible wrong filter
|
| 62 |
+
overlap = _partial_overlap(output or [], reference)
|
| 63 |
+
if overlap > 0:
|
| 64 |
+
return round(0.5 * overlap, 4)
|
| 65 |
+
|
| 66 |
+
return 0.0
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# ---------------------------------------------------------------------------
|
| 70 |
+
# Task 2: fix-logic (Medium)
|
| 71 |
+
# ---------------------------------------------------------------------------
|
| 72 |
+
|
| 73 |
+
def grade_medium(
|
| 74 |
+
output: Optional[list],
|
| 75 |
+
reference: list,
|
| 76 |
+
error: Optional[str],
|
| 77 |
+
query_str: str,
|
| 78 |
+
cumulative_errors: int = 0,
|
| 79 |
+
) -> float:
|
| 80 |
+
"""
|
| 81 |
+
Scoring:
|
| 82 |
+
1.0 — LEFT JOIN used AND date >= '2024-01-01' AND output matches reference
|
| 83 |
+
0.6 — only one of the two bugs is fixed AND output partially matches
|
| 84 |
+
0.2 — query runs but output is wrong
|
| 85 |
+
0.0 — query fails
|
| 86 |
+
-0.1 per error step (capped at 0.0 total)
|
| 87 |
+
"""
|
| 88 |
+
if error is not None:
|
| 89 |
+
penalty = 0.1 * cumulative_errors
|
| 90 |
+
return max(0.0, 0.0 - penalty)
|
| 91 |
+
|
| 92 |
+
q = query_str.lower()
|
| 93 |
+
has_left_join = "left join" in q
|
| 94 |
+
has_gte_date = ">= '2024-01-01'" in q or ">='2024-01-01'" in q
|
| 95 |
+
|
| 96 |
+
both_fixed = has_left_join and has_gte_date
|
| 97 |
+
one_fixed = has_left_join or has_gte_date
|
| 98 |
+
|
| 99 |
+
if both_fixed and _rows_match(output or [], reference):
|
| 100 |
+
base = 1.0
|
| 101 |
+
elif one_fixed and _partial_overlap(output or [], reference) >= 0.5:
|
| 102 |
+
base = 0.6
|
| 103 |
+
elif not error:
|
| 104 |
+
base = 0.2
|
| 105 |
+
else:
|
| 106 |
+
base = 0.0
|
| 107 |
+
|
| 108 |
+
penalty = 0.1 * cumulative_errors
|
| 109 |
+
return max(0.0, round(base - penalty, 4))
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# ---------------------------------------------------------------------------
|
| 113 |
+
# Task 3: fix-and-optimize (Hard)
|
| 114 |
+
# ---------------------------------------------------------------------------
|
| 115 |
+
|
| 116 |
+
def grade_hard(
|
| 117 |
+
output: Optional[list],
|
| 118 |
+
reference: list,
|
| 119 |
+
error: Optional[str],
|
| 120 |
+
query_str: str,
|
| 121 |
+
) -> float:
|
| 122 |
+
"""
|
| 123 |
+
Scoring:
|
| 124 |
+
1.0 — alias fixed AND GROUP BY present AND output matches reference
|
| 125 |
+
0.7 — alias fixed AND query runs but missing GROUP BY
|
| 126 |
+
0.4 — query runs with partial output correctness
|
| 127 |
+
0.0 — query fails to execute
|
| 128 |
+
+0.05 bonus if CTE (WITH clause) is used
|
| 129 |
+
"""
|
| 130 |
+
if error is not None:
|
| 131 |
+
return 0.0
|
| 132 |
+
|
| 133 |
+
q = query_str.lower()
|
| 134 |
+
has_group_by = "group by" in q
|
| 135 |
+
has_cte = q.lstrip().startswith("with ")
|
| 136 |
+
|
| 137 |
+
exact_match = _rows_match(output or [], reference)
|
| 138 |
+
overlap = _partial_overlap(output or [], reference)
|
| 139 |
+
|
| 140 |
+
if exact_match and has_group_by:
|
| 141 |
+
base = 1.0
|
| 142 |
+
elif has_group_by and overlap >= 0.5:
|
| 143 |
+
# Alias might be fixed but output not perfectly matching reference ordering
|
| 144 |
+
base = 0.7
|
| 145 |
+
elif not error and overlap > 0:
|
| 146 |
+
base = 0.4
|
| 147 |
+
elif not error:
|
| 148 |
+
base = 0.2
|
| 149 |
+
else:
|
| 150 |
+
base = 0.0
|
| 151 |
+
|
| 152 |
+
bonus = 0.05 if has_cte else 0.0
|
| 153 |
+
return min(1.0, round(base + bonus, 4))
|
server/main.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
FastAPI server exposing the OpenENV SQL Debugging environment.
|
| 3 |
+
|
| 4 |
+
Endpoints:
|
| 5 |
+
POST /reset?task=<name> → SQLObservation (reset with optional task selection)
|
| 6 |
+
POST /step → StepResult (submit SQLAction, get StepResult)
|
| 7 |
+
GET /state → SQLObservation (current state, no side effects)
|
| 8 |
+
GET /health → {"status":"ok"} (liveness probe)
|
| 9 |
+
"""
|
| 10 |
+
from fastapi import FastAPI, HTTPException, Query
|
| 11 |
+
from fastapi.responses import JSONResponse
|
| 12 |
+
|
| 13 |
+
from models import SQLAction, SQLObservation, StepResult
|
| 14 |
+
from env import SQLEnvironment
|
| 15 |
+
|
| 16 |
+
app = FastAPI(
|
| 17 |
+
title="OpenENV — SQL Debugging Environment",
|
| 18 |
+
description=(
|
| 19 |
+
"An OpenEnv-compliant RL environment where an AI agent debugs and fixes "
|
| 20 |
+
"broken SQL queries against an in-memory SQLite database."
|
| 21 |
+
),
|
| 22 |
+
version="1.0.0",
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
# Single global environment instance (one agent at a time)
|
| 26 |
+
_env = SQLEnvironment()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# ---------------------------------------------------------------------------
|
| 30 |
+
# /health
|
| 31 |
+
# ---------------------------------------------------------------------------
|
| 32 |
+
|
| 33 |
+
@app.get("/health", summary="Liveness probe")
|
| 34 |
+
def health():
|
| 35 |
+
"""Returns 200 OK with status=ok if the server is running."""
|
| 36 |
+
return {"status": "ok"}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# ---------------------------------------------------------------------------
|
| 40 |
+
# /reset
|
| 41 |
+
# ---------------------------------------------------------------------------
|
| 42 |
+
|
| 43 |
+
VALID_TASKS = ["fix-syntax", "fix-logic", "fix-and-optimize"]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@app.post("/reset", response_model=SQLObservation, summary="Reset the environment")
|
| 47 |
+
def reset(
|
| 48 |
+
task: str = Query(
|
| 49 |
+
default="fix-syntax",
|
| 50 |
+
description="Task name. One of: fix-syntax, fix-logic, fix-and-optimize",
|
| 51 |
+
)
|
| 52 |
+
):
|
| 53 |
+
"""
|
| 54 |
+
Reset the environment with the specified task and return the initial observation.
|
| 55 |
+
If no task is provided, defaults to 'fix-syntax'.
|
| 56 |
+
"""
|
| 57 |
+
if task not in VALID_TASKS:
|
| 58 |
+
raise HTTPException(
|
| 59 |
+
status_code=400,
|
| 60 |
+
detail=f"Invalid task '{task}'. Must be one of: {VALID_TASKS}",
|
| 61 |
+
)
|
| 62 |
+
try:
|
| 63 |
+
obs = _env.reset(task_name=task)
|
| 64 |
+
return obs
|
| 65 |
+
except ValueError as exc:
|
| 66 |
+
raise HTTPException(status_code=400, detail=str(exc))
|
| 67 |
+
except RuntimeError as exc:
|
| 68 |
+
raise HTTPException(status_code=500, detail=str(exc))
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
# ---------------------------------------------------------------------------
|
| 72 |
+
# /step
|
| 73 |
+
# ---------------------------------------------------------------------------
|
| 74 |
+
|
| 75 |
+
@app.post("/step", response_model=StepResult, summary="Submit an action")
|
| 76 |
+
def step(action: SQLAction):
|
| 77 |
+
"""
|
| 78 |
+
Submit a SQL query as the agent's action. Returns a StepResult with
|
| 79 |
+
the new observation, reward, done flag, and info dict.
|
| 80 |
+
"""
|
| 81 |
+
try:
|
| 82 |
+
result = _env.step(action)
|
| 83 |
+
return result
|
| 84 |
+
except RuntimeError as exc:
|
| 85 |
+
raise HTTPException(status_code=400, detail=str(exc))
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
# ---------------------------------------------------------------------------
|
| 89 |
+
# /state
|
| 90 |
+
# ---------------------------------------------------------------------------
|
| 91 |
+
|
| 92 |
+
@app.get("/state", response_model=SQLObservation, summary="Get current state")
|
| 93 |
+
def state():
|
| 94 |
+
"""
|
| 95 |
+
Return the current observation without advancing the episode.
|
| 96 |
+
Useful for agents that need to re-read the environment state.
|
| 97 |
+
"""
|
| 98 |
+
try:
|
| 99 |
+
obs = _env.state()
|
| 100 |
+
return obs
|
| 101 |
+
except RuntimeError as exc:
|
| 102 |
+
raise HTTPException(status_code=400, detail=str(exc))
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# ---------------------------------------------------------------------------
|
| 106 |
+
# Root redirect → docs
|
| 107 |
+
# ---------------------------------------------------------------------------
|
| 108 |
+
|
| 109 |
+
@app.get("/", include_in_schema=False)
|
| 110 |
+
def root():
|
| 111 |
+
return JSONResponse({"message": "OpenENV SQL Debugging Environment. See /docs for API reference."})
|
server/models.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Pydantic models for the OpenENV SQL Debugging environment.
|
| 3 |
+
"""
|
| 4 |
+
from typing import Optional
|
| 5 |
+
from pydantic import BaseModel
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class SQLAction(BaseModel):
|
| 9 |
+
"""Action submitted by the agent — a SQL query string."""
|
| 10 |
+
query: str
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class SQLObservation(BaseModel):
|
| 14 |
+
"""Observation returned by the environment after reset or step."""
|
| 15 |
+
schema_str: str # Table definitions (CREATE TABLE statements)
|
| 16 |
+
task_description: str # Natural language description of what the query should do
|
| 17 |
+
broken_query: str # The buggy starting query (provided at reset, unchanged)
|
| 18 |
+
last_error: Optional[str] = None # Execution error from last action, or None
|
| 19 |
+
last_output: Optional[str] = None # Stringified output of last query, or None
|
| 20 |
+
step_number: int = 0
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class StepResult(BaseModel):
|
| 24 |
+
"""Result returned after each step."""
|
| 25 |
+
observation: SQLObservation
|
| 26 |
+
reward: float # Per-step reward in [0.0, 1.0]
|
| 27 |
+
done: bool
|
| 28 |
+
info: dict
|
server/requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi>=0.110.0
|
| 2 |
+
uvicorn[standard]>=0.29.0
|
| 3 |
+
pydantic>=2.0.0
|
server/tasks/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Task registry — maps task names to their definition modules.
|
| 3 |
+
"""
|
| 4 |
+
from .task_easy import TASK as TASK_EASY
|
| 5 |
+
from .task_medium import TASK as TASK_MEDIUM
|
| 6 |
+
from .task_hard import TASK as TASK_HARD
|
| 7 |
+
|
| 8 |
+
TASK_REGISTRY: dict = {
|
| 9 |
+
"fix-syntax": TASK_EASY,
|
| 10 |
+
"fix-logic": TASK_MEDIUM,
|
| 11 |
+
"fix-and-optimize": TASK_HARD,
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
__all__ = ["TASK_REGISTRY"]
|
server/tasks/__pycache__/__init__.cpython-314.pyc
ADDED
|
Binary file (771 Bytes). View file
|
|
|
server/tasks/__pycache__/task_easy.cpython-314.pyc
ADDED
|
Binary file (1.75 kB). View file
|
|
|
server/tasks/__pycache__/task_hard.cpython-314.pyc
ADDED
|
Binary file (2.75 kB). View file
|
|
|
server/tasks/__pycache__/task_medium.cpython-314.pyc
ADDED
|
Binary file (2.36 kB). View file
|
|
|
server/tasks/task_easy.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Task 1 — fix-syntax (Easy)
|
| 3 |
+
Scenario: A query is missing a comma between column names.
|
| 4 |
+
Goal: Return id and name from the users table for active users.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
SCHEMA_STR = """
|
| 8 |
+
CREATE TABLE users (
|
| 9 |
+
id INTEGER PRIMARY KEY,
|
| 10 |
+
name TEXT NOT NULL,
|
| 11 |
+
active INTEGER NOT NULL -- 1 = active, 0 = inactive
|
| 12 |
+
);
|
| 13 |
+
""".strip()
|
| 14 |
+
|
| 15 |
+
# Seed data: list of (id, name, active)
|
| 16 |
+
SEED_DATA = [
|
| 17 |
+
(1, "Alice", 1),
|
| 18 |
+
(2, "Bob", 0),
|
| 19 |
+
(3, "Carol", 1),
|
| 20 |
+
(4, "Dave", 1),
|
| 21 |
+
(5, "Eve", 0),
|
| 22 |
+
]
|
| 23 |
+
|
| 24 |
+
SETUP_SQL = [
|
| 25 |
+
"""
|
| 26 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 27 |
+
id INTEGER PRIMARY KEY,
|
| 28 |
+
name TEXT NOT NULL,
|
| 29 |
+
active INTEGER NOT NULL
|
| 30 |
+
)
|
| 31 |
+
""",
|
| 32 |
+
"INSERT INTO users (id, name, active) VALUES (1, 'Alice', 1)",
|
| 33 |
+
"INSERT INTO users (id, name, active) VALUES (2, 'Bob', 0)",
|
| 34 |
+
"INSERT INTO users (id, name, active) VALUES (3, 'Carol', 1)",
|
| 35 |
+
"INSERT INTO users (id, name, active) VALUES (4, 'Dave', 1)",
|
| 36 |
+
"INSERT INTO users (id, name, active) VALUES (5, 'Eve', 0)",
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
BROKEN_QUERY = "SELECT id name FROM users WHERE active = 1;"
|
| 40 |
+
|
| 41 |
+
REFERENCE_QUERY = "SELECT id, name FROM users WHERE active = 1 ORDER BY id;"
|
| 42 |
+
|
| 43 |
+
TASK_DESCRIPTION = (
|
| 44 |
+
"Fix the SQL query so that it selects BOTH the 'id' AND 'name' columns "
|
| 45 |
+
"from the 'users' table, returning only rows where active = 1. "
|
| 46 |
+
"The current query is missing a comma between 'id' and 'name'."
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
TASK = {
|
| 50 |
+
"name": "fix-syntax",
|
| 51 |
+
"difficulty": "easy",
|
| 52 |
+
"schema_str": SCHEMA_STR,
|
| 53 |
+
"broken_query": BROKEN_QUERY,
|
| 54 |
+
"reference_query": REFERENCE_QUERY,
|
| 55 |
+
"task_description": TASK_DESCRIPTION,
|
| 56 |
+
"setup_sql": SETUP_SQL,
|
| 57 |
+
"grader": "grade_easy",
|
| 58 |
+
}
|
server/tasks/task_hard.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Task 3 — fix-and-optimize (Hard)
|
| 3 |
+
Scenario: Correlated subquery uses wrong alias (e.dept instead of employees.dept)
|
| 4 |
+
AND the outer query is missing a GROUP BY clause.
|
| 5 |
+
Goal: For each department, return the average salary of employees earning above
|
| 6 |
+
their department's average. Must GROUP BY dept.
|
| 7 |
+
Bonus: +0.05 if the agent uses a CTE (WITH clause) instead of a correlated subquery.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
SCHEMA_STR = """
|
| 11 |
+
CREATE TABLE employees (
|
| 12 |
+
id INTEGER PRIMARY KEY,
|
| 13 |
+
dept TEXT NOT NULL,
|
| 14 |
+
salary REAL NOT NULL
|
| 15 |
+
);
|
| 16 |
+
""".strip()
|
| 17 |
+
|
| 18 |
+
SETUP_SQL = [
|
| 19 |
+
"""
|
| 20 |
+
CREATE TABLE IF NOT EXISTS employees (
|
| 21 |
+
id INTEGER PRIMARY KEY,
|
| 22 |
+
dept TEXT NOT NULL,
|
| 23 |
+
salary REAL NOT NULL
|
| 24 |
+
)
|
| 25 |
+
""",
|
| 26 |
+
# Engineering: avg = (90000+80000+70000)/3 = 80000
|
| 27 |
+
# Above avg: 90000, 80000 — avg of those = 85000
|
| 28 |
+
"INSERT INTO employees VALUES (1, 'Engineering', 90000)",
|
| 29 |
+
"INSERT INTO employees VALUES (2, 'Engineering', 80000)",
|
| 30 |
+
"INSERT INTO employees VALUES (3, 'Engineering', 70000)",
|
| 31 |
+
# Marketing: avg = (60000+50000)/2 = 55000
|
| 32 |
+
# Above avg: 60000 — avg of those = 60000
|
| 33 |
+
"INSERT INTO employees VALUES (4, 'Marketing', 60000)",
|
| 34 |
+
"INSERT INTO employees VALUES (5, 'Marketing', 50000)",
|
| 35 |
+
# HR: avg = (45000+55000+40000)/3 = 46667
|
| 36 |
+
# Above avg: 55000 — avg of those = 55000
|
| 37 |
+
"INSERT INTO employees VALUES (6, 'HR', 45000)",
|
| 38 |
+
"INSERT INTO employees VALUES (7, 'HR', 55000)",
|
| 39 |
+
"INSERT INTO employees VALUES (8, 'HR', 40000)",
|
| 40 |
+
]
|
| 41 |
+
|
| 42 |
+
# The broken query: wrong alias 'e.dept' in subquery (table alias 'e' not defined inside subquery)
|
| 43 |
+
# and missing GROUP BY in outer query
|
| 44 |
+
BROKEN_QUERY = """SELECT dept, AVG(salary)
|
| 45 |
+
FROM employees
|
| 46 |
+
WHERE salary > (SELECT AVG(salary) FROM employees WHERE dept = e.dept);"""
|
| 47 |
+
|
| 48 |
+
# Fixed query (standard correlated subquery approach — valid SQL)
|
| 49 |
+
REFERENCE_QUERY = """SELECT dept, AVG(salary) as avg_above_dept_avg
|
| 50 |
+
FROM employees e
|
| 51 |
+
WHERE salary > (SELECT AVG(salary) FROM employees WHERE dept = e.dept)
|
| 52 |
+
GROUP BY dept
|
| 53 |
+
ORDER BY dept;"""
|
| 54 |
+
|
| 55 |
+
# CTE alternative (also correct — eligible for bonus)
|
| 56 |
+
CTE_REFERENCE_QUERY = """WITH dept_avgs AS (
|
| 57 |
+
SELECT dept, AVG(salary) AS dept_avg
|
| 58 |
+
FROM employees
|
| 59 |
+
GROUP BY dept
|
| 60 |
+
)
|
| 61 |
+
SELECT e.dept, AVG(e.salary) as avg_above_dept_avg
|
| 62 |
+
FROM employees e
|
| 63 |
+
JOIN dept_avgs d ON e.dept = d.dept
|
| 64 |
+
WHERE e.salary > d.dept_avg
|
| 65 |
+
GROUP BY e.dept
|
| 66 |
+
ORDER BY e.dept;"""
|
| 67 |
+
|
| 68 |
+
TASK_DESCRIPTION = (
|
| 69 |
+
"Fix two bugs in this SQL query:\n"
|
| 70 |
+
"1. The correlated subquery references alias 'e.dept', but alias 'e' is not defined in the subquery scope. "
|
| 71 |
+
"Move the alias to the outer query: 'FROM employees e'.\n"
|
| 72 |
+
"2. The outer query is missing a GROUP BY clause — add 'GROUP BY dept'.\n"
|
| 73 |
+
"Goal: For each department, return the average salary of employees who earn MORE than their "
|
| 74 |
+
"department's average salary.\n"
|
| 75 |
+
"BONUS: Rewrite using a CTE (WITH clause) for extra credit (+0.05 score)."
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
TASK = {
|
| 79 |
+
"name": "fix-and-optimize",
|
| 80 |
+
"difficulty": "hard",
|
| 81 |
+
"schema_str": SCHEMA_STR,
|
| 82 |
+
"broken_query": BROKEN_QUERY,
|
| 83 |
+
"reference_query": REFERENCE_QUERY,
|
| 84 |
+
"cte_reference_query": CTE_REFERENCE_QUERY,
|
| 85 |
+
"task_description": TASK_DESCRIPTION,
|
| 86 |
+
"setup_sql": SETUP_SQL,
|
| 87 |
+
"grader": "grade_hard",
|
| 88 |
+
}
|
server/tasks/task_medium.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Task 2 — fix-logic (Medium)
|
| 3 |
+
Scenario: INNER JOIN should be LEFT JOIN; date filter uses > instead of >=.
|
| 4 |
+
Goal: List ALL users (including those with no orders) and their order totals from 2024 onwards.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
SCHEMA_STR = """
|
| 8 |
+
CREATE TABLE users (
|
| 9 |
+
id INTEGER PRIMARY KEY,
|
| 10 |
+
name TEXT NOT NULL
|
| 11 |
+
);
|
| 12 |
+
|
| 13 |
+
CREATE TABLE orders (
|
| 14 |
+
id INTEGER PRIMARY KEY,
|
| 15 |
+
user_id INTEGER NOT NULL,
|
| 16 |
+
total REAL NOT NULL,
|
| 17 |
+
created_at TEXT NOT NULL -- stored as ISO-8601 date string: 'YYYY-MM-DD'
|
| 18 |
+
);
|
| 19 |
+
""".strip()
|
| 20 |
+
|
| 21 |
+
SETUP_SQL = [
|
| 22 |
+
"""
|
| 23 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 24 |
+
id INTEGER PRIMARY KEY,
|
| 25 |
+
name TEXT NOT NULL
|
| 26 |
+
)
|
| 27 |
+
""",
|
| 28 |
+
"""
|
| 29 |
+
CREATE TABLE IF NOT EXISTS orders (
|
| 30 |
+
id INTEGER PRIMARY KEY,
|
| 31 |
+
user_id INTEGER NOT NULL,
|
| 32 |
+
total REAL NOT NULL,
|
| 33 |
+
created_at TEXT NOT NULL
|
| 34 |
+
)
|
| 35 |
+
""",
|
| 36 |
+
"INSERT INTO users VALUES (1, 'Alice')",
|
| 37 |
+
"INSERT INTO users VALUES (2, 'Bob')",
|
| 38 |
+
"INSERT INTO users VALUES (3, 'Carol')", # Carol has no orders
|
| 39 |
+
"INSERT INTO users VALUES (4, 'Dave')", # Dave has no orders
|
| 40 |
+
# Orders: some before 2024, some on exactly 2024-01-01, some after
|
| 41 |
+
"INSERT INTO orders VALUES (1, 1, 150.0, '2023-12-31')", # before cutoff
|
| 42 |
+
"INSERT INTO orders VALUES (2, 1, 200.0, '2024-01-01')", # exactly on cutoff (>= must include)
|
| 43 |
+
"INSERT INTO orders VALUES (3, 2, 400.0, '2024-06-15')", # after cutoff
|
| 44 |
+
"INSERT INTO orders VALUES (4, 2, 50.0, '2023-11-01')", # before cutoff
|
| 45 |
+
]
|
| 46 |
+
|
| 47 |
+
BROKEN_QUERY = """SELECT u.name, o.total
|
| 48 |
+
FROM users u
|
| 49 |
+
INNER JOIN orders o ON u.id = o.user_id
|
| 50 |
+
WHERE o.created_at > '2024-01-01';"""
|
| 51 |
+
|
| 52 |
+
REFERENCE_QUERY = """SELECT u.name, o.total
|
| 53 |
+
FROM users u
|
| 54 |
+
LEFT JOIN orders o ON u.id = o.user_id AND o.created_at >= '2024-01-01'
|
| 55 |
+
ORDER BY u.id, o.id;"""
|
| 56 |
+
|
| 57 |
+
TASK_DESCRIPTION = (
|
| 58 |
+
"Fix two bugs in the SQL query:\n"
|
| 59 |
+
"1. Change INNER JOIN to LEFT JOIN so that ALL users appear, even those with no orders.\n"
|
| 60 |
+
"2. Change the date filter from '> 2024-01-01' to '>= 2024-01-01' so orders made exactly on 2024-01-01 are included.\n"
|
| 61 |
+
"The result should list every user with their qualifying order totals (NULL for users with no orders in 2024+)."
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
TASK = {
|
| 65 |
+
"name": "fix-logic",
|
| 66 |
+
"difficulty": "medium",
|
| 67 |
+
"schema_str": SCHEMA_STR,
|
| 68 |
+
"broken_query": BROKEN_QUERY,
|
| 69 |
+
"reference_query": REFERENCE_QUERY,
|
| 70 |
+
"task_description": TASK_DESCRIPTION,
|
| 71 |
+
"setup_sql": SETUP_SQL,
|
| 72 |
+
"grader": "grade_medium",
|
| 73 |
+
}
|
test_env.py
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
test_env.py — Local end-to-end test for the OpenENV SQL Debugging environment.
|
| 3 |
+
|
| 4 |
+
Does NOT require an HF_TOKEN — it uses hard-coded correct SQL fixes to validate
|
| 5 |
+
that the server is returning expected rewards, not an LLM.
|
| 6 |
+
|
| 7 |
+
Prerequisites:
|
| 8 |
+
pip install requests
|
| 9 |
+
docker run -p 7860:7860 sql-debug-env (or uvicorn running locally)
|
| 10 |
+
|
| 11 |
+
Run:
|
| 12 |
+
python test_env.py
|
| 13 |
+
python test_env.py --url http://localhost:7860 # custom server URL
|
| 14 |
+
|
| 15 |
+
Exit code: 0 if all tests pass, 1 if any test fails.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import sys
|
| 19 |
+
import json
|
| 20 |
+
import argparse
|
| 21 |
+
import requests
|
| 22 |
+
|
| 23 |
+
# ---------------------------------------------------------------------------
|
| 24 |
+
# Correct ("golden") fix queries for every task
|
| 25 |
+
# ---------------------------------------------------------------------------
|
| 26 |
+
TASK_FIXES = {
|
| 27 |
+
"fix-syntax": [
|
| 28 |
+
# Bug: missing comma between id and name
|
| 29 |
+
"SELECT id, name FROM users WHERE active = 1;",
|
| 30 |
+
],
|
| 31 |
+
"fix-logic": [
|
| 32 |
+
# Bugs: INNER JOIN → LEFT JOIN, > → >=, move date filter to ON clause
|
| 33 |
+
(
|
| 34 |
+
"SELECT u.name, o.total "
|
| 35 |
+
"FROM users u "
|
| 36 |
+
"LEFT JOIN orders o ON u.id = o.user_id AND o.created_at >= '2024-01-01';"
|
| 37 |
+
),
|
| 38 |
+
],
|
| 39 |
+
"fix-and-optimize": [
|
| 40 |
+
# Bug: missing alias 'e' on outer table + GROUP BY
|
| 41 |
+
(
|
| 42 |
+
"SELECT e.dept, AVG(e.salary) "
|
| 43 |
+
"FROM employees e "
|
| 44 |
+
"WHERE e.salary > (SELECT AVG(salary) FROM employees WHERE dept = e.dept) "
|
| 45 |
+
"GROUP BY e.dept;"
|
| 46 |
+
),
|
| 47 |
+
],
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
# Minimum expected reward for the golden fix on the first correct attempt
|
| 51 |
+
MIN_PASS_REWARD = {
|
| 52 |
+
"fix-syntax": 0.9,
|
| 53 |
+
"fix-logic": 0.9,
|
| 54 |
+
"fix-and-optimize": 0.9,
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
PASS = "✅ PASS"
|
| 58 |
+
FAIL = "❌ FAIL"
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ---------------------------------------------------------------------------
|
| 62 |
+
# Helpers
|
| 63 |
+
# ---------------------------------------------------------------------------
|
| 64 |
+
|
| 65 |
+
def health_check(base: str) -> None:
|
| 66 |
+
"""Verify server is reachable and healthy."""
|
| 67 |
+
try:
|
| 68 |
+
r = requests.get(f"{base}/health", timeout=10)
|
| 69 |
+
r.raise_for_status()
|
| 70 |
+
data = r.json()
|
| 71 |
+
assert data.get("status") == "ok", f"Unexpected health response: {data}"
|
| 72 |
+
print(f"[health] {PASS} → {data}")
|
| 73 |
+
except Exception as exc:
|
| 74 |
+
print(f"[health] {FAIL} → {exc}")
|
| 75 |
+
print("\nIs the server running? Start it with:")
|
| 76 |
+
print(" docker run -p 7860:7860 sql-debug-env")
|
| 77 |
+
print(" OR: cd server && uvicorn main:app --port 7860")
|
| 78 |
+
sys.exit(1)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def reset_env(base: str, task: str) -> dict:
|
| 82 |
+
r = requests.post(f"{base}/reset", params={"task": task}, timeout=30)
|
| 83 |
+
r.raise_for_status()
|
| 84 |
+
return r.json()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def step_env(base: str, query: str) -> dict:
|
| 88 |
+
payload = {"query": query}
|
| 89 |
+
r = requests.post(
|
| 90 |
+
f"{base}/step",
|
| 91 |
+
data=json.dumps(payload),
|
| 92 |
+
headers={"Content-Type": "application/json"},
|
| 93 |
+
timeout=30,
|
| 94 |
+
)
|
| 95 |
+
r.raise_for_status()
|
| 96 |
+
return r.json()
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def get_state(base: str) -> dict:
|
| 100 |
+
r = requests.get(f"{base}/state", timeout=10)
|
| 101 |
+
r.raise_for_status()
|
| 102 |
+
return r.json()
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
# ---------------------------------------------------------------------------
|
| 106 |
+
# Test routines
|
| 107 |
+
# ---------------------------------------------------------------------------
|
| 108 |
+
|
| 109 |
+
def test_reset_returns_observation(base: str, task: str) -> bool:
|
| 110 |
+
"""POST /reset should return a valid SQLObservation."""
|
| 111 |
+
try:
|
| 112 |
+
obs = reset_env(base, task)
|
| 113 |
+
required = ["schema_str", "task_description", "broken_query", "step_number"]
|
| 114 |
+
missing = [k for k in required if k not in obs]
|
| 115 |
+
if missing:
|
| 116 |
+
print(f" [{task}] reset missing fields: {missing} {FAIL}")
|
| 117 |
+
return False
|
| 118 |
+
if obs["step_number"] != 0:
|
| 119 |
+
print(f" [{task}] step_number should be 0 after reset, got {obs['step_number']} {FAIL}")
|
| 120 |
+
return False
|
| 121 |
+
print(f" [{task}] /reset observation {PASS}")
|
| 122 |
+
return True
|
| 123 |
+
except Exception as exc:
|
| 124 |
+
print(f" [{task}] /reset error: {exc} {FAIL}")
|
| 125 |
+
return False
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_state_endpoint(base: str, task: str) -> bool:
|
| 129 |
+
"""GET /state should mirror the current observation without side effects."""
|
| 130 |
+
try:
|
| 131 |
+
reset_env(base, task)
|
| 132 |
+
state = get_state(base)
|
| 133 |
+
required = ["schema_str", "task_description", "broken_query", "step_number"]
|
| 134 |
+
missing = [k for k in required if k not in state]
|
| 135 |
+
if missing:
|
| 136 |
+
print(f" [{task}] /state missing fields: {missing} {FAIL}")
|
| 137 |
+
return False
|
| 138 |
+
print(f" [{task}] /state returns observation {PASS}")
|
| 139 |
+
return True
|
| 140 |
+
except Exception as exc:
|
| 141 |
+
print(f" [{task}] /state error: {exc} {FAIL}")
|
| 142 |
+
return False
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def test_broken_query_fails(base: str, task: str) -> bool:
|
| 146 |
+
"""Submitting the original broken query should return reward=0 (or low)."""
|
| 147 |
+
try:
|
| 148 |
+
obs = reset_env(base, task)
|
| 149 |
+
broken = obs["broken_query"]
|
| 150 |
+
result = step_env(base, broken)
|
| 151 |
+
reward = result["reward"]
|
| 152 |
+
# Broken queries may run but score low, or fail (reward 0)
|
| 153 |
+
# We just verify the structure
|
| 154 |
+
for field in ["observation", "reward", "done", "info"]:
|
| 155 |
+
if field not in result:
|
| 156 |
+
print(f" [{task}] /step missing field '{field}' {FAIL}")
|
| 157 |
+
return False
|
| 158 |
+
print(f" [{task}] broken query step (reward={reward:.4f}) {PASS}")
|
| 159 |
+
return True
|
| 160 |
+
except Exception as exc:
|
| 161 |
+
print(f" [{task}] broken query step error: {exc} {FAIL}")
|
| 162 |
+
return False
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def test_golden_fix_scores_high(base: str, task: str) -> bool:
|
| 166 |
+
"""Submitting the correct fix should yield a high reward."""
|
| 167 |
+
try:
|
| 168 |
+
reset_env(base, task)
|
| 169 |
+
fix_queries = TASK_FIXES[task]
|
| 170 |
+
result = None
|
| 171 |
+
for query in fix_queries:
|
| 172 |
+
result = step_env(base, query)
|
| 173 |
+
reward = result["reward"]
|
| 174 |
+
done = result["done"]
|
| 175 |
+
min_r = MIN_PASS_REWARD[task]
|
| 176 |
+
ok = reward >= min_r
|
| 177 |
+
status = PASS if ok else FAIL
|
| 178 |
+
print(f" [{task}] golden fix reward={reward:.4f} (need>={min_r}) {status}")
|
| 179 |
+
if not ok:
|
| 180 |
+
print(f" done={done} info={result.get('info')}")
|
| 181 |
+
return ok
|
| 182 |
+
except Exception as exc:
|
| 183 |
+
print(f" [{task}] golden fix error: {exc} {FAIL}")
|
| 184 |
+
return False
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def test_wrong_query_gives_nonperfect(base: str, task: str) -> bool:
|
| 188 |
+
"""A completely wrong query should not give reward=1.0."""
|
| 189 |
+
try:
|
| 190 |
+
reset_env(base, task)
|
| 191 |
+
result = step_env(base, "SELECT 1;")
|
| 192 |
+
reward = result["reward"]
|
| 193 |
+
ok = reward < 1.0
|
| 194 |
+
status = PASS if ok else FAIL
|
| 195 |
+
print(f" [{task}] wrong query reward={reward:.4f} (<1.0) {status}")
|
| 196 |
+
return ok
|
| 197 |
+
except Exception as exc:
|
| 198 |
+
print(f" [{task}] wrong query test error: {exc} {FAIL}")
|
| 199 |
+
return False
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def test_max_steps_triggers_done(base: str, task: str, max_steps: int = 8) -> bool:
|
| 203 |
+
"""After max_steps steps the env should set done=True."""
|
| 204 |
+
try:
|
| 205 |
+
reset_env(base, task)
|
| 206 |
+
done = False
|
| 207 |
+
last_result = None
|
| 208 |
+
for i in range(max_steps + 2): # go slightly over
|
| 209 |
+
last_result = step_env(base, "SELECT 1;")
|
| 210 |
+
done = last_result["done"]
|
| 211 |
+
if done:
|
| 212 |
+
break
|
| 213 |
+
ok = done
|
| 214 |
+
status = PASS if ok else FAIL
|
| 215 |
+
extra = f" (after {i+1} steps)" if ok else " (never triggered)"
|
| 216 |
+
print(f" [{task}] done=True at max_steps {status}{extra}")
|
| 217 |
+
return ok
|
| 218 |
+
except Exception as exc:
|
| 219 |
+
print(f" [{task}] max_steps test error: {exc} {FAIL}")
|
| 220 |
+
return False
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
# ---------------------------------------------------------------------------
|
| 224 |
+
# Full suite
|
| 225 |
+
# ---------------------------------------------------------------------------
|
| 226 |
+
|
| 227 |
+
def run_suite(base: str) -> bool:
|
| 228 |
+
tasks = ["fix-syntax", "fix-logic", "fix-and-optimize"]
|
| 229 |
+
results = []
|
| 230 |
+
|
| 231 |
+
print("\n" + "=" * 60)
|
| 232 |
+
print("OpenENV — Local End-to-End Test Suite")
|
| 233 |
+
print(f"Server : {base}")
|
| 234 |
+
print("=" * 60)
|
| 235 |
+
|
| 236 |
+
# 1. Health check
|
| 237 |
+
print("\n── Health Check ─────────────────────────────────────────")
|
| 238 |
+
health_check(base)
|
| 239 |
+
|
| 240 |
+
# 2. Per-task tests
|
| 241 |
+
for task in tasks:
|
| 242 |
+
print(f"\n── Task: {task} ──────────────────────────────────────────")
|
| 243 |
+
results.append(test_reset_returns_observation(base, task))
|
| 244 |
+
results.append(test_state_endpoint(base, task))
|
| 245 |
+
results.append(test_broken_query_fails(base, task))
|
| 246 |
+
results.append(test_wrong_query_gives_nonperfect(base, task))
|
| 247 |
+
results.append(test_golden_fix_scores_high(base, task))
|
| 248 |
+
results.append(test_max_steps_triggers_done(base, task))
|
| 249 |
+
|
| 250 |
+
# 3. Summary
|
| 251 |
+
passed = sum(results)
|
| 252 |
+
total = len(results)
|
| 253 |
+
print("\n" + "=" * 60)
|
| 254 |
+
if passed == total:
|
| 255 |
+
print(f"ALL TESTS PASSED ✅ ({passed}/{total})")
|
| 256 |
+
else:
|
| 257 |
+
print(f"SOME TESTS FAILED ❌ ({passed}/{total} passed)")
|
| 258 |
+
print("=" * 60 + "\n")
|
| 259 |
+
|
| 260 |
+
return passed == total
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
# ---------------------------------------------------------------------------
|
| 264 |
+
# Entry point
|
| 265 |
+
# ---------------------------------------------------------------------------
|
| 266 |
+
|
| 267 |
+
if __name__ == "__main__":
|
| 268 |
+
parser = argparse.ArgumentParser(description="OpenENV local test suite")
|
| 269 |
+
parser.add_argument(
|
| 270 |
+
"--url",
|
| 271 |
+
default="http://localhost:7860",
|
| 272 |
+
help="Base URL of the running OpenENV server (default: http://localhost:7860)",
|
| 273 |
+
)
|
| 274 |
+
args = parser.parse_args()
|
| 275 |
+
|
| 276 |
+
ok = run_suite(args.url)
|
| 277 |
+
sys.exit(0 if ok else 1)
|