File size: 8,923 Bytes
9aba5a4
2f8e591
 
 
9aba5a4
 
2f8e591
 
 
 
 
 
9aba5a4
 
2f8e591
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
---
title: OpenENV — SQL Query Debugging Environment
emoji: 🛠️
colorFrom: blue
colorTo: indigo
sdk: docker
app_port: 7860
tags:
  - openenv
  - reinforcement-learning
  - sql
  - nlp
---

# OpenENV — SQL Query Debugging Environment

[![OpenEnv](https://img.shields.io/badge/OpenEnv-compliant-brightgreen)](https://openenv.dev)
[![HuggingFace Spaces](https://img.shields.io/badge/HuggingFace-Space-orange)](https://huggingface.co/spaces)
[![Python 3.11](https://img.shields.io/badge/Python-3.11-blue)](https://python.org)

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.

---

## Environment Description

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:

- Whether the query executed without errors
- The actual output of the query (stringified rows)
- A reward score reflecting correctness progression

This is **dense reward** design — the agent receives partial credit for partial progress, encouraging systematic debugging rather than random guessing.

---

## Observation Space

| Field              | Type           | Description                                        |
|--------------------|----------------|----------------------------------------------------|
| `schema_str`       | `string`       | CREATE TABLE definitions for the task's database   |
| `task_description` | `string`       | Natural language description of the desired result |
| `broken_query`     | `string`       | The original buggy SQL query (shown at reset)      |
| `last_error`       | `string\|null` | SQL error from the previous step, or null          |
| `last_output`      | `string\|null` | Stringified query output from last step, or null   |
| `step_number`      | `integer`      | Current step within the episode (starts at 0)      |

---

## Action Space

| Type     | Description                                        |
|----------|----------------------------------------------------|
| `text`   | A SQL query string submitted by the agent as a fix |

**Action schema:**
```json
{ "query": "SELECT id, name FROM users WHERE active = 1;" }
```

---

## Tasks

### Task 1: `fix-syntax` — Easy
**Scenario:** A `SELECT` statement is missing a comma between column names.

```sql
-- Broken
SELECT id name FROM users WHERE active = 1;

-- Fixed
SELECT id, name FROM users WHERE active = 1;
```

**Grading:**
| Score | Condition |
|-------|-----------|
| `1.0` | Query runs AND output matches reference exactly |
| `0.5` | Query runs but output partially correct |
| `0.0` | Query fails with an error |

---

### Task 2: `fix-logic` — Medium
**Scenario:** `INNER JOIN` should be `LEFT JOIN`; date filter uses `>` instead of `>=`.

```sql
-- Broken
SELECT u.name, o.total
FROM users u
INNER JOIN orders o ON u.id = o.user_id
WHERE o.created_at > '2024-01-01';

-- Fixed
SELECT u.name, o.total
FROM users u
LEFT JOIN orders o ON u.id = o.user_id AND o.created_at >= '2024-01-01';
```

**Grading:**
| Score | Condition |
|-------|-----------|
| `1.0` | Both bugs fixed AND output matches |
| `0.6` | One of the two bugs fixed |
| `0.2` | Query runs but output is wrong |
| `0.0` | Query fails |
| `-0.1/error` | Penalty for each error step (capped at 0.0) |

---

### Task 3: `fix-and-optimize` — Hard
**Scenario:** Correlated subquery uses wrong alias (`e.dept` undefined inside subquery) + outer query missing `GROUP BY`.

```sql
-- Broken
SELECT dept, AVG(salary)
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees WHERE dept = e.dept);

-- Fixed (correlated subquery approach)
SELECT dept, AVG(salary)
FROM employees e
WHERE salary > (SELECT AVG(salary) FROM employees WHERE dept = e.dept)
GROUP BY dept;

-- Bonus: CTE approach (+0.05)
WITH dept_avgs AS (
    SELECT dept, AVG(salary) AS dept_avg FROM employees GROUP BY dept
)
SELECT e.dept, AVG(e.salary)
FROM employees e JOIN dept_avgs d ON e.dept = d.dept
WHERE e.salary > d.dept_avg
GROUP BY e.dept;
```

**Grading:**
| Score | Condition |
|-------|-----------|
| `1.0` | Alias fixed + GROUP BY + output matches |
| `0.7` | Alias fixed + runs but no GROUP BY |
| `0.4` | Runs with partial output |
| `0.0` | Query fails |
| `+0.05` | Bonus for using a CTE (`WITH` clause) |

---

## Reward Function

Dense reward — partial credit given at every step:

```
reward = correctness_score × (1.0 - 0.05 × step_penalty_factor)
```

- `correctness_score` ∈ `[0.0, 1.0]` — from the task-specific grader
- `step_penalty_factor` = `max(0, step_number - 1)` — small discount per step to discourage thrashing
- Final episode score = reward at the step where `done=True`, or last reward if `max_steps` reached

---

## Setup & Usage

### Prerequisites
- Docker (for containerized deployment)
- Python 3.11+ (for local development)

### Local Development

```powershell
# Install dependencies
cd server
pip install -r requirements.txt

# Start the server
uvicorn main:app --host 0.0.0.0 --port 7860
```

### Docker Build & Run

```bash
# Build image
docker build server/ -t sql-debug-env

# Run
docker run -p 7860:7860 sql-debug-env
```

### Testing the API

```powershell
# Health check
Invoke-RestMethod -Uri http://localhost:7860/health

# Reset to easy task
Invoke-RestMethod -Method POST -Uri "http://localhost:7860/reset?task=fix-syntax"

# Submit a fix
$body = '{"query": "SELECT id, name FROM users WHERE active = 1"}'
Invoke-RestMethod -Method POST -Uri http://localhost:7860/step -Body $body -ContentType "application/json"
```

### API Reference

| Method | Path               | Description                                      |
|--------|--------------------|--------------------------------------------------|
| GET    | `/health`          | Returns `{"status": "ok"}`                       |
| POST   | `/reset?task=<t>`  | Reset env, returns initial `SQLObservation`      |
| POST   | `/step`            | Body: `SQLAction`, returns `StepResult`          |
| GET    | `/state`           | Returns current `SQLObservation` (no side effect)|
| GET    | `/docs`            | Interactive Swagger UI                           |

---

## Running inference.py

```powershell
# Required
$env:HF_TOKEN = "hf_your_token_here"

# Optional overrides
$env:API_BASE_URL = "https://router.huggingface.co/v1"
$env:MODEL_NAME   = "Qwen/Qwen2.5-72B-Instruct"
$env:ENV_BASE_URL = "http://localhost:7860"

python inference.py
```

**Expected log format:**
```
[START fix-syntax]
[STEP 1 | reward=0.0000 | done=False]
[STEP 2 | reward=1.0000 | done=True]
[END fix-syntax | final_reward=1.0000]
```

### Required Environment Variables

| Variable       | Description              | Default                              |
|----------------|--------------------------|--------------------------------------|
| `HF_TOKEN`     | Hugging Face API key     | *(required)*                         |
| `API_BASE_URL` | LLM API endpoint         | `https://router.huggingface.co/v1`   |
| `MODEL_NAME`   | Model identifier         | `Qwen/Qwen2.5-72B-Instruct`          |
| `ENV_BASE_URL` | OpenENV server base URL  | `http://localhost:7860`              |

---

## Baseline Scores

Scores obtained by running `inference.py` with `Qwen/Qwen2.5-72B-Instruct` via HF router:

| Task              | Difficulty | Typical Score | Notes                          |
|-------------------|-----------|---------------|--------------------------------|
| `fix-syntax`      | Easy      | 0.90–1.00     | Usually solved in 1–2 steps    |
| `fix-logic`       | Medium    | 0.50–0.80     | Left join insight required     |
| `fix-and-optimize`| Hard      | 0.40–0.70     | CTE approach yields bonus      |

*Scores are stochastic; re-run to reproduce.*

---

## OpenEnv Validation

```bash
openenv validate .
```

Expected output:
```
✅ openenv.yaml found and valid
✅ /reset endpoint responds 200
✅ /step endpoint responds 200
✅ /state endpoint responds 200
✅ /health endpoint responds 200
✅ inference.py found at project root
```

---

## Project Structure

```
OpenENV/
├── server/
│   ├── Dockerfile
│   ├── requirements.txt
│   ├── main.py        # FastAPI server
│   ├── env.py         # Core environment logic
│   ├── graders.py     # Per-task grader functions
│   ├── models.py      # Pydantic models
│   └── tasks/
│       ├── __init__.py
│       ├── task_easy.py
│       ├── task_medium.py
│       └── task_hard.py
├── openenv.yaml       # OpenEnv spec metadata
├── inference.py       # Baseline inference script
├── README.md
└── project.md
```