File size: 5,412 Bytes
76b843b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
---
title: SQL Debugger & Optimizer
emoji: πŸ› οΈ
colorFrom: blue
colorTo: indigo
sdk: docker
app_file: app.py
pinned: false
---

# πŸ› οΈ SQL Debugger & Optimizer β€” OpenEnv Environment

> πŸš€ **NeuroHack β€” OpenEnv Submission**
> A real-world reinforcement learning environment where an AI agent debugs broken SQL queries using **deterministic SQLite execution** β€” no LLM-based scoring.

---

## πŸ“‹ Table of Contents

- [Overview](#overview)
- [Why This Wins](#why-this-wins)
- [Live Demo](#live-demo)
- [Project Structure](#project-structure)
- [Getting Started](#getting-started)
  - [Run Locally](#run-locally)
  - [Docker](#docker)
  - [API Example](#api-example)
- [Environment Details](#environment-details)
  - [Tasks](#tasks)
  - [Reward System](#reward-system)
  - [Performance](#performance)
- [License](#license)

---

## Overview

The **SQL Debugger & Optimizer** is an OpenEnv-compatible reinforcement learning environment where an AI agent receives broken SQL queries and must output corrected versions.

The agent receives:
- πŸ”΄ A **broken SQL query**
- πŸ—‚οΈ The **database schema**
- πŸ“ A **natural language description** of the intended behavior

It must output a **corrected SQL query**, which is then:
1. Executed against a real SQLite database
2. Compared against the reference (correct) query output
3. Scored with a layered reward from `0.0 β†’ 1.0`

---

## Why This Wins

Unlike traditional LLM-evaluated systems:

| Feature | Description |
|--------|-------------|
| βœ… **100% Deterministic Grading** | Real SQLite execution β€” no subjective LLM scoring |
| βœ… **Layered Reward System** | Syntax β†’ Logic β†’ Data β†’ Optimization |
| βœ… **Real-World Bugs** | JOIN errors, N+1 queries, SQL injection vulnerabilities |
| βœ… **Engineering Relevance** | Mirrors production database debugging scenarios |
| βœ… **OpenEnv-Compatible API** | Drop-in `/reset` and `/step` endpoints |

---

## Live Demo

Open the interactive UI at:

```
http://localhost:7860/ui
```

With the UI you can:
- Fix broken SQL queries interactively
- View the corrected SQL output
- See reward scores in real-time
- Track agent performance with graphs

---

## Project Structure

```
sql-debugger-env/
β”œβ”€β”€ app.py                 # FastAPI server β€” /reset, /step, /ui endpoints
β”œβ”€β”€ sql_debugger_env.py    # Core RL environment logic & SQLite execution
β”œβ”€β”€ inference.py           # Agent inference utilities
β”œβ”€β”€ openenv.yaml           # OpenEnv environment specification
β”œβ”€β”€ requirements.txt       # Python dependencies
β”œβ”€β”€ Dockerfile             # Container build configuration
└── README.md              # This file
```

---

## Getting Started

### Run Locally

```bash
pip install -r requirements.txt
python app.py
```

Then open: [http://localhost:7860/ui](http://localhost:7860/ui)

---

### Docker

```bash
# Build the image
docker build -t sql-debugger-env .

# Run the container
docker run -p 7860:7860 sql-debugger-env
```

---

### API Example

The environment exposes an OpenEnv-compatible REST API:

```python
import requests

# 1. Start a new episode
r = requests.post("http://localhost:7860/reset", json={"task": "medium"})
session_id = r.json()["session_id"]
obs = r.json()["observation"]

# 2. Submit a fix action
action = {
    "challenge_id": obs["challenge"]["id"],
    "fixed_sql": "SELECT users.id, orders.total FROM users JOIN orders ON users.id = orders.user_id",
    "explanation": "Fixed JOIN logic β€” was using wrong foreign key",
    "detected_issues": ["wrong_join"]
}

r = requests.post("http://localhost:7860/step", json={
    "session_id": session_id,
    "action": action
})

print(r.json()["reward"])   # e.g. 0.92
```

**Endpoints:**

| Method | Endpoint | Description |
|--------|----------|-------------|
| `POST` | `/reset` | Start a new episode. Accepts `{"task": "easy" \| "medium" \| "hard"}` |
| `POST` | `/step` | Submit a fix. Returns reward, done flag, and next observation |
| `GET`  | `/ui`   | Interactive web interface |

---

## Environment Details

### Tasks

| Difficulty | Bug Types |
|------------|-----------|
| 🟒 **Easy** | Syntax errors (`SELCT`, `FORM`, missing `WHERE`) |
| 🟑 **Medium** | JOIN logic errors, aggregation mistakes |
| πŸ”΄ **Hard** | N+1 query patterns, optimization issues, complex aggregations |

---

### Reward System

Each submitted query is evaluated across multiple components:

| Component | Weight | Description |
|-----------|--------|-------------|
| Syntax Correctness | `0.20` | Query parses and executes without error |
| Row Count Match | `0.25` | Output row count matches reference |
| Column Match | `0.15` | Returned columns match expected schema |
| Data Exact Match | `0.30` | Row-by-row data comparison |
| Security Fix | `0.10` | SQL injection or unsafe patterns resolved |
| Optimization | `0.05` | Query avoids N+1 or redundant scans |
| Explanation Quality | `0.05` | Detected issues and explanation provided |
| **Total** | **1.00** | |

---

### Performance

Benchmarks from the reference agent (`inference.py`):

| Task | Score |
|------|-------|
| Easy | ~0.90 |
| Medium | ~0.90 |
| Hard | ~0.76 |
| **Average** | πŸš€ **~0.85** |

---

## License

This project is licensed under the **MIT License** β€” see [`LICENSE`](LICENSE) for details.

---

<div align="center">
  Built for <strong>NeuroHack</strong> Β· OpenEnv Track Β· 2025
</div>