Spaces:
Sleeping
Download README.md from darshsingh1/sql-debug-env: direct link, hf CLI and curl.
- Browser
- Download file 8.92 kB
-
https://huggingface.co/spaces/darshsingh1/sql-debug-env/resolve/main/README.md
- Command line
-
hf download hf://spaces/darshsingh1/sql-debug-env/README.md
-
curl -L -o README.md https://huggingface.co/spaces/darshsingh1/sql-debug-env/resolve/main/README.md
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
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:
{ "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.
-- 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 >=.
-- 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.
-- 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 graderstep_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 ifmax_stepsreached
Setup & Usage
Prerequisites
- Docker (for containerized deployment)
- Python 3.11+ (for local development)
Local Development
# 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
# Build image
docker build server/ -t sql-debug-env
# Run
docker run -p 7860:7860 sql-debug-env
Testing the API
# 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
# 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
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